Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Retain partial JSON results when later command steps fail (#4584)
Maximilian Roosa6c26c787e7e
diff --git a/.claude/skills/writing-user-outputs/SKILL.md b/.claude/skills/writing-user-outputs/SKILL.mdindex 41f81e1e6..d7939455b 100644--- a/.claude/skills/writing-user-outputs/SKILL.md+++ b/.claude/skills/writing-user-outputs/SKILL.md@@ -105,15 +105,12 @@ only when the pipe is a courier rather than the destination; anything a personreads directly stays on plain anstream, which is what strips color on a pipeand honors `NO_COLOR`.-**`--format=json` answers** go through `crate::output::print_json`, never a-hand-rolled `println!("{}", serde_json::to_string_pretty(&v)?)`. It serializes-pretty with one trailing newline and prints through anstream, so no-`--format=json` surface panics when its consumer stops reading. Before that,-thirty call sites had open-coded those two lines, and whether any one of them-panicked under `| head -3` came down to which `println!` its module happened to-import. `wt switch --format=json` is the one non-caller: it emits its single-result as one compact line (still through anstream's `println!`), because that-is what a shell loop reads.+**`--format=json` answers** use `crate::output::print_json` at the command+handler. Inner operations return typed facts; when work can complete before a+later failure, retain those facts in `CommandFailure<T>`. The outer handler can+use `finish_output` to emit the available result once and return the original+error for main's readable stderr diagnostics and native exit handling. A path+with no result emits nothing; a legitimate JSON null remains a result.**Shell integration functions** (`src/output/global.rs`):diff --git a/docs/src/content/docs/switch.md b/docs/src/content/docs/switch.mdindex 5250d9c69..6ec3eca1c 100644--- a/docs/src/content/docs/switch.md+++ b/docs/src/content/docs/switch.md@@ -290,11 +290,11 @@ Automation:Output formatJSON prints one structured result to stdout once the switch, including any --execute- command, completes. Once arguments are accepted, failures print an object with an error- string. Argument errors use stderr only. Diagnostics and --execute output go to stderr. A- worktree created before a later failure remains in place. Canceling the interactive picker- produces no result. Background hooks run independently of the result. Designed for tool- integration (e.g., Claude Code WorktreeCreate hooks).+ command, completes. A worktree created before a later failure remains in place and is+ included in the result. Read stdout even when the exit status is nonzero. Errors,+ diagnostics, and --execute output go to stderr. Failure before a result exists and+ canceling the interactive picker produce no result. Background hooks run independently of+ the result. Designed for tool integration (e.g., Claude Code WorktreeCreate hooks).[default: text][possible values: text, json]diff --git a/plugins/worktrunk/skills/worktrunk/reference/switch.md b/plugins/worktrunk/skills/worktrunk/reference/switch.mdindex 28b4fc041..7730ef06b 100644--- a/plugins/worktrunk/skills/worktrunk/reference/switch.md+++ b/plugins/worktrunk/skills/worktrunk/reference/switch.md@@ -260,11 +260,11 @@ Automation:Output formatJSON prints one structured result to stdout once the switch, including any --execute- command, completes. Once arguments are accepted, failures print an object with an error- string. Argument errors use stderr only. Diagnostics and --execute output go to stderr. A- worktree created before a later failure remains in place. Canceling the interactive picker- produces no result. Background hooks run independently of the result. Designed for tool- integration (e.g., Claude Code WorktreeCreate hooks).+ command, completes. A worktree created before a later failure remains in place and is+ included in the result. Read stdout even when the exit status is nonzero. Errors,+ diagnostics, and --execute output go to stderr. Failure before a result exists and+ canceling the interactive picker produce no result. Background hooks run independently of+ the result. Designed for tool integration (e.g., Claude Code WorktreeCreate hooks).[default: text][possible values: text, json]diff --git a/skills/worktrunk/reference/switch.md b/skills/worktrunk/reference/switch.mdindex 28b4fc041..7730ef06b 100644--- a/skills/worktrunk/reference/switch.md+++ b/skills/worktrunk/reference/switch.md@@ -260,11 +260,11 @@ Automation:Output formatJSON prints one structured result to stdout once the switch, including any --execute- command, completes. Once arguments are accepted, failures print an object with an error- string. Argument errors use stderr only. Diagnostics and --execute output go to stderr. A- worktree created before a later failure remains in place. Canceling the interactive picker- produces no result. Background hooks run independently of the result. Designed for tool- integration (e.g., Claude Code WorktreeCreate hooks).+ command, completes. A worktree created before a later failure remains in place and is+ included in the result. Read stdout even when the exit status is nonzero. Errors,+ diagnostics, and --execute output go to stderr. Failure before a result exists and+ canceling the interactive picker produce no result. Background hooks run independently of+ the result. Designed for tool integration (e.g., Claude Code WorktreeCreate hooks).[default: text][possible values: text, json]diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 3ce6cab3c..e05d4ddfe 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -445,12 +445,11 @@ pub(crate) struct SwitchArgs {/// Output format////// JSON prints one structured result to stdout once the switch, including- /// any --execute command, completes.- /// Once arguments are accepted, failures print an object with an `error`- /// string. Argument errors use stderr only. Diagnostics and- /// --execute output go to stderr. A worktree created before a later failure- /// remains in place.- /// Canceling the interactive picker produces no result.+ /// any --execute command, completes. A worktree created before a later+ /// failure remains in place and is included in the result. Read stdout+ /// even when the exit status is nonzero. Errors, diagnostics, and+ /// --execute output go to stderr. Failure before a result exists and+ /// canceling the interactive picker produce no result./// Background hooks run independently of the result./// Designed for tool integration (e.g., Claude Code WorktreeCreate hooks).#[arg(long, default_value = "text", help_heading = "Automation")]diff --git a/src/commands/commit.rs b/src/commands/commit.rsindex ba200b05d..21daa3af7 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -20,7 +20,9 @@ pub use worktrunk::config::StageMode;////// `stage_mode` is the *resolved* mode that was actually applied (CLI flag/// merged with config defaults), not the user-supplied flag.+#[derive(serde::Serialize)]pub struct CommitOutcome {+ #[serde(rename = "commit")]pub sha: String,pub message: String,pub stage_mode: StageMode,@@ -141,10 +143,10 @@ impl<'a> CommitGenerator<'a> {show_progress: bool,show_no_squash_note: bool,stage_mode: StageMode,- ) -> anyhow::Result<CommitOutcome> {+ ) -> crate::output::CommandResult<CommitOutcome> {// Fail early if nothing is staged (avoids confusing LLM prompt with empty diff)if !wt.has_staged_changes()? {- anyhow::bail!("Nothing to commit");+ return Err(anyhow::anyhow!("Nothing to commit").into());}if show_progress {@@ -195,19 +197,21 @@ impl<'a> CommitGenerator<'a> {.context("Failed to commit")?;let commit_sha = wt.run_command(&["rev-parse", "HEAD"])?.trim().to_string();- // Display uses `Repository::short_sha`; the JSON payload carries the full SHA.- let commit_hash = wt.repo().short_sha(&commit_sha)?;-+ let outcome = CommitOutcome {+ sha: commit_sha,+ message: commit_message,+ stage_mode,+ };+ // The commit identity is known even if display preparation fails.+ let commit_hash = match wt.repo().short_sha(&outcome.sha) {+ Ok(hash) => hash,+ Err(error) => return Err(crate::output::CommandFailure::with_result(error, outcome)),+ };eprintln!("{}",success_message(cformat!("Committed changes @ <dim>{commit_hash}</>")));-- Ok(CommitOutcome {- sha: commit_sha,- message: commit_message,- stage_mode,- })+ Ok(outcome)}}@@ -219,7 +223,10 @@ impl CommitOptions<'_> {/// --squash` batching post-commit + post-remove + post-switch + post-merge)/// share one announce line; standalone callers (e.g. `wt commit`)/// construct an announcer of their own and flush right after.- pub fn commit(self, announcer: &mut HookAnnouncer<'_>) -> anyhow::Result<CommitOutcome> {+ pub fn commit(+ self,+ announcer: &mut HookAnnouncer<'_>,+ ) -> crate::output::CommandResult<CommitOutcome> {// Use the worktree path from context — this is the target worktree when// --branch is specified, or the current worktree otherwise.let wt = self.ctx.repo.worktree_at(self.ctx.worktree_path);@@ -284,7 +291,11 @@ impl CommitOptions<'_> {// Register post-commit hooks onto the caller's announcer (respects --no-hooks).if self.hooks.run() {let extra_vars = template_vars.as_extra_vars();- announcer.register(self.ctx, HookType::PostCommit, &extra_vars, None)?;+ if let Err(error) =+ announcer.register(self.ctx, HookType::PostCommit, &extra_vars, None)+ {+ return Err(crate::output::CommandFailure::with_result(error, outcome));+ }}Ok(outcome)diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex b9b322d1c..64240d827 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -394,136 +394,170 @@ fn merge_in(};let guidance = super::step::PreApprovedGuidance::Resolved(project_append);- // Handle uncommitted changes (skip if --no-commit) - track whether commit occurred- let committed = if has_committable_changes {- let ctx = env.context(yes);- let mut options = CommitOptions::new(&ctx);- options.target_branch = Some(&target_branch);- options.hooks = commit_hooks;- options.stage_mode = stage_mode;- options.show_no_squash_note = true;- options.guidance = guidance.clone();-- let _ = options.commit(&mut announcer)?;- true // Committed directly- } else {- false // No dirty changes or --no-commit+ // Only confirmed stages are reported on failure. In particular cleanup+ // stays unknown until finish_after_merge records its removal decision.+ #[derive(Default, serde::Serialize)]+ struct MergeProgress<'a> {+ branch: &'a str,+ target: &'a str,+ committed: bool,+ squashed: bool,+ rebased: bool,+ merged: bool,+ removed: Option<bool>,+ }+ let mut progress = MergeProgress {+ branch: ¤t_branch,+ target: &target_branch,+ ..MergeProgress::default()};+ let operation = (|| -> anyhow::Result<()> {+ // Handle uncommitted changes (skip if --no-commit) - track whether commit occurred+ progress.committed = if has_committable_changes {+ let ctx = env.context(yes);+ let mut options = CommitOptions::new(&ctx);+ options.target_branch = Some(&target_branch);+ options.hooks = commit_hooks;+ options.stage_mode = stage_mode;+ options.show_no_squash_note = true;+ options.guidance = guidance.clone();++ let _ = options.commit(&mut announcer).map_err(|failure| {+ progress.committed = failure.result.is_some();+ failure.error+ })?;+ true // Committed directly+ } else {+ false // No dirty changes or --no-commit+ };++ // Squash commits if enabled - track whether squashing occurred.+ // Pass `commit_hooks` (not the shadowed `verify`) so handle_squash gets the+ // --no-hooks vs declined-approval distinction.+ progress.squashed = if squash_enabled {+ matches!(+ super::step::squash::handle_squash_in(+ env,+ Some(&target_branch),+ yes,+ commit_hooks,+ Some(stage_mode),+ &mut announcer,+ guidance,+ )+ .map_err(|failure| {+ progress.squashed = matches!(+ failure.result.as_deref(),+ Some(super::step::SquashResult::Squashed { .. })+ );+ failure.error+ })?,+ super::step::SquashResult::Squashed { .. }+ )+ } else {+ false+ };++ // Rebase onto target - track whether rebasing occurred+ progress.rebased = if rebase {+ // Auto-rebase onto target+ matches!(+ super::step::handle_rebase(repo, Some(&target_branch))?,+ super::step::RebaseResult::Rebased { .. }+ )+ } else {+ // --no-rebase preserves the graph produced by the commit/squash stages+ // above. Merge commits in that graph are valid as long as the target+ // can fast-forward to the final tip.+ let target_ref = format!("refs/heads/{target_branch}");+ let target_sha = repo+ .run_command(&["rev-parse", "--verify", "--end-of-options", &target_ref])?+ .trim()+ .to_string();+ let source_sha = current_wt+ .run_command(&["rev-parse", "--verify", "HEAD"])?+ .trim()+ .to_string();+ if !repo.is_ancestor_by_sha(&target_sha, &source_sha)? {+ return Err(worktrunk::git::GitError::NotRebased {+ target_branch: target_branch.clone(),+ }+ .into());+ }+ false // Rebase skipped; the graph produced by earlier stages remains+ };++ // Run pre-merge checks unless --no-hooks was specified+ // Do this after commit/squash/rebase to validate the final state that will be pushed+ if verify {+ let ctx = env.context(yes);+ let mut vars = TemplateVars::new().with_target(&target_branch);+ if let Some(p) = target_worktree_path.as_deref() {+ vars = vars.with_target_worktree_path(p);+ }+ execute_planned_hook(+ &plan,+ &feature_root,+ &ctx,+ HookType::PreMerge,+ &vars.as_extra_vars(),+ FailureStrategy::FailFast,+ crate::output::pre_hook_display_path(ctx.worktree_path),+ )?;+ }- // Squash commits if enabled - track whether squashing occurred.- // Pass `commit_hooks` (not the shadowed `verify`) so handle_squash gets the- // --no-hooks vs declined-approval distinction.- let squashed = if squash_enabled {- matches!(- super::step::squash::handle_squash_in(- env,+ // Merge to target branch+ let operations = Some(MergeOperations {+ committed: progress.committed,+ squashed: progress.squashed,+ rebased: progress.rebased,+ });+ let pushed = if !ff {+ // Create a merge commit on the target branch via commit-tree + update-ref+ handle_no_ff_merge(repo, Some(&target_branch), operations, ¤t_branch)+ } else {+ // Fast-forward push to target branch+ handle_push(+ repo,Some(&target_branch),+ PushKind::MergeFastForward,+ operations,+ )+ };+ pushed.map_err(|failure| {+ progress.merged = failure.result.is_some();+ failure.error+ })?;+ progress.merged = true;++ let removed = finish_after_merge(+ repo,+ config,+ env,+ &mut announcer,+ FinishAfterMergeArgs {+ current_branch: ¤t_branch,+ source_is_current,+ target_branch: &target_branch,+ target_worktree_path: target_worktree_path.as_deref(),+ remove,+ verify,yes,- commit_hooks,- Some(stage_mode),- &mut announcer,- guidance,- )?,- super::step::SquashResult::Squashed { .. }+ plan: &plan,+ },)- } else {- false- };+ .map_err(|failure| {+ progress.removed = failure.result.map(|result| *result);+ failure.error+ })?;+ progress.removed = Some(removed);- // Rebase onto target - track whether rebasing occurred- let rebased = if rebase {- // Auto-rebase onto target- matches!(- super::step::handle_rebase(repo, Some(&target_branch))?,- super::step::RebaseResult::Rebased { .. }- )- } else {- // --no-rebase preserves the graph produced by the commit/squash stages- // above. Merge commits in that graph are valid as long as the target- // can fast-forward to the final tip.- let target_ref = format!("refs/heads/{target_branch}");- let target_sha = repo- .run_command(&["rev-parse", "--verify", "--end-of-options", &target_ref])?- .trim()- .to_string();- let source_sha = current_wt- .run_command(&["rev-parse", "--verify", "HEAD"])?- .trim()- .to_string();- if !repo.is_ancestor_by_sha(&target_sha, &source_sha)? {- return Err(worktrunk::git::GitError::NotRebased { target_branch }.into());- }- false // Rebase skipped; the graph produced by earlier stages remains- };-- // Run pre-merge checks unless --no-hooks was specified- // Do this after commit/squash/rebase to validate the final state that will be pushed- if verify {- let ctx = env.context(yes);- let mut vars = TemplateVars::new().with_target(&target_branch);- if let Some(p) = target_worktree_path.as_deref() {- vars = vars.with_target_worktree_path(p);- }- execute_planned_hook(- &plan,- &feature_root,- &ctx,- HookType::PreMerge,- &vars.as_extra_vars(),- FailureStrategy::FailFast,- crate::output::pre_hook_display_path(ctx.worktree_path),- )?;- }-- // Merge to target branch- let operations = Some(MergeOperations {- committed,- squashed,- rebased,- });- if !ff {- // Create a merge commit on the target branch via commit-tree + update-ref- handle_no_ff_merge(repo, Some(&target_branch), operations, ¤t_branch)?;- } else {- // Fast-forward push to target branch- handle_push(- repo,- Some(&target_branch),- PushKind::MergeFastForward,- operations,- )?;- }-- let removed = finish_after_merge(- repo,- config,- env,- &mut announcer,- FinishAfterMergeArgs {- current_branch: ¤t_branch,- source_is_current,- target_branch: &target_branch,- target_worktree_path: target_worktree_path.as_deref(),- remove,- verify,- yes,- plan: &plan,- },- )?;-- announcer.flush()?;+ announcer.flush()?;+ Ok(())+ })();if json_mode {- let output = serde_json::json!({- "branch": current_branch,- "target": target_branch,- "committed": committed,- "squashed": squashed,- "rebased": rebased,- "removed": removed,- });- print_json(&output)?;+ print_json(&progress)?;}-- Ok(())+ operation}diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 115a0cfa9..fced20b8f 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -393,7 +393,8 @@ impl AltXRemover {&plan,/* quiet */ true,&mut announcer,- )?;+ )+ .map_err(|failure| failure.error)?;announcer.flush()?;}RemovalPlan::BranchOnly {diff --git a/src/commands/relocate.rs b/src/commands/relocate.rsindex 7b0f4e4d7..a442c8227 100644--- a/src/commands/relocate.rs+++ b/src/commands/relocate.rs@@ -34,8 +34,9 @@ use worktrunk::styling::{};use super::backup;-use super::commit::{CommitGenerator, StageMode};+use super::commit::{CommitGenerator, CommitOutcome, StageMode};use super::worktree::compute_worktree_path;+use crate::output::{CommandFailure, CommandResult};// ============================================================================// Types representing each stage of the pipeline@@ -91,6 +92,7 @@ struct ShellPosition<'a> {}/// A worktree that was successfully relocated.+#[derive(serde::Serialize)]pub struct RelocatedEntry {pub branch: String,pub from: PathBuf,@@ -100,6 +102,7 @@ pub struct RelocatedEntry {/// A worktree that was skipped during validation or execution. `reason` is a/// short stable identifier suitable for JSON / scripting (e.g. `"locked"`,/// `"uncommitted"`, `"unmerged"`, `"target_blocked"`).+#[derive(serde::Serialize)]pub struct SkippedEntry {pub branch: String,pub reason: &'static str,@@ -251,6 +254,16 @@ pub fn gather_candidates(pub struct ValidationResult {pub validated: Vec<ValidatedCandidate>,pub skipped: Vec<SkippedEntry>,+ pub commits: Vec<RelocationCommit>,+}++/// A confirmed auto-commit, independent of whether its worktree later moves.+#[derive(serde::Serialize)]+pub struct RelocationCommit {+ pub branch: String,+ pub path: PathBuf,+ #[serde(flatten)]+ pub outcome: CommitOutcome,}/// Check each candidate for locked/dirty state and optionally auto-commit.@@ -259,6 +272,8 @@ pub struct ValidationResult {/// the approved project-level append fragment added to each auto-commit/// prompt. Resolved once upfront by the caller so per-worktree commits share/// the same approved value rather than each running its own approval gate.+/// Confirmed auto-commits remain in the returned result if a later check or+/// commit fails; validation does not claim those worktrees have moved.pub fn validate_candidates(repo: &Repository,config: &UserConfig,@@ -266,115 +281,142 @@ pub fn validate_candidates(auto_commit: bool,repo_path: &Path,project_append: Option<&str>,-) -> anyhow::Result<ValidationResult> {+) -> CommandResult<ValidationResult> {let mut validated = Vec::new();let mut skipped: Vec<SkippedEntry> = Vec::new();+ let mut commits = Vec::new();- for candidate in candidates {- let branch = candidate.branch();+ let validation = (|| -> anyhow::Result<()> {+ 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.push(SkippedEntry {- branch: branch.to_string(),- reason: "locked",- });- continue;- }+ // 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.push(SkippedEntry {+ branch: branch.to_string(),+ reason: "locked",+ });+ continue;+ }- let is_main = paths_match(&candidate.wt.path, repo_path);-- // Check dirty.- //- // `git worktree move` carries modified-tracked and untracked files- // along with the worktree, so for linked worktrees we don't need to- // require a clean state. The main worktree is different: it can't be- // moved with `git worktree move`, and the fallback path runs- // `git switch <default-branch>` which refuses to switch over- // uncommitted changes — so we still skip dirty main worktrees unless- // `--commit` was passed.- let worktree = repo.worktree_at(&candidate.wt.path);- if worktree.is_dirty()? && (auto_commit || is_main) {- if auto_commit {- // An unresolved conflict can't be committed by anyone until- // the user resolves it by hand — the same class of blocker as- // a locked worktree, so skip this one and carry on with the- // rest rather than failing the whole run. Checked before the- // progress line so nothing announces a commit that won't- // happen. `worktree.stage` below refuses the same state; this- // is the policy choice of skip over abort, not the guard.- let unmerged = worktree.unmerged_paths()?;- if !unmerged.is_empty() {+ let is_main = paths_match(&candidate.wt.path, repo_path);++ // Check dirty.+ //+ // `git worktree move` carries modified-tracked and untracked files+ // along with the worktree, so for linked worktrees we don't need to+ // require a clean state. The main worktree is different: it can't be+ // moved with `git worktree move`, and the fallback path runs+ // `git switch <default-branch>` which refuses to switch over+ // uncommitted changes — so we still skip dirty main worktrees unless+ // `--commit` was passed.+ let worktree = repo.worktree_at(&candidate.wt.path);+ if worktree.is_dirty()? && (auto_commit || is_main) {+ if auto_commit {+ // An unresolved conflict can't be committed by anyone until+ // the user resolves it by hand — the same class of blocker as+ // a locked worktree, so skip this one and carry on with the+ // rest rather than failing the whole run. Checked before the+ // progress line so nothing announces a commit that won't+ // happen. `worktree.stage` below refuses the same state; this+ // is the policy choice of skip over abort, not the guard.+ let unmerged = worktree.unmerged_paths()?;+ if !unmerged.is_empty() {+ eprintln!(+ "{}",+ warning_message(cformat!(+ "Skipping <bold>{branch}</> ({})",+ format_unresolved_conflicts(unmerged.len())+ ))+ );+ eprintln!("{}", format_with_gutter(&unmerged.join("\n"), None));+ skipped.push(SkippedEntry {+ branch: branch.to_string(),+ reason: "unmerged",+ });+ continue;+ }+ eprintln!(+ "{}",+ progress_message(cformat!("Committing changes in <bold>{branch}</>..."))+ );+ // Stage all changes. `stage` refuses an unmerged index first —+ // `git add -A` over an unresolved conflict would otherwise+ // commit the `<<<<<<<` markers.+ worktree.stage(StageMode::All)?;+ // Commit using shared pipeline+ let project_id = repo.project_identifier().ok();+ let commit_config = config.commit_generation(project_id.as_ref());+ let committed = CommitGenerator::new(&commit_config, project_append)+ .commit_staged_changes(+ &worktree,+ false, // show_progress - already showing "Committing changes in..."+ false, // show_no_squash_note+ StageMode::All, // resolved staging mode applied above+ );+ let (outcome, error) = match committed {+ Ok(outcome) => (Some(outcome), None),+ Err(failure) => (failure.result.map(|result| *result), Some(failure.error)),+ };+ if let Some(outcome) = outcome {+ commits.push(RelocationCommit {+ branch: branch.to_string(),+ path: candidate.wt.path.clone(),+ outcome,+ });+ }+ if let Some(error) = error {+ return Err(error);+ }+ } else {+ // is_main without --commiteprintln!("{}",warning_message(cformat!(- "Skipping <bold>{branch}</> ({})",- format_unresolved_conflicts(unmerged.len())+ "Skipping <bold>{branch}</> (uncommitted changes in main worktree)"+ ))+ );+ eprintln!(+ "{}",+ hint_message(cformat!(+ "To auto-commit changes before relocating, use <underline>--commit</>")));- eprintln!("{}", format_with_gutter(&unmerged.join("\n"), None));skipped.push(SkippedEntry {branch: branch.to_string(),- reason: "unmerged",+ reason: "uncommitted",});continue;}- eprintln!(- "{}",- progress_message(cformat!("Committing changes in <bold>{branch}</>..."))- );- // Stage all changes. `stage` refuses an unmerged index first —- // `git add -A` over an unresolved conflict would otherwise- // commit the `<<<<<<<` markers.- worktree.stage(StageMode::All)?;- // Commit using shared pipeline- let project_id = repo.project_identifier().ok();- let commit_config = config.commit_generation(project_id.as_ref());- CommitGenerator::new(&commit_config, project_append).commit_staged_changes(- &worktree,- false, // show_progress - already showing "Committing changes in..."- false, // show_no_squash_note- StageMode::None, // already staged above- )?;- } else {- // is_main without --commit- eprintln!(- "{}",- warning_message(cformat!(- "Skipping <bold>{branch}</> (uncommitted changes in main worktree)"- ))- );- eprintln!(- "{}",- hint_message(cformat!(- "To auto-commit changes before relocating, use <underline>--commit</>"- ))- );- skipped.push(SkippedEntry {- branch: branch.to_string(),- reason: "uncommitted",- });- continue;}++ validated.push(ValidatedCandidate {+ wt: candidate.wt,+ expected_path: candidate.expected_path,+ is_main,+ });}- validated.push(ValidatedCandidate {- wt: candidate.wt,- expected_path: candidate.expected_path,- is_main,- });+ Ok(())+ })();+ let result = ValidationResult {+ validated,+ skipped,+ commits,+ };+ match validation {+ Ok(()) => Ok(result),+ Err(error) => Err(CommandFailure::with_result(error, result)),}-- Ok(ValidationResult { validated, skipped })}// ============================================================================@@ -658,14 +700,13 @@ impl<'a> RelocationExecutor<'a> {let msg = cformat!("Relocated <bold>{branch}</>: {src_display} → {dest_display}");eprintln!("{}", success_message(msg));- follow_shell(shell, idx, &src_path, &dest_path)?;-self.moved.insert(idx);self.relocated_entries.push(RelocatedEntry {branch,- from: src_path,- to: dest_path,+ from: src_path.clone(),+ to: dest_path.clone(),});+ follow_shell(shell, idx, &src_path, &dest_path)?;Ok(())}@@ -779,14 +820,17 @@ impl<'a> RelocationExecutor<'a> {let msg = cformat!("Relocated <bold>{branch}</>: {src_display} → {dest_display}");eprintln!("{}", success_message(msg));- let (from, to) = (&temp.original_path, &candidate.expected_path);- follow_shell(shell, temp.index, from, to)?;-self.relocated_entries.push(RelocatedEntry {branch: branch.to_string(),- from: temp.original_path,+ from: temp.original_path.clone(),to: candidate.expected_path.clone(),});+ follow_shell(+ shell,+ temp.index,+ &temp.original_path,+ &candidate.expected_path,+ )?;}Ok(())diff --git a/src/commands/remove.rs b/src/commands/remove.rsindex a8b7a5195..8f5eff683 100644--- a/src/commands/remove.rs+++ b/src/commands/remove.rs@@ -19,7 +19,10 @@ use worktrunk::git::{use worktrunk::styling::{eprintln, info_message};use crate::cli::{RemoveArgs, SwitchFormat};-use crate::output::{BackgroundFallbackMode, RemovalExecution, handle_remove_output, print_json};+use crate::output::{+ BackgroundFallbackMode, CommandFailure, CommandResult, RemovalExecution, handle_remove_output,+ print_json,+};use super::hook_plan::{ApprovedHookPlan, HookPlanBuilder};use super::hooks::HookAnnouncer;@@ -377,179 +380,178 @@ fn maybe_reap_result(result: &RemovalPlan, reap_enabled: bool) {pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {let json_mode = args.format == SwitchFormat::Json;let verify = args.hooks.resolve();- UserConfig::load()- .context("Failed to load config")- .and_then(|config| {- let repo = Repository::current().context("Failed to remove worktree")?;-- // CLI flags override config; otherwise fall through to [remove] delete-branch- // (defaults to true).- let project = repo.project_identifier().ok();- let cli_override = flag_pair(args.delete_branch, args.no_delete_branch);- let delete_branch =- cli_override.unwrap_or_else(|| config.remove(project.as_ref()).delete_branch());-- // Validate conflicting flags- if !delete_branch && args.force_delete {- return Err(worktrunk::git::GitError::Other {+ let config = UserConfig::load().context("Failed to load config")?;+ let repo = Repository::current().context("Failed to remove worktree")?;++ // CLI flags override config; otherwise fall through to [remove] delete-branch+ // (defaults to true).+ let project = repo.project_identifier().ok();+ let cli_override = flag_pair(args.delete_branch, args.no_delete_branch);+ let delete_branch =+ cli_override.unwrap_or_else(|| config.remove(project.as_ref()).delete_branch());++ // Validate conflicting flags+ if !delete_branch && args.force_delete {+ return Err(worktrunk::git::GitError::Other {message: "Cannot use --force-delete with delete-branch=false (set via --no-delete-branch or [remove] delete-branch = false)".into(),}.into());- }+ }- // `--reap` relies on per-process cwd discovery (`lsof`/`ps`), which- // has no cheap Windows equivalent — reject it there rather than- // silently no-op.- #[cfg(not(unix))]- if args.reap {- anyhow::bail!("--reap is not supported on Windows");- }+ // `--reap` relies on per-process cwd discovery (`lsof`/`ps`), which+ // has no cheap Windows equivalent — reject it there rather than+ // silently no-op.+ #[cfg(not(unix))]+ if args.reap {+ return Err(anyhow::anyhow!("--reap is not supported on Windows"));+ }- // Helper: build and approve, once, the frozen hook plan the- // removal will run. Every hook (`pre-remove` / `post-remove` per- // removed worktree, `post-switch` per post-removal destination) is- // selected from the invoking worktree's `.config/wt.toml` — the- // worktree `wt remove` ran in. `!verify` (`--no-hooks`) or a- // declined prompt yields an empty plan — every executor then runs- // no project hooks.- let approve_remove = |removed_worktree_paths: &[&Path],- destination_paths: &[&Path],- yes: bool|- -> anyhow::Result<ApprovedHookPlan> {- if !verify {- return Ok(ApprovedHookPlan::empty());- }- // Non-fatal: a worktree with no project hooks must remove even- // when the project identifier can't be resolved (the plan ends- // up empty and `approve` never needs it). Matches the pre-plan- // behaviour where the empty-batch fast path ran first.- let project_id = repo.project_identifier().ok();- let pid = project_id.as_ref();- let project_config = repo.load_project_config()?;- let mut builder = HookPlanBuilder::new(project_config.as_ref(), &config, pid);- for &wt_path in removed_worktree_paths {- builder.add(wt_path, &[HookType::PreRemove, HookType::PostRemove]);- }- let mut seen_dests = std::collections::HashSet::new();- for &dest in destination_paths {- if !seen_dests.insert(dest) {- continue;- }- builder.add(dest, &[HookType::PostSwitch]);- }- match builder.finish().approve(pid, yes)? {- Some(plan) => Ok(plan),- None => {- eprintln!(- "{}",- info_message("Commands declined, continuing removal without hooks")- );- Ok(ApprovedHookPlan::empty())- }- }- };-- // No argument means `@`, resolved like any other selector.- let branches = if args.branches.is_empty() {- vec!["@".to_string()]- } else {- args.branches- };-- // Validate ALL first, then approve, then execute- let plans = validate_remove_targets(- &repo,- &config,- branches,- !delete_branch,- args.force_delete,- args.force,- );-- if !plans.has_valid_plans() {- anyhow::bail!("");+ // Helper: build and approve, once, the frozen hook plan the+ // removal will run. Every hook (`pre-remove` / `post-remove` per+ // removed worktree, `post-switch` per post-removal destination) is+ // selected from the invoking worktree's `.config/wt.toml` — the+ // worktree `wt remove` ran in. `!verify` (`--no-hooks`) or a+ // declined prompt yields an empty plan — every executor then runs+ // no project hooks.+ let approve_remove = |removed_worktree_paths: &[&Path],+ destination_paths: &[&Path],+ yes: bool|+ -> anyhow::Result<ApprovedHookPlan> {+ if !verify {+ return Ok(ApprovedHookPlan::empty());+ }+ // Non-fatal: a worktree with no project hooks must remove even+ // when the project identifier can't be resolved (the plan ends+ // up empty and `approve` never needs it). Matches the pre-plan+ // behaviour where the empty-batch fast path ran first.+ let project_id = repo.project_identifier().ok();+ let pid = project_id.as_ref();+ let project_config = repo.load_project_config()?;+ let mut builder = HookPlanBuilder::new(project_config.as_ref(), &config, pid);+ for &wt_path in removed_worktree_paths {+ builder.add(wt_path, &[HookType::PreRemove, HookType::PostRemove]);+ }+ let mut seen_dests = std::collections::HashSet::new();+ for &dest in destination_paths {+ if !seen_dests.insert(dest) {+ continue;}-- // Early exit for benchmarking time-to-first-output- if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {- return Ok(());+ builder.add(dest, &[HookType::PostSwitch]);+ }+ match builder.finish().approve(pid, yes)? {+ Some(plan) => Ok(plan),+ None => {+ eprintln!(+ "{}",+ info_message("Commands declined, continuing removal without hooks")+ );+ Ok(ApprovedHookPlan::empty())}+ }+ };- // Approve hooks (only if we have valid plans): `pre-remove` /- // `post-remove` anchored at each removed worktree and- // `post-switch` at each destination, all selected from the- // invoking worktree's config — see `approve_remove` above.- // (`destination_targets` is mostly the primary worktree- // repeated; the helper dedups destinations by path.)- let all_plans = || {- plans- .others- .iter()- .chain(&plans.branch_only)- .chain(plans.current.iter())- };- let removed_targets: Vec<&Path> =- all_plans().filter_map(|r| r.removed_worktree_path()).collect();- let destination_targets: Vec<&Path> =- all_plans().filter_map(|r| r.destination_path()).collect();- let plan = approve_remove(&removed_targets, &destination_targets, yes)?;-- // Execute all validated plans: others first, branch-only next, current last- let show_branch =- plans.others.len() + plans.branch_only.len() + plans.current.iter().len() > 1;- let run = |result: &RemovalPlan| -> anyhow::Result<BranchFate> {- maybe_reap_result(result, args.reap);- let mut announcer = HookAnnouncer::new(&repo, show_branch);- let fate = handle_remove_output(- result,- removal_execution(args.foreground),- ForegroundStdin::Inherit,- &plan,- false,- &mut announcer,- )?;- announcer.flush()?;- Ok(fate)- };- let mut failed = !plans.errors.is_empty();- let mut json_items = Vec::new();- let mut interrupted = None;- for result in all_plans() {- match run(result) {- Ok(fate) => {- if json_mode {- json_items.push(result.to_json(fate));- }- }- Err(e) => {- if let Some(signal) = e.interrupt_signal() {- interrupted = Some(signal);- break;- }- crate::print_command_error(&e);- failed = true;- }- }- }+ // No argument means `@`, resolved like any other selector.+ let branches = if args.branches.is_empty() {+ vec!["@".to_string()]+ } else {+ args.branches+ };- if json_mode {- print_json(&json_items)?;- }- if let Some(signal) = interrupted {- return Err(WorktrunkError::Interrupted { signal, hint: None }.into());- }+ // Validate ALL first, then approve, then execute+ let plans = validate_remove_targets(+ &repo,+ &config,+ branches,+ !delete_branch,+ args.force_delete,+ args.force,+ );- // Fire-and-forget repo-wide internal cleanup (stale trash +- // orphaned fsmonitor daemons) — runs after primary output so- // it never delays the user-visible progress/success messages.- super::process::run_internal_sweep(&repo);+ let mut failed = !plans.errors.is_empty();+ if !plans.has_valid_plans() {+ return Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into());+ }++ // Early exit for benchmarking time-to-first-output+ if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {+ return Ok(());+ }- if failed {- anyhow::bail!("");+ // Approve hooks (only if we have valid plans): `pre-remove` /+ // `post-remove` anchored at each removed worktree and+ // `post-switch` at each destination, all selected from the+ // invoking worktree's config — see `approve_remove` above.+ // (`destination_targets` is mostly the primary worktree+ // repeated; the helper dedups destinations by path.)+ let all_plans = || {+ plans+ .others+ .iter()+ .chain(&plans.branch_only)+ .chain(plans.current.iter())+ };+ let removed_targets: Vec<&Path> = all_plans()+ .filter_map(|r| r.removed_worktree_path())+ .collect();+ let destination_targets: Vec<&Path> =+ all_plans().filter_map(|r| r.destination_path()).collect();+ let plan = approve_remove(&removed_targets, &destination_targets, yes)?;++ // Execute all validated plans: others first, branch-only next, current last+ let show_branch = plans.others.len() + plans.branch_only.len() + plans.current.iter().len() > 1;+ let run = |result: &RemovalPlan| -> CommandResult<BranchFate> {+ maybe_reap_result(result, args.reap);+ let mut announcer = HookAnnouncer::new(&repo, show_branch);+ let fate = handle_remove_output(+ result,+ removal_execution(args.foreground),+ ForegroundStdin::Inherit,+ &plan,+ false,+ &mut announcer,+ )?;+ announcer+ .flush()+ .map_err(|error| CommandFailure::with_result(error, fate))?;+ Ok(fate)+ };+ let mut json_items = Vec::new();+ let mut interrupted = None;+ for result in all_plans() {+ let (fate, error) = match run(result) {+ Ok(fate) => (Some(fate), None),+ Err(failure) => (failure.result.map(|result| *result), Some(failure.error)),+ };+ if json_mode && let Some(fate) = fate {+ json_items.push(result.to_json(fate));+ }+ if let Some(error) = error {+ if error.interrupt_signal().is_some() {+ interrupted = Some(error);+ break;}+ crate::print_command_error(&error);+ failed = true;+ }+ }- Ok(())- })+ if json_mode {+ print_json(&json_items)?;+ }+ if let Some(error) = interrupted {+ return Err(error);+ }++ // Fire-and-forget repo-wide internal cleanup (stale trash ++ // orphaned fsmonitor daemons) — runs after primary output so+ // it never delays the user-visible progress/success messages.+ super::process::run_internal_sweep(&repo);++ if failed {+ return Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into());+ }++ Ok(())}#[cfg(test)]diff --git a/src/commands/step/commit.rs b/src/commands/step/commit.rsindex 1d2b1d264..e9f355a33 100644--- a/src/commands/step/commit.rs+++ b/src/commands/step/commit.rs@@ -6,10 +6,11 @@ use worktrunk::config::UserConfig;use worktrunk::styling::println;use super::super::command_approval::{approve_or_skip, resolve_template_for_preview};-use super::super::commit::{CommitOptions, CommitOutcome, HookGate, StageMode};+use super::super::commit::{CommitOptions, HookGate, StageMode};use super::super::context::CommandEnv;use super::super::hooks::HookAnnouncer;use super::shared::print_dry_run;+use crate::output::{CommandFailure, finish_output};/// Handle `wt step commit` command///@@ -21,13 +22,14 @@ pub fn step_commit(stage: Option<StageMode>,show_prompt: bool,dry_run: bool,-) -> anyhow::Result<Option<CommitOutcome>> {+ format: crate::cli::SwitchFormat,+) -> anyhow::Result<()> {// --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(branch.as_deref(), stage, dry_run, yes)?;- return Ok(None);+ return Ok(());}// Load config once, run LLM setup prompt, then reuse config@@ -57,9 +59,13 @@ pub fn step_commit(options.show_no_squash_note = false;let mut announcer = HookAnnouncer::new(ctx.repo, false);- let outcome = options.commit(&mut announcer)?;- announcer.flush()?;- Ok(Some(outcome))+ let outcome = options+ .commit(&mut announcer)+ .and_then(|result| match announcer.flush() {+ Ok(()) => Ok(result),+ Err(error) => Err(CommandFailure::with_result(error, result)),+ });+ finish_output(outcome, format == crate::cli::SwitchFormat::Json)}/// Handle `wt step commit` in `--show-prompt` or `--dry-run` mode.diff --git a/src/commands/step/copy_ignored.rs b/src/commands/step/copy_ignored.rsindex d87f09957..506563814 100644--- a/src/commands/step/copy_ignored.rs+++ b/src/commands/step/copy_ignored.rs@@ -95,7 +95,7 @@ pub fn step_copy_ignored("entries": Vec::<serde_json::Value>::new(),});insert_empty_counts(&mut payload);- print_json(&payload)?;+ return print_json(&payload);} else {eprintln!("{}",@@ -128,7 +128,7 @@ pub fn step_copy_ignored(if !dry_run {insert_empty_counts(&mut payload);}- print_json(&payload)?;+ return print_json(&payload);} else {eprintln!("{}",@@ -165,7 +165,7 @@ pub fn step_copy_ignored(if !dry_run {insert_empty_counts(&mut payload);}- print_json(&payload)?;+ return print_json(&payload);} else {eprintln!("{}", info_message("No matching files to copy"));}@@ -184,8 +184,7 @@ pub fn step_copy_ignored("to": dest_path,"entries": entries,});- print_json(&payload)?;- return Ok(());+ return print_json(&payload);}// The preview is primary output, so it goes to stdout.println!(@@ -210,34 +209,38 @@ pub fn step_copy_ignored(Progress::start("Copying")};- for (src_entry, is_dir) in &entries_to_copy {- let relative = src_entry- .strip_prefix(&source_path)- .unwrap_or(src_entry.as_path());- let dest_entry = dest_path.join(relative);+ let copying = (|| -> anyhow::Result<()> {+ for (src_entry, is_dir) in &entries_to_copy {+ let relative = src_entry+ .strip_prefix(&source_path)+ .unwrap_or(src_entry.as_path());+ let dest_entry = dest_path.join(relative);- if *is_dir {- // A pure copy deletes no source, so the skip count has nothing to guard.- let _skipped =- copy_dir_recursive(src_entry, &dest_entry, Some(&dest_path), force, &progress)- .with_context(|| {- format!("copying directory {}", format_path_for_display(relative))+ if *is_dir {+ // A pure copy deletes no source, so the skip count has nothing to guard.+ let _skipped =+ copy_dir_recursive(src_entry, &dest_entry, Some(&dest_path), force, &progress)+ .with_context(|| {+ format!("copying directory {}", format_path_for_display(relative))+ })?;+ } else {+ if let Some(parent) = dest_entry.parent() {+ fs::create_dir_all(parent).with_context(|| {+ format!(+ "creating directory for {}",+ format_path_for_display(relative)+ )})?;- } 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, data)) = copy_leaf(src_entry, &dest_entry, Some(&dest_path), force)?- {- progress.record(bytes, data);+ }+ if let Some((bytes, data)) =+ copy_leaf(src_entry, &dest_entry, Some(&dest_path), force)?+ {+ progress.record(bytes, data);+ }}}- }+ Ok(())+ })();let (copied_count, copied_bytes) = progress.totals();let (reflinked, written) = progress.copy_split();progress.finish();@@ -263,7 +266,9 @@ pub fn step_copy_ignored("written": written,});print_json(&payload)?;+ return copying;} else {+ copying?;// Show summarylet file_word = if copied_count == 1 { "file" } else { "files" };eprintln!(diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rsindex d2d4a941b..29fedaffb 100644--- a/src/commands/step/prune.rs+++ b/src/commands/step/prune.rs@@ -17,7 +17,9 @@//! command's cancellation latch also stops admission before an interrupted//! sibling's cleanup completes. The//! current worktree is removed last, after the fan-out, because its removal-//! cd's the shell to the primary.+//! cd's the shell to the primary. Completed removals travel with execution+//! errors through the worker channel, so aborting a scan or removal preserves+//! confirmed results in the final command response.use crate::commands::command_executor::ForegroundStdin;@@ -43,7 +45,7 @@ use worktrunk::styling::{};use worktrunk::trace::Span;-use crate::output::print_json;+use crate::output::{CommandFailure, CommandResult, print_json};use super::super::hook_plan::{ApprovedHookPlan, HookPlan, HookPlanBuilder};use super::super::hooks::HookAnnouncer;@@ -287,10 +289,9 @@ fn removal_needs_write(kind: CandidateKind, plan: &RemovalPlan, ctx: &RemovalCon}}-/// Try to remove a candidate immediately. Returns `Ok(Some(fate))` if removed-/// — the executed outcome the summary counts and `--format=json` names —-/// `Ok(None)` if the removal turned out to be a no-op, `Err` on execution-/// error.+/// Try to remove a candidate immediately. A confirmed removal returns its fate,+/// including through a late hook failure; a successful no-op returns `None`.+/// The caller carries completion and execution error together.////// `plan` is the scan-time `prepare_worktree_removal` result from/// [`check_one`]; only `StaleDetached` candidates arrive without one (their@@ -303,7 +304,7 @@ fn try_remove(candidate: &Candidate,plan: Option<RemovalPlan>,ctx: &RemovalContext<'_>,-) -> anyhow::Result<Option<BranchFate>> {+) -> CommandResult<Option<BranchFate>> {let _span = Span::new(format!("prune-remove:{}", candidate.label));// Cancellation may arrive while this admitted job waits for terminal output.@@ -358,22 +359,31 @@ fn try_remove(} else {ForegroundStdin::Closed};- let fate = handle_remove_output(&plan, execution, stdin, ctx.hook_plan, true, &mut announcer)?;- announcer.flush()?;- let branch_deleted = fate.deleted();- // A branch-only candidate that kept its branch removed nothing at all —- // unless the removal pruned a stale worktree entry, a removal worth- // counting. Excluding the no-op keeps the summary and JSON honest when a- // concurrent writer advanced an orphan branch between scan and delete- // (the per-item retention warning has already told the user).- if !branch_deleted- && let RemovalPlan::BranchOnly {- prune_entry: None, ..- } = plan- {- return Ok(None);- }- Ok(Some(fate))+ // A branch-only candidate whose ref was not deleted removed nothing,+ // unless it also pruned a stale worktree entry. Apply that same rule to+ // successful outcomes and confirmed partial outcomes carried by errors.+ let completed_fate = |fate: BranchFate| {+ if !fate.deleted()+ && matches!(+ plan,+ RemovalPlan::BranchOnly {+ prune_entry: None,+ ..+ }+ )+ {+ None+ } else {+ Some(fate)+ }+ };+ let fate = handle_remove_output(&plan, execution, stdin, ctx.hook_plan, true, &mut announcer)+ .map_err(|failure| failure.map_result(completed_fate))?;+ let completed = completed_fate(fate);+ announcer+ .flush()+ .map_err(|error| CommandFailure::with_result(error, completed))?;+ Ok(completed)}/// One candidate skipped because its project hooks aren't yet approved.@@ -856,8 +866,7 @@ fn render_dry_run(})}).collect();- print_json(&items)?;- return Ok(());+ return print_json(&items);}// The human preview mirrors the `--format=json` plan above (the worktrees@@ -1203,194 +1212,197 @@ pub fn step_prune(// `removal_needs_write`). The current worktree is the one exception to// the fan-out: its removal cd's to the primary, so defer it until last.let scan_span = Span::new("prune-scan");- let (removed, deferred_current) = std::thread::scope(- |s| -> anyhow::Result<(Vec<Candidate>, Option<DeferredCurrent>)> {- let (tx, rx) = chan::unbounded::<(usize, anyhow::Result<CheckOutcome>)>();- // Pre-shadow with references so `move` on s.spawn moves only `tx`- // (so it's dropped when the spawn ends and `rx` can terminate),- // while the heavy state stays borrowed and remains usable by the- // main thread.- let repo_ref = &repo;- let snapshot_ref = &snapshot;- let check_items_ref = &check_items;- let integration_target_ref = integration_target.as_str();- let current_path_ref = current_root.as_path();- let ref_write_times_ref = &ref_write_times;- s.spawn(move || {- check_items_ref- .par_iter()- .enumerate()- .for_each(|(idx, item)| {- let outcome = check_one(- item,- repo_ref,- snapshot_ref,- integration_target_ref,- worktrees,- current_path_ref,- min_age_duration,- ref_write_times_ref,- now_secs,- );- let _ = tx.send((idx, outcome));- });- });+ let (removed, deferred_current, mut first_err) = std::thread::scope(|s| {+ let (tx, rx) = chan::unbounded::<(usize, anyhow::Result<CheckOutcome>)>();+ // Pre-shadow with references so `move` on s.spawn moves only `tx`+ // (so it's dropped when the spawn ends and `rx` can terminate),+ // while the heavy state stays borrowed and remains usable by the+ // main thread.+ let repo_ref = &repo;+ let snapshot_ref = &snapshot;+ let check_items_ref = &check_items;+ let integration_target_ref = integration_target.as_str();+ let current_path_ref = current_root.as_path();+ let ref_write_times_ref = &ref_write_times;+ s.spawn(move || {+ check_items_ref+ .par_iter()+ .enumerate()+ .for_each(|(idx, item)| {+ let outcome = check_one(+ item,+ repo_ref,+ snapshot_ref,+ integration_target_ref,+ worktrees,+ current_path_ref,+ min_age_duration,+ ref_write_times_ref,+ now_secs,+ );+ let _ = tx.send((idx, outcome));+ });+ });- // Removal workers, sized like the scan's rayon pool so- // `RAYON_NUM_THREADS=1` serializes removals too (deterministic- // output for tests). Results flow back on `done_rx`; the channel- // closes once every worker has drained the job queue and exited,- // so draining it below also waits out all in-flight printing.- let (job_tx, job_rx) = chan::unbounded::<RemovalJob>();- let (done_tx, done_rx) =- chan::unbounded::<(Candidate, anyhow::Result<Option<BranchFate>>)>();- let abort_ref = &abort;- let removal_ctx_ref = &removal_ctx;- // Empty check_items → zero workers, correctly: no jobs can queue.- let workers = rayon::current_num_threads().min(check_items.len());- for _ in 0..workers {- let job_rx = job_rx.clone();- let done_tx = done_tx.clone();- s.spawn(move || {- for job in job_rx {- match job {- RemovalJob::Remove { candidate, plan } => {- // Skip (not print, not remove) once a sibling- // failed; queued skip lines below still print- // — they were discovered before the failure.- if abort_ref.load(Ordering::Relaxed) {- continue;- }- let result = try_remove(&candidate, *plan, removal_ctx_ref)- .with_context(|| candidate.removal_context())- .inspect_err(|error| abort_removals(error, abort_ref));- if done_tx.send((candidate, result)).is_err() {- return;- }+ // Removal workers, sized like the scan's rayon pool so+ // `RAYON_NUM_THREADS=1` serializes removals too (deterministic+ // output for tests). Results flow back on `done_rx`; the channel+ // closes once every worker has drained the job queue and exited,+ // so draining it below also waits out all in-flight printing.+ let (job_tx, job_rx) = chan::unbounded::<RemovalJob>();+ let (done_tx, done_rx) =+ chan::unbounded::<(Candidate, CommandResult<Option<BranchFate>>)>();+ let abort_ref = &abort;+ let removal_ctx_ref = &removal_ctx;+ // Empty check_items → zero workers, correctly: no jobs can queue.+ let workers = rayon::current_num_threads().min(check_items.len());+ for _ in 0..workers {+ let job_rx = job_rx.clone();+ let done_tx = done_tx.clone();+ s.spawn(move || {+ for job in job_rx {+ match job {+ RemovalJob::Remove { candidate, plan } => {+ // Skip (not print, not remove) once a sibling+ // failed; queued skip lines below still print+ // — they were discovered before the failure.+ if abort_ref.load(Ordering::Relaxed) {+ continue;}- RemovalJob::PrintSkip(line) => {- // Hold the read side so a skip line can't- // land inside a write-side removal's- // exclusive output window (spinner).- let _read = removal_ctx_ref- .output_lock- .read()- .unwrap_or_else(|e| e.into_inner());- eprintln!("{line}");+ let result = try_remove(&candidate, *plan, removal_ctx_ref).map_err(+ |mut failure| {+ failure.error =+ failure.error.context(candidate.removal_context());+ abort_removals(&failure.error, abort_ref);+ failure+ },+ );+ if done_tx.send((candidate, result)).is_err() {+ return;}}+ RemovalJob::PrintSkip(line) => {+ // Hold the read side so a skip line can't+ // land inside a write-side removal's+ // exclusive output window (spinner).+ let _read = removal_ctx_ref+ .output_lock+ .read()+ .unwrap_or_else(|e| e.into_inner());+ eprintln!("{line}");+ }}- });- }- drop(job_rx);- drop(done_tx);-- let mut deferred_current: Option<DeferredCurrent> = None;- for (idx, outcome) in &rx {- // A check error fails the whole run — flip `abort` so the- // workers drain their queue without executing more removals- // (whose results this early return would silently drop).- let outcome = outcome- .context("checking branch integration")- .inspect_err(|error| abort_removals(error, abort_ref))?;- let Some(_reason) = outcome.reason else {- continue;- };- if !outcome.removable {- continue;}- let item = &check_items[idx];- let (label, branch, path, kind, _suffix) =- candidate_fields(item, &repo, worktrees, ¤t_root);- if let Some(age) = outcome.age- && age < min_age_duration- {- let line = info_message(cformat!(- "Skipped <bold>{label}</> (younger than {min_age})"- ))- .to_string();- let _ = job_tx.send(RemovalJob::PrintSkip(line));- skipped_young.push(label);- continue;- }- // Keyed on the plan, not the candidate's shape: only a- // worktree removal runs `pre-remove`/`post-remove`. Branch-- // only plans and detached stale entries run no hooks.- let needs_approval = match &outcome.plan {- Some(RemovalPlan::Worktree { .. }) => {- !pre_remove_unapproved.is_empty()- || !post_remove_unapproved.is_empty()- || (matches!(kind, CandidateKind::Current)- && !post_switch_unapproved.is_empty())- }- Some(RemovalPlan::BranchOnly { .. }) | None => false,- };- if needs_approval {- let line =- info_message(cformat!("Skipped <bold>{label}</> (approval required)"))- .to_string();- let _ = job_tx.send(RemovalJob::PrintSkip(line));- let differs = path.as_deref().is_some_and(|wt_path| {- let candidate_bytes = Repository::at(wt_path)- .and_then(|candidate_repo| candidate_repo.project_config_path())- .ok()- .flatten()- .and_then(|p| std::fs::read(p).ok());- candidate_bytes != invoking_project_bytes- });- skipped_approval.push(SkippedApproval { path, differs });+ });+ }+ drop(job_rx);+ drop(done_tx);++ let mut deferred_current: Option<DeferredCurrent> = None;+ let mut first_err: Option<anyhow::Error> = None;+ for (idx, outcome) in &rx {+ // A failed check stops new removals, but drain both channels+ // so the response retains every removal already completed.+ let outcome = match outcome.context("checking branch integration") {+ Ok(outcome) => outcome,+ Err(error) => {+ abort_removals(&error, abort_ref);+ first_err.get_or_insert(error);continue;}- let candidate = Candidate {- check_idx: idx,- label,- branch,- path,- kind,- deletes_branch: outcome.deletes_branch,- fate: None,- };- if matches!(candidate.kind, CandidateKind::Current) {- deferred_current = Some((candidate, outcome.plan));- } else {- let _ = job_tx.send(RemovalJob::Remove {- candidate,- plan: Box::new(outcome.plan),- });+ };+ let Some(_reason) = outcome.reason else {+ continue;+ };+ if !outcome.removable {+ continue;+ }+ let item = &check_items[idx];+ let (label, branch, path, kind, _suffix) =+ candidate_fields(item, &repo, worktrees, ¤t_root);+ if let Some(age) = outcome.age+ && age < min_age_duration+ {+ let line = info_message(cformat!(+ "Skipped <bold>{label}</> (younger than {min_age})"+ ))+ .to_string();+ let _ = job_tx.send(RemovalJob::PrintSkip(line));+ skipped_young.push(label);+ continue;+ }+ // Keyed on the plan, not the candidate's shape: only a+ // worktree removal runs `pre-remove`/`post-remove`. Branch-+ // only plans and detached stale entries run no hooks.+ let needs_approval = match &outcome.plan {+ Some(RemovalPlan::Worktree { .. }) => {+ !pre_remove_unapproved.is_empty()+ || !post_remove_unapproved.is_empty()+ || (matches!(kind, CandidateKind::Current)+ && !post_switch_unapproved.is_empty())}+ Some(RemovalPlan::BranchOnly { .. }) | None => false,+ };+ if needs_approval {+ let line = info_message(cformat!("Skipped <bold>{label}</> (approval required)"))+ .to_string();+ let _ = job_tx.send(RemovalJob::PrintSkip(line));+ let differs = path.as_deref().is_some_and(|wt_path| {+ let candidate_bytes = Repository::at(wt_path)+ .and_then(|candidate_repo| candidate_repo.project_config_path())+ .ok()+ .flatten()+ .and_then(|p| std::fs::read(p).ok());+ candidate_bytes != invoking_project_bytes+ });+ skipped_approval.push(SkippedApproval { path, differs });+ continue;}- drop(job_tx);-- let mut removed: Vec<Candidate> = Vec::new();- let mut first_err: Option<anyhow::Error> = None;- for (mut candidate, result) in &done_rx {- match result {- // Record the executed outcome, not the scan's prediction —- // what the summary and `--format=json` report.- Ok(Some(fate)) => {- candidate.record_fate(fate);- removed.push(candidate);- }- Ok(None) => {}- Err(err) if first_err.is_none() => first_err = Some(err),- // Concurrent failures (e.g. one Ctrl-C killing every- // in-flight child) all carry the same story; report the- // first and keep the rest out of the terminal.- Err(err) => {+ let candidate = Candidate {+ check_idx: idx,+ label,+ branch,+ path,+ kind,+ deletes_branch: outcome.deletes_branch,+ fate: None,+ };+ if matches!(candidate.kind, CandidateKind::Current) {+ deferred_current = Some((candidate, outcome.plan));+ } else {+ let _ = job_tx.send(RemovalJob::Remove {+ candidate,+ plan: Box::new(outcome.plan),+ });+ }+ }+ drop(job_tx);++ let mut removed: Vec<Candidate> = Vec::new();+ for (mut candidate, result) in &done_rx {+ let completed = match result {+ Ok(completed) => completed,+ Err(failure) => {+ if first_err.is_none() {+ first_err = Some(failure.error);+ } else {tracing::debug!(- error = %err,- "additional removal failure for {}: {err:#}",- candidate.label+ error = %failure.error,+ "additional removal failure for {}: {:#}",+ candidate.label,+ failure.error,);}+ failure.result.and_then(|result| *result)}+ };+ if let Some(fate) = completed {+ candidate.record_fate(fate);+ removed.push(candidate);}- if let Some(err) = first_err {- return Err(err);- }- Ok((removed, deferred_current))- },- )?;+ }+ (removed, deferred_current, first_err)+ });drop(scan_span);let mut removed = removed;@@ -1399,12 +1411,20 @@ pub fn step_prune(// current worktree stays last.removed.sort_by_key(|c| c.check_idx);// Remove deferred current worktree last (cd-to-primary happens here)- if let Some((mut current, plan)) = deferred_current- && let Some(fate) =- try_remove(¤t, plan, &removal_ctx).with_context(|| current.removal_context())?+ if first_err.is_none()+ && let Some((mut current, plan)) = deferred_current{- current.record_fate(fate);- removed.push(current);+ let completed = match try_remove(¤t, plan, &removal_ctx) {+ Ok(completed) => completed,+ Err(failure) => {+ first_err = Some(failure.error.context(current.removal_context()));+ failure.result.and_then(|result| *result)+ }+ };+ if let Some(fate) = completed {+ current.record_fate(fate);+ removed.push(current);+ }}if format == crate::cli::SwitchFormat::Json {@@ -1420,15 +1440,20 @@ pub fn step_prune(}).collect();print_json(&items)?;- } else if removed.is_empty() {- if skipped_young.is_empty() && skipped_approval.is_empty() {- eprintln!("{}", info_message("No merged worktrees to remove"));- }} else {- eprintln!(- "{}",- success_message(format!("Pruned {}", prune_summary(&removed)))- );+ if let Some(error) = first_err {+ return Err(error);+ }+ if removed.is_empty() {+ if skipped_young.is_empty() && skipped_approval.is_empty() {+ eprintln!("{}", info_message("No merged worktrees to remove"));+ }+ } else {+ eprintln!(+ "{}",+ success_message(format!("Pruned {}", prune_summary(&removed)))+ );+ }}if !skipped_approval.is_empty() {@@ -1443,7 +1468,10 @@ pub fn step_prune(}}- Ok(())+ match first_err {+ Some(error) => Err(error),+ None => Ok(()),+ }}/// One headline+gutter pair for the `(approval required)` end-of-run hint.diff --git a/src/commands/step/relocate.rs b/src/commands/step/relocate.rsindex ba6e2547b..1c49193d7 100644--- a/src/commands/step/relocate.rs+++ b/src/commands/step/relocate.rs@@ -5,8 +5,6 @@use anyhow::Context;use color_print::cformat;-use std::path::PathBuf;-use worktrunk::config::UserConfig;use worktrunk::git::Repository;@@ -32,8 +30,9 @@ pub fn step_relocate(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,+ GatherResult, RelocatedEntry, 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;@@ -66,7 +65,7 @@ pub fn step_relocate(if candidates.is_empty() {if json_mode {- print_relocate_json(&[], &template_skips, dry_run)?;+ return print_relocations(&[], &template_skips, &[], dry_run);} else {show_no_relocations_needed(template_error_branches.len());}@@ -78,13 +77,13 @@ pub fn step_relocate(if json_mode {let planned: Vec<_> = candidates.iter()- .map(|c| RelocatedEntryView {+ .map(|c| RelocatedEntry {branch: c.branch().to_string(),from: c.wt.path.clone(),to: c.expected_path.clone(),}).collect();- print_relocate_json(&planned, &template_skips, true)?;+ return print_relocations(&planned, &template_skips, &[], true);} else {show_dry_run_preview(&candidates);}@@ -113,20 +112,37 @@ pub fn step_relocate(let ValidationResult {validated,skipped: validation_skipped,- } = validate_candidates(+ commits,+ } = match validate_candidates(&repo,&config,candidates,commit,&repo_path,project_append.as_deref(),- )?;+ ) {+ Ok(validation) => validation,+ Err(failure) => {+ if json_mode && let Some(validation) = failure.result {+ print_relocations(+ &[],+ template_skips.iter().chain(&validation.skipped),+ &validation.commits,+ false,+ )?;+ }+ return Err(failure.error);+ }+ };if validated.is_empty() {if json_mode {- let mut all_skipped = template_skips;- all_skipped.extend(validation_skipped);- print_relocate_json(&[], &all_skipped, false)?;+ return print_relocations(+ &[],+ template_skips.iter().chain(&validation_skipped),+ &commits,+ false,+ );} else {// Include template-error branches — the JSON path folds them into// `all_skipped`, so the human count must match.@@ -136,28 +152,39 @@ pub fn step_relocate(}// Phase 3 & 4: Create executor (classifies targets) and execute relocations- let mut executor = RelocationExecutor::new(&repo, validated, clobber)?;+ let mut executor = match RelocationExecutor::new(&repo, validated, clobber) {+ Ok(executor) => executor,+ Err(error) => {+ if json_mode {+ print_relocations(+ &[],+ template_skips.iter().chain(&validation_skipped),+ &commits,+ false,+ )?;+ }+ return Err(error);+ }+ };// Where the user's shell stands — inherited from the parent `wt` when this// runs inside an alias or hook body, whose process cwd is the worktree// root (#3723).let cwd = worktrunk::shell_exec::shell_cwd();- executor.execute(&default_branch, cwd.as_deref())?;+ let execution = 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)?;+ print_relocations(+ &executor.relocated_entries,+ template_skips+ .iter()+ .chain(&validation_skipped)+ .chain(&executor.skipped_entries),+ &commits,+ false,+ )?;+ return execution;} else {+ execution?;// Template-error branches count as skips too — the JSON path folds// them into `all_skipped`, so keep the human total consistent.let total_skipped =@@ -168,30 +195,23 @@ pub fn step_relocate(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],+fn print_relocations<'a>(+ entries: &[super::super::relocate::RelocatedEntry],+ skipped: impl IntoIterator<Item = &'a super::super::relocate::SkippedEntry>,+ commits: &[super::super::relocate::RelocationCommit],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<_>>(),- });- print_json(&payload)?;- Ok(())+ #[derive(serde::Serialize)]+ struct Output<'a> {+ dry_run: bool,+ entries: &'a [super::super::relocate::RelocatedEntry],+ skipped: Vec<&'a super::super::relocate::SkippedEntry>,+ commits: &'a [super::super::relocate::RelocationCommit],+ }+ print_json(&Output {+ dry_run,+ entries,+ skipped: skipped.into_iter().collect(),+ commits,+ })}diff --git a/src/commands/step/squash.rs b/src/commands/step/squash.rsindex 57cd51085..921c73430 100644--- a/src/commands/step/squash.rs+++ b/src/commands/step/squash.rs@@ -38,17 +38,19 @@ pub enum PreApprovedGuidance {}/// Result of a squash operation-#[derive(Debug, Clone)]+#[derive(Debug, Clone, serde::Serialize)]+#[serde(tag = "outcome", rename_all = "snake_case")]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 {+ #[serde(rename = "commit")]sha: String,message: String,stage_mode: StageMode,},/// Nothing to squash: no commits ahead of target branch- NoCommitsAhead(String),+ NoCommitsAhead { target: String },/// Nothing to squash: already a single commitAlreadySingleCommit,/// Squash attempted but resulted in no net changes (commits canceled out)@@ -74,7 +76,7 @@ pub fn handle_squash(stage: Option<StageMode>,announcer: &mut HookAnnouncer<'_>,pre_approved_guidance: PreApprovedGuidance,-) -> anyhow::Result<SquashResult> {+) -> crate::output::CommandResult<SquashResult> {// Load config once, run LLM setup prompt, then reuse configlet mut config = UserConfig::load().context("Failed to load config")?;// One-time LLM setup prompt (errors logged internally; don't block commit)@@ -102,7 +104,7 @@ pub fn handle_squash_in(stage: Option<StageMode>,announcer: &mut HookAnnouncer<'_>,pre_approved_guidance: PreApprovedGuidance,-) -> anyhow::Result<SquashResult> {+) -> crate::output::CommandResult<SquashResult> {let repo = &env.repo;// Rewriting history under a half-finished operation is never what the user// meant, and mid-rebase HEAD is detached — so this runs ahead of the branch@@ -212,7 +214,9 @@ pub fn handle_squash_in(// Handle different scenariosif commit_count == 0 && !has_staged {// No commits and no staged changes - nothing to squash- return Ok(SquashResult::NoCommitsAhead(span_target));+ return Ok(SquashResult::NoCommitsAhead {+ target: span_target,+ });}if commit_count == 1 && !has_staged {@@ -230,7 +234,15 @@ pub fn handle_squash_in(sha,message,stage_mode,- } = generator.commit_staged_changes(&wt, true, true, stage_mode)?;+ } = generator+ .commit_staged_changes(&wt, true, true, stage_mode)+ .map_err(|failure| {+ failure.map_result(|outcome| SquashResult::Squashed {+ sha: outcome.sha,+ message: outcome.message,+ stage_mode: outcome.stage_mode,+ })+ })?;return Ok(SquashResult::Squashed {sha,message,@@ -416,35 +428,35 @@ pub fn handle_squash_in(.and_then(|_| wt.run_command(&["rev-parse", "HEAD"])){Ok(sha) => sha.trim().to_string(),- Err(err) => return Err(reattach_after_failure(&wt, &branch_ref, err)),+ Err(err) => return Err(reattach_after_failure(&wt, &branch_ref, err).into()),};let subject = commit_message.lines().next().unwrap_or_default();if let Err(err) = move_branch(&commit_sha, &format!("wt squash: {subject}")) {- return Err(reattach_after_failure(&wt, &branch_ref, err));- }- reattach_head(&wt, &branch_ref)?;-- // Full SHA for the JSON payload, abbreviated form for the success line.- 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)?;+ return Err(reattach_after_failure(&wt, &branch_ref, err).into());}-- Ok(SquashResult::Squashed {- sha: commit_sha,+ let result = SquashResult::Squashed {+ sha: commit_sha.clone(),message: commit_message,stage_mode,- })+ };+ let completion = (|| -> anyhow::Result<()> {+ reattach_head(&wt, &branch_ref)?;+ let commit_hash = repo.short_sha(&commit_sha)?;+ eprintln!(+ "{}",+ success_message(cformat!("Squashed @ <dim>{commit_hash}</>"))+ );+ if hooks.run() {+ let extra_vars = template_vars.as_extra_vars();+ announcer.register(&ctx, HookType::PostCommit, &extra_vars, None)?;+ }+ Ok(())+ })();+ match completion {+ Ok(()) => Ok(result),+ Err(error) => Err(crate::output::CommandFailure::with_result(error, result)),+ }}/// Put HEAD back on the branch it was detached from for the squash commit.diff --git a/src/commands/worktree/finish.rs b/src/commands/worktree/finish.rsindex 142b8fd0a..273f6345d 100644--- a/src/commands/worktree/finish.rs+++ b/src/commands/worktree/finish.rs@@ -39,7 +39,10 @@ use crate::commands::repository_ext::{live_sibling_checkout,};use crate::commands::template_vars::TemplateVars;-use crate::output::{handle_merge_remove_output, post_hook_display_path, pre_hook_display_path};+use crate::output::{+ CommandFailure, CommandResult, handle_merge_remove_output, post_hook_display_path,+ pre_hook_display_path,+};/// Inputs to [`finish_after_merge`]. Owned by the caller; this struct just/// bundles them so the function signature stays readable.@@ -64,13 +67,16 @@ pub struct FinishAfterMergeArgs<'a> {/// `announcer` is mutated in place; `flush()` stays with the caller because it/// covers the whole command's background hooks (post-commit, post-remove,/// post-switch, post-merge), not just this step.+/// Records the removal decision before fallible post-merge hook setup, so a+/// later error cannot discard a completed removal. `None` means cleanup did+/// not reach a confirmed outcome.pub fn finish_after_merge(repo: &Repository,config: &UserConfig,env: &CommandEnv,announcer: &mut HookAnnouncer<'_>,args: FinishAfterMergeArgs<'_>,-) -> anyhow::Result<bool> {+) -> CommandResult<bool> {let FinishAfterMergeArgs {current_branch,source_is_current,@@ -204,44 +210,50 @@ pub fn finish_after_merge(// The fate is dropped: merge's own reporting (`removed` in the JSON// blob, the removal messages) doesn't itemize the branch, and the// handler has already narrated any retention.- handle_merge_remove_output(&remove_result, plan, announcer)?;+ handle_merge_remove_output(&remove_result, plan, announcer)+ .map_err(|failure| failure.map_result(|_| true))?;true};- if verify {- // Post-merge hooks run in the destination worktree (target). `ctx.repo`- // is rooted there only for template *rendering* (the feature worktree- // may be gone); the command set is the frozen `plan`, anchored at- // `destination_path` at the gate — no re-read of the destination's- // (now post-merge) `.config/wt.toml`.- let dest_repo = Repository::at(&destination_path)?;- let ctx = CommandContext::new(- &dest_repo,- config,- Some(current_branch),- &destination_path,- yes,- );- let display_path = if removed && source_is_current {- post_hook_display_path(&destination_path)- } else {- pre_hook_display_path(&destination_path)- };+ let finish = (|| -> anyhow::Result<()> {+ if verify {+ // Post-merge hooks run in the destination worktree (target). `ctx.repo`+ // is rooted there only for template *rendering* (the feature worktree+ // may be gone); the command set is the frozen `plan`, anchored at+ // `destination_path` at the gate — no re-read of the destination's+ // (now post-merge) `.config/wt.toml`.+ let dest_repo = Repository::at(&destination_path)?;+ let ctx = CommandContext::new(+ &dest_repo,+ config,+ Some(current_branch),+ &destination_path,+ yes,+ );+ let display_path = if removed && source_is_current {+ post_hook_display_path(&destination_path)+ } else {+ pre_hook_display_path(&destination_path)+ };- let mut vars = feature_vars.with_target(target_branch);- if let Some(p) = target_worktree_path {- vars = vars.with_target_worktree_path(p);+ let mut vars = feature_vars.with_target(target_branch);+ if let Some(p) = target_worktree_path {+ vars = vars.with_target_worktree_path(p);+ }+ register_planned(+ announcer,+ plan,+ &destination_path,+ &ctx,+ HookType::PostMerge,+ &vars.as_extra_vars(),+ display_path,+ )?;}- register_planned(- announcer,- plan,- &destination_path,- &ctx,- HookType::PostMerge,- &vars.as_extra_vars(),- display_path,- )?;- }- Ok(removed)+ Ok(())+ })();+ finish+ .map(|()| removed)+ .map_err(|error| CommandFailure::with_result(error, removed))}diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsindex efbd69ea9..0fba360ea 100644--- a/src/commands/worktree/mod.rs+++ b/src/commands/worktree/mod.rs@@ -89,10 +89,10 @@ mod types;// Re-export public types and functionspub use finish::{FinishAfterMergeArgs, finish_after_merge};-pub use push::{PushKind, PushOutcome, PushResult, handle_no_ff_merge, handle_push};+pub use push::{PushKind, handle_no_ff_merge, handle_push};pub use resolve::{compute_worktree_path, is_worktree_at_expected_path, worktree_display_name};+pub(crate) use switch::SwitchPipeline;pub use switch::handle_switch_command;-pub(crate) use switch::{SwitchPipeline, print_switch_json_error};pub use types::{BranchFate, MergeOperations, RemovalPlan, RetainedReason, SharedBranchCheckout,SwitchBranchInfo, SwitchResult,diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rsindex 8d21b7c84..10e161325 100644--- a/src/commands/worktree/push.rs+++ b/src/commands/worktree/push.rs@@ -35,6 +35,7 @@ use worktrunk::styling::{use super::types::MergeOperations;use crate::commands::repository_ext::RepositoryCliExt;+use crate::output::{CommandFailure, CommandResult};/// Distinguishes a standalone push from a fast-forward push driven by `wt merge`.///@@ -72,12 +73,17 @@ impl PushKind {}/// Outcome of a push or no-ff merge, returned for JSON output.+#[derive(Debug, serde::Serialize)]pub struct PushResult {pub target: String,+ #[serde(rename = "commits")]pub commit_count: usize,+ #[serde(flatten)]pub outcome: PushOutcome,}+#[derive(Debug, serde::Serialize)]+#[serde(tag = "outcome", rename_all = "snake_case")]pub enum PushOutcome {/// Target was fast-forwarded to HEAD.FastForwarded,@@ -376,7 +382,8 @@ fn format_up_to_date_context(operations: Option<MergeOperations>) -> String {/// `reflog_message` labels the target branch's reflog entry — the recovery/// affordance for the one operation that moves a branch the user isn't/// standing on, where every other mover (`push`, `merge`, `reset`) names-/// itself.+/// itself. A failure of the final concurrency check carries completed work;+/// ref-update and worktree-sync failures do not claim a completed advance.fn advance_target(repo: &Repository,target_branch: &str,@@ -384,7 +391,7 @@ fn advance_target(old_sha: &str,new_sha: &str,reflog_message: &str,-) -> anyhow::Result<()> {+) -> CommandResult<()> {let target_ref = format!("refs/heads/{target_branch}");repo.run_command(&["update-ref",@@ -433,7 +440,9 @@ fn advance_target(// the ref. Re-read the ref so that interleaving surfaces instead// of being reported as a clean merge. The push range is in the// tip's ancestry either way, so this warns rather than fails.- let tip_after = repo.run_command(&["rev-parse", &target_ref])?;+ let tip_after = repo+ .run_command(&["rev-parse", &target_ref])+ .map_err(|error| CommandFailure::with_result(error, ()))?;if tip_after.trim() != new_sha {eprintln!("{}",@@ -475,7 +484,7 @@ fn advance_target(was not synced"),};- Err(e).context(context)+ Err(e.context(context).into())}// ---------------------------------------------------------------------------@@ -495,7 +504,7 @@ pub fn handle_push(target: Option<&str>,kind: PushKind,operations: Option<MergeOperations>,-) -> anyhow::Result<PushResult> {+) -> CommandResult<PushResult> {let ctx = MergeContext::prepare(repo, target, operations)?;ctx.show_progress(kind.verb_progressive(), "", operations)?;@@ -511,21 +520,27 @@ pub fn handle_push(});}- advance_target(+ let advancement = advance_target(&ctx.repo,&ctx.target_branch,ctx.target_worktree_path.as_ref(),&ctx.target_tip,&ctx.head_sha,kind.reflog_message(),- )?;+ );- ctx.show_success(kind.verb_past(), "", "");- Ok(PushResult {+ if advancement.is_ok() {+ ctx.show_success(kind.verb_past(), "", "");+ }+ let result = PushResult {target: ctx.target_branch,commit_count: ctx.commit_count,outcome: PushOutcome::FastForwarded,- })+ };+ match advancement {+ Ok(()) => Ok(result),+ Err(failure) => Err(failure.map_result(|()| result)),+ }}// ---------------------------------------------------------------------------@@ -545,7 +560,7 @@ pub fn handle_no_ff_merge(target: Option<&str>,operations: Option<MergeOperations>,feature_branch: &str,-) -> anyhow::Result<PushResult> {+) -> CommandResult<PushResult> {let ctx = MergeContext::prepare(repo, target, operations)?;ctx.show_progress("Merging", " (--no-ff)", operations)?;@@ -594,7 +609,10 @@ pub fn handle_no_ff_merge(.trim().to_string();- advance_target(+ // Display uses `Repository::short_sha`; the JSON payload carries the full SHA.+ let merge_sha_short = ctx.repo.short_sha(&merge_sha)?;++ let advancement = advance_target(&ctx.repo,&ctx.target_branch,ctx.target_worktree_path.as_ref(),@@ -605,18 +623,21 @@ pub fn handle_no_ff_merge(} else {"wt step push: no-ff"},- )?;-- // Display uses `Repository::short_sha`; the JSON payload carries the full SHA.- let merge_sha_short = ctx.repo.short_sha(&merge_sha)?;- let sha_suffix = cformat!(" @ <dim>{merge_sha_short}</>");- ctx.show_success("Merged to", &sha_suffix, ", --no-ff");+ );- Ok(PushResult {+ if advancement.is_ok() {+ let sha_suffix = cformat!(" @ <dim>{merge_sha_short}</>");+ ctx.show_success("Merged to", &sha_suffix, ", --no-ff");+ }+ let result = PushResult {target: ctx.target_branch,commit_count: ctx.commit_count,outcome: PushOutcome::MergeCommit { merge_sha },- })+ };+ match advancement {+ Ok(()) => Ok(result),+ Err(failure) => Err(failure.map_result(|()| result)),+ }}#[cfg(test)]@@ -686,9 +707,11 @@ mod tests {std::fs::write(root.join("x.txt"), "local-edit").unwrap();let err = advance_target(&repo, "main", Some(&root), &new, &new2, "test").unwrap_err();+ assert!(err.result.is_none());assert!(- err.to_string().contains("rolled back"),- "unexpected error: {err:#}"+ err.error.to_string().contains("rolled back"),+ "unexpected error: {:#}",+ err.error);assert_eq!(test.git_output(&["rev-parse", "main"]), new);assert_eq!(@@ -698,9 +721,11 @@ mod tests {// Stale old_sha: the compare-and-swap fails before anything moves.let err = advance_target(&repo, "main", Some(&root), &old, &new2, "test").unwrap_err();+ assert!(err.result.is_none());assert!(- err.to_string().contains("Can't push"),- "unexpected error: {err:#}"+ err.error.to_string().contains("Can't push"),+ "unexpected error: {:#}",+ err.error);assert_eq!(test.git_output(&["rev-parse", "main"]), new);}diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex aeab8a07c..3f3db6a7d 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -7,7 +7,6 @@use std::path::{Path, PathBuf};use crate::display::format_relative_time_short;-use ansi_str::AnsiStr as _;use anyhow::{Context, bail};use color_print::cformat;use dunce::canonicalize;@@ -26,8 +25,8 @@ use worktrunk::git::{use worktrunk::path::{canonicalize_with_parents, format_path_for_display};use worktrunk::shell_exec::{ShellEscapeMode, shell_cwd};use worktrunk::styling::{- eprintln, format_with_gutter, hint_message, info_message, println, progress_message,- suggest_command, warning_message,+ eprintln, format_with_gutter, hint_message, info_message, progress_message, suggest_command,+ warning_message,};use super::resolve::{compute_worktree_path, offer_bare_repo_worktree_path_fix};@@ -42,8 +41,8 @@ use crate::commands::hook_plan::{ApprovedHookPlan, HookPlanBuilder, register_plause crate::commands::hooks::{HookAnnouncer, execute_hook};use crate::commands::template_vars::TemplateVars;use crate::output::{- execute_user_command, handle_switch_output, is_shell_integration_active,- prompt_shell_integration,+ CommandFailure, CommandResult, execute_user_command, handle_switch_output,+ is_shell_integration_active, print_json, prompt_shell_integration,};/// A `pr:N` / `mr:N` argument resolved through the forge.@@ -884,16 +883,11 @@ fn validate_worktree_creation(/// (GitLab/Azure DevOps). Only a failed `pushRemote` write — the last one, with/// the other two landed — leaves a branch the next run adopts directly.///-/// # Arguments-///-/// * `remote_ref` - The ref to track (e.g., "pull/123/head" or "merge-requests/101/head")-/// * `fork_push_url` - URL to push to, or `None` if push isn't supported (prefixed branch)-fn setup_fork_branch(+/// The caller records the created worktree before configuring tracking, so+/// a tracking error preserves that result.+fn create_fork_worktree(repo: &Repository,branch: &str,- remote: &str,- remote_ref: &str,- fork_push_url: Option<&str>,worktree_path: &Path,) -> anyhow::Result<()> {// Create branch and worktree in one command (delayed streaming: silent if@@ -905,8 +899,7 @@ fn setup_fork_branch(// up tracking only where the start point resolves under `refs/heads/` or// `refs/remotes/`, and `FETCH_HEAD` resolves as itself. Under every value// of the setting — `always` included — git writes no tracking config from- // this start point, leaving the `set_config` calls below as the only- // writers.+ // this start point, leaving `configure_fork_branch` as the only writer.let worktree_path_str = worktree_path.to_string_lossy();let git_args = ["worktree",@@ -930,6 +923,16 @@ fn setup_fork_branch(worktree_creation_error(repo, e, branch.to_string(), None, false)})?;+ Ok(())+}++fn configure_fork_branch(+ repo: &Repository,+ branch: &str,+ remote: &str,+ remote_ref: &str,+ fork_push_url: Option<&str>,+) -> anyhow::Result<()> {// Configure branch tracking for pull and pushlet branch_remote_key = format!("branch.{}.remote", branch);let branch_merge_key = format!("branch.{}.merge", branch);@@ -1137,7 +1140,7 @@ fn execute_switch(force: bool,run_hooks: bool,hook_plan: &ApprovedHookPlan,-) -> anyhow::Result<(SwitchResult, SwitchBranchInfo)> {+) -> CommandResult<(SwitchResult, SwitchBranchInfo)> {match plan {SwitchPlan::Existing {path,@@ -1191,11 +1194,11 @@ fn execute_switch(}// Execute based on creation method- let (created_branch, base_branch, from_remote) = match &method {+ let (created_branch, base_branch, from_remote, detect_tracking) = match &method {CreationMethod::Regular {create_branch,base_branch,- base_pr_upstream,+ ..} => {// Check if local branch exists BEFORE git worktree add (for DWIM detection)let branch_handle = repo.branch(&branch);@@ -1291,40 +1294,24 @@ fn execute_switch(branch.clone(),base_branch.clone(),*create_branch,- ));- }-- // `--base pr:N` / `--base mr:N` against a same-repo PR/MR: the- // user asked for a custom local name pointing at an existing- // remote branch — wire up tracking so `git push` from the new- // worktree pushes back to the PR/MR's source branch instead- // of failing with "no upstream branch". See issue #2497.- if *create_branch- && let Some((upstream_remote, upstream_branch)) = base_pr_upstream- {- repo.set_config(&format!("branch.{branch}.remote"), upstream_remote)?;- repo.set_config(- &format!("branch.{branch}.merge"),- &format!("refs/heads/{upstream_branch}"),- )?;+ )+ .into());}- // Report tracking info when the branch was auto-created from a remote- let from_remote = if !create_branch && !local_branch_existed {- branch_handle.upstream()?- } else {- None- };-- (*create_branch, base_branch.clone(), from_remote)+ (+ *create_branch,+ base_branch.clone(),+ None,+ !create_branch && !local_branch_existed,+ )}CreationMethod::ForkRef {ref_type,number,ref_path,- fork_push_url,remote,+ ..} => {let label = ref_type.display(*number);@@ -1336,40 +1323,10 @@ fn execute_switch(// No rollback on failure. One here used to delete the// branch on any error, so the "a branch named 'X' already// exists" case force-deleted a branch `wt` had not created,- // taking any commits only it held. `setup_fork_branch`+ // taking any commits only it held. `create_fork_worktree`// leaves nothing for a rollback to clean up.- setup_fork_branch(- repo,- &branch,- remote,- ref_path,- fork_push_url.as_deref(),- &worktree_path,- )?;-- // Show push configuration or warning about prefixed branch- if let Some(url) = fork_push_url {- eprintln!(- "{}",- info_message(cformat!("Push configured to fork: <underline>{url}</>"))- );- } else {- // Prefixed branch name due to conflict - push won't work- eprintln!(- "{}",- warning_message(cformat!(- "Using prefixed branch name <bold>{branch}</> due to name conflict"- ))- );- eprintln!(- "{}",- hint_message(- "Push to fork is not supported with prefixed branches; feedback welcome at https://github.com/max-sixty/worktrunk/issues/714",- )- );- }-- (false, None, Some(label))+ create_fork_worktree(repo, &branch, &worktree_path)?;+ (false, None, Some(label), false)}};@@ -1402,42 +1359,121 @@ fn execute_switch(None => (None, None),};- // Execute pre-start commands. `hook_repo` roots the render context- // in the new worktree (created just above); the commands come from- // the frozen `hook_plan`, selected at the gate from the invoking- // worktree's config.- if run_hooks {- let hook_repo = Repository::at(&worktree_path)?;- let ctx =- CommandContext::new(&hook_repo, config, Some(&branch), &worktree_path, force);- let mut vars = TemplateVars::new()- .with_target(&branch)- .with_target_worktree_path(&worktree_path)- .with_pr(pr_number, pr_url.as_deref());- if let CreationMethod::Regular { base_branch, .. } = &method {- vars =- vars.with_base_strs(base_branch.as_deref(), base_worktree_path.as_deref());+ let mut result = SwitchResult::Created {+ path: worktree_path.clone(),+ created_branch,+ base_branch,+ base_worktree_path: base_worktree_path.clone(),+ from_remote,+ };+ // Creation is committed. Keep the typed outcome through tracking+ // setup and hooks, which can still fail independently.+ let finish = (|| -> anyhow::Result<()> {+ match &method {+ CreationMethod::Regular {+ create_branch,+ base_pr_upstream,+ ..+ } => {+ // A same-repo PR/MR base tracks its source branch even+ // when the user chose a different local branch name.+ if *create_branch+ && let Some((upstream_remote, upstream_branch)) = base_pr_upstream+ {+ repo.set_config(&format!("branch.{branch}.remote"), upstream_remote)?;+ repo.set_config(+ &format!("branch.{branch}.merge"),+ &format!("refs/heads/{upstream_branch}"),+ )?;+ }+ if detect_tracking+ && let SwitchResult::Created { from_remote, .. } = &mut result+ {+ *from_remote = repo.branch(&branch).upstream()?;+ }+ }+ CreationMethod::ForkRef {+ ref_path,+ fork_push_url,+ remote,+ ..+ } => {+ configure_fork_branch(+ repo,+ &branch,+ remote,+ ref_path,+ fork_push_url.as_deref(),+ )?;+ if let Some(url) = fork_push_url {+ eprintln!(+ "{}",+ info_message(cformat!(+ "Push configured to fork: <underline>{url}</>"+ ))+ );+ } else {+ eprintln!(+ "{}",+ warning_message(cformat!(+ "Using prefixed branch name <bold>{branch}</> due to name conflict"+ ))+ );+ eprintln!(+ "{}",+ hint_message(+ "Push to fork is not supported with prefixed branches; feedback welcome at https://github.com/max-sixty/worktrunk/issues/714"+ )+ );+ }+ }}- ctx.execute_pre_create_commands(&vars.as_extra_vars(), hook_plan, &worktree_path)?;- }- // Record successful switch in history- if let Some((path, branch)) = &new_previous {- let _ = repo.record_switch_source(path, branch.as_deref());- }+ // Execute pre-start commands. `hook_repo` roots the render context+ // in the new worktree (created just above); the commands come from+ // the frozen `hook_plan`, selected at the gate from the invoking+ // worktree's config.+ if run_hooks {+ let hook_repo = Repository::at(&worktree_path)?;+ let ctx = CommandContext::new(+ &hook_repo,+ config,+ Some(&branch),+ &worktree_path,+ force,+ );+ let mut vars = TemplateVars::new()+ .with_target(&branch)+ .with_target_worktree_path(&worktree_path)+ .with_pr(pr_number, pr_url.as_deref());+ if let CreationMethod::Regular { base_branch, .. } = &method {+ vars = vars+ .with_base_strs(base_branch.as_deref(), base_worktree_path.as_deref());+ }+ ctx.execute_pre_create_commands(+ &vars.as_extra_vars(),+ hook_plan,+ &worktree_path,+ )?;+ }- Ok((- SwitchResult::Created {- path: worktree_path,- created_branch,- base_branch,- base_worktree_path,- from_remote,- },+ // Record successful switch in history+ if let Some((path, branch)) = &new_previous {+ let _ = repo.record_switch_source(path, branch.as_deref());+ }++ Ok(())+ })();+ let outcome = (+ result,SwitchBranchInfo {branch: Some(branch),},- ))+ );+ match finish {+ Ok(()) => Ok(outcome),+ Err(error) => Err(CommandFailure::with_result(error, outcome)),+ }}}}@@ -1591,35 +1627,6 @@ impl SwitchJsonOutput {}}-/// Emit the structured `--format=json` result after synchronous work succeeds.-///-/// One compact line rather than [`crate::output::print_json`]'s pretty form —-/// a switch reports a single result, and a line is what a shell loop reads.-/// The `println!` is anstream's for the same reason `print_json` uses it: a-/// consumer that stops reading must not panic the command.-///-/// A no-op for `SwitchFormat::Text`.-fn emit_switch_json(- format: SwitchFormat,- result: &SwitchResult,- branch_info: &SwitchBranchInfo,-) -> anyhow::Result<()> {- if format != SwitchFormat::Json {- return Ok(());- }- let json = SwitchJsonOutput::from_result(result, branch_info);- let json = serde_json::to_string(&json).context("Failed to serialize to JSON")?;- println!("{json}");- Ok(())-}--/// Emit the single failure result for a parsed JSON switch invocation.-/// Main owns the failure boundary, including errors before pipeline creation.-pub(crate) fn print_switch_json_error(message: &str) {- let payload = serde_json::json!({ "error": message.ansi_strip() });- println!("{payload}");-}-/// Options for the switch commandstruct SwitchOptions<'a> {branch: &'a str,@@ -1996,142 +2003,165 @@ impl SwitchPipeline<'_> {// blocks re-running.validate_switch_templates(repo, config, &plan, execute, execute_args, hooks_approved)?;- // Execute the validated plan.let (result, branch_info) =- execute_switch(repo, plan, config, yes, hooks_approved, &hook_plan)?;+ match execute_switch(repo, plan, config, yes, hooks_approved, &hook_plan) {+ Ok(result) => result,+ Err(failure) => {+ if format == SwitchFormat::Json+ && let Some((result, branch_info)) = failure.result.as_deref()+ {+ print_json(&SwitchJsonOutput::from_result(result, branch_info))?;+ }+ return Err(failure.error);+ }+ };- // Early exit for benchmarking time-to-first-output.- if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {- return emit_switch_json(format, &result, &branch_info);- }+ // Emit the result after all synchronous work, retaining the completed+ // switch if a later directive, hook, or --execute operation fails.+ let finish = (|| -> anyhow::Result<()> {+ // Early exit for benchmarking time-to-first-output.+ if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {+ return Ok(());+ }- // Show success message (temporal locality: immediately after the- // worktree operation). Returns the path to display in hooks when the- // user's shell won't be in the worktree, and shows the worktree-path- // hint on first --create (before the shell integration warning).- //- // `shell_cwd()` is where the user's shell stands: the process cwd,- // unless a parent `wt` passed its own down (an alias or hook body runs- // from the worktree root, so a nested switch would otherwise resolve- // the user to that root — #3723). When the shell's CWD was already- // gone when `wt` started, `startup_cwd()` never captured one and this- // reads as absent — fall back to `repo_path()` (the main worktree- // root). `current_worktree().root()` resolves against the Repository's- // discovery path, which is alive even after recovery, but we keep the- // same fallback for any pathological case where rev-parse fails.- let fallback_path = repo.repo_path()?.to_path_buf();- let cwd = shell_cwd().unwrap_or(fallback_path.clone());- let source_root = repo.current_worktree().root().unwrap_or(fallback_path);- let display_paths =- handle_switch_output(&result, &branch_info, change_dir, Some(&source_root), &cwd)?;-- // Offer shell integration if not already installed/active (only shows- // the prompt/hint when shell integration isn't working). With- // --execute, show hints only — don't interrupt with a prompt. Skip when- // change_dir is false (the user opted out of cd, so shell integration- // is irrelevant) and on the picker path (no `binary_name`).- // Best-effort: don't fail the switch if the offer fails, but stop on- // cancellation.- if let Some(binary_name) = shell_integration_binary- && change_dir- && !is_shell_integration_active()- {- let skip_prompt = execute.is_some();- if let Err(err) = prompt_shell_integration(repo, config, binary_name, skip_prompt)- && err.interrupt_signal().is_some()+ // Show success message (temporal locality: immediately after the+ // worktree operation). Returns the path to display in hooks when the+ // user's shell won't be in the worktree, and shows the worktree-path+ // hint on first --create (before the shell integration warning).+ //+ // `shell_cwd()` is where the user's shell stands: the process cwd,+ // unless a parent `wt` passed its own down (an alias or hook body runs+ // from the worktree root, so a nested switch would otherwise resolve+ // the user to that root — #3723). When the shell's CWD was already+ // gone when `wt` started, `startup_cwd()` never captured one and this+ // reads as absent — fall back to `repo_path()` (the main worktree+ // root). `current_worktree().root()` resolves against the Repository's+ // discovery path, which is alive even after recovery, but we keep the+ // same fallback for any pathological case where rev-parse fails.+ let fallback_path = repo.repo_path()?.to_path_buf();+ let cwd = shell_cwd().unwrap_or(fallback_path.clone());+ let source_root = repo.current_worktree().root().unwrap_or(fallback_path);+ let display_paths =+ handle_switch_output(&result, &branch_info, change_dir, Some(&source_root), &cwd)?;++ // Offer shell integration if not already installed/active (only shows+ // the prompt/hint when shell integration isn't working). With+ // --execute, show hints only — don't interrupt with a prompt. Skip when+ // change_dir is false (the user opted out of cd, so shell integration+ // is irrelevant) and on the picker path (no `binary_name`).+ // Best-effort: don't fail the switch if the offer fails, but stop on+ // cancellation.+ if let Some(binary_name) = shell_integration_binary+ && change_dir+ && !is_shell_integration_active(){- return Err(err);+ let skip_prompt = execute.is_some();+ if let Err(err) = prompt_shell_integration(repo, config, binary_name, skip_prompt)+ && err.interrupt_signal().is_some()+ {+ return Err(err);+ }}- }- // Build template vars for base/target context (used by both hooks and- // --execute). "base" is the source worktree the user switched from (all- // switches), or the branch they branched from (creates). "target"- // matches the bare vars (the destination) — kept symmetric with- // pre-switch.- // `pr_number` / `pr_url` come from the resolved argument, not from- // `result` — a `pr:N` switch onto a branch that already has a worktree- // returns `SwitchResult::Existing`, which knows nothing about the PR.- let mut template_vars =- TemplateVars::for_post_switch(&result, &branch_info, &source_branch, &source_path);- if let Some(identity) = &ref_identity {- template_vars = template_vars.with_pr(Some(identity.number), Some(&identity.url));- }- let extra_vars = template_vars.as_extra_vars();-- // Spawn background hooks after the success message.- // - post-switch: runs on ALL switches (shows "@ path" when the shell- // won't be there)- // - post-start: runs only when creating a NEW worktree- if hooks_approved {- spawn_switch_background_hooks(- config,- &result,- branch_info.branch.as_deref(),- yes,- &extra_vars,- display_paths.hooks.as_deref(),- &hook_plan,- )?;- }+ // Build template vars for base/target context (used by both hooks and+ // --execute). "base" is the source worktree the user switched from (all+ // switches), or the branch they branched from (creates). "target"+ // matches the bare vars (the destination) — kept symmetric with+ // pre-switch.+ // `pr_number` / `pr_url` come from the resolved argument, not from+ // `result` — a `pr:N` switch onto a branch that already has a worktree+ // returns `SwitchResult::Existing`, which knows nothing about the PR.+ let mut template_vars =+ TemplateVars::for_post_switch(&result, &branch_info, &source_branch, &source_path);+ if let Some(identity) = &ref_identity {+ template_vars = template_vars.with_pr(Some(identity.number), Some(&identity.url));+ }+ let extra_vars = template_vars.as_extra_vars();++ // Spawn background hooks after the success message.+ // - post-switch: runs on ALL switches (shows "@ path" when the shell+ // won't be there)+ // - post-start: runs only when creating a NEW worktree+ if hooks_approved {+ spawn_switch_background_hooks(+ config,+ &result,+ branch_info.branch.as_deref(),+ yes,+ &extra_vars,+ display_paths.hooks.as_deref(),+ &hook_plan,+ )?;+ }- // Execute the user command after post-start hooks have been spawned.- // Note: execute_args requires execute via clap's `requires` attribute.- if let Some(cmd) = execute {- // Build template context for expansion (includes base vars when- // creating).- let ctx = CommandContext::new(- repo,- config,- branch_info.branch.as_deref(),- result.path(),- yes,- );- // Compute only the vars the command actually names. The map is- // consumed by `expand_template` and nothing else — the child- // receives argv, never the context as JSON on stdin, and- // `--execute` renders no `-v` variables table. So a var the- // templates don't reference is a git subprocess whose result is- // thrown away.- //- // The union is complete: `validate_switch_templates` already- // parsed both positions against `ValidationScope::SwitchExecute`- // before the switch ran, so nothing reaching here is unparsable.- // No `alias_context_filter` — `args` is alias scope only, and- // `branch` (the implicit read behind `{{ vars.X }}`) is in- // `build_hook_context`'s unconditional cheap block.- let referenced = referenced_vars_for_templates(- std::iter::once(cmd).chain(execute_args.iter().map(String::as_str)),- );- let template_vars =- build_hook_context(&ctx, &extra_vars, VarScope::Referenced(&referenced))?;-- // Every position is one argv element. Literal expansion preserves- // spaces, quotes, and shell metacharacters as data.- let program =- template_vars.expand(cmd, ShellEscapeMode::Literal, repo, "--execute command")?;- let args: Result<Vec<_>, _> = execute_args- .iter()- .map(|arg| {- template_vars.expand(arg, ShellEscapeMode::Literal, repo, "--execute argument")- })- .collect();- let argv: Vec<String> = std::iter::once(program).chain(args?).collect();- // The header names where the program starts, which is the- // directory the switch selected and not the worktree the hooks- // announce (#4042).- execute_user_command(- &argv,- display_paths.execute.as_deref(),- &display_paths.execute_dir,- format == SwitchFormat::Json,- )?;- }+ // Execute the user command after post-start hooks have been spawned.+ // Note: execute_args requires execute via clap's `requires` attribute.+ if let Some(cmd) = execute {+ // Build template context for expansion (includes base vars when+ // creating).+ let ctx = CommandContext::new(+ repo,+ config,+ branch_info.branch.as_deref(),+ result.path(),+ yes,+ );+ // Compute only the vars the command actually names. The map is+ // consumed by `expand_template` and nothing else — the child+ // receives argv, never the context as JSON on stdin, and+ // `--execute` renders no `-v` variables table. So a var the+ // templates don't reference is a git subprocess whose result is+ // thrown away.+ //+ // The union is complete: `validate_switch_templates` already+ // parsed both positions against `ValidationScope::SwitchExecute`+ // before the switch ran, so nothing reaching here is unparsable.+ // No `alias_context_filter` — `args` is alias scope only, and+ // `branch` (the implicit read behind `{{ vars.X }}`) is in+ // `build_hook_context`'s unconditional cheap block.+ let referenced = referenced_vars_for_templates(+ std::iter::once(cmd).chain(execute_args.iter().map(String::as_str)),+ );+ let template_vars =+ build_hook_context(&ctx, &extra_vars, VarScope::Referenced(&referenced))?;++ // Every position is one argv element. Literal expansion preserves+ // spaces, quotes, and shell metacharacters as data.+ let program = template_vars.expand(+ cmd,+ ShellEscapeMode::Literal,+ repo,+ "--execute command",+ )?;+ let args: Result<Vec<_>, _> = execute_args+ .iter()+ .map(|arg| {+ template_vars.expand(+ arg,+ ShellEscapeMode::Literal,+ repo,+ "--execute argument",+ )+ })+ .collect();+ let argv: Vec<String> = std::iter::once(program).chain(args?).collect();+ // The header names where the program starts, which is the+ // directory the switch selected and not the worktree the hooks+ // announce (#4042).+ execute_user_command(+ &argv,+ display_paths.execute.as_deref(),+ &display_paths.execute_dir,+ format == SwitchFormat::Json,+ )?;+ }- // Reserve stdout for one result after every fallible synchronous step.- // A late failure still leaves the worktree in place, but reports no- // success document. Detached hooks keep their independent lifecycle.- emit_switch_json(format, &result, &branch_info)+ Ok(())+ })();+ if format == SwitchFormat::Json {+ print_json(&SwitchJsonOutput::from_result(&result, &branch_info))?;+ }+ finish}}@@ -2214,44 +2244,41 @@ pub fn handle_switch_command(args: SwitchArgs, yes: bool) -> anyhow::Result<()>worktrunk::config::suppress_warnings();}- UserConfig::load()- .context("Failed to load config")- .and_then(|mut config| {- // No branch argument: open interactive picker- let change_dir_flag = flag_pair(args.cd, args.no_cd);-- let Some(branch) = args.branch else {- // No branch argument: open the interactive picker. `--execute`- // (and its trailing args) run against the picked worktree.- return crate::commands::handle_picker(- args.branches,- args.remotes,- args.prs,- change_dir_flag,- args.format,- args.execute.as_deref(),- &args.execute_args,- );- };+ let mut config = UserConfig::load().context("Failed to load config")?;+ // No branch argument: open interactive picker+ let change_dir_flag = flag_pair(args.cd, args.no_cd);++ let Some(branch) = args.branch else {+ // No branch argument: open the interactive picker. `--execute`+ // (and its trailing args) run against the picked worktree.+ return crate::commands::handle_picker(+ args.branches,+ args.remotes,+ args.prs,+ change_dir_flag,+ args.format,+ args.execute.as_deref(),+ &args.execute_args,+ );+ };- run_switch(- SwitchOptions {- branch: &branch,- create: args.create,- base: args.base.as_deref(),- path: args.path.as_deref(),- execute: args.execute.as_deref(),- execute_args: &args.execute_args,- yes,- clobber: args.clobber,- change_dir: change_dir_flag,- verify,- format: args.format,- },- &mut config,- &crate::binary_name(),- )- })+ run_switch(+ SwitchOptions {+ branch: &branch,+ create: args.create,+ base: args.base.as_deref(),+ path: args.path.as_deref(),+ execute: args.execute.as_deref(),+ execute_args: &args.execute_args,+ yes,+ clobber: args.clobber,+ change_dir: change_dir_flag,+ verify,+ format: args.format,+ },+ &mut config,+ &crate::binary_name(),+ )}/// Validate all templates that will be expanded after worktree creation.diff --git a/src/help.rs b/src/help.rsindex f548b1697..c53426721 100644--- a/src/help.rs+++ b/src/help.rs@@ -286,7 +286,7 @@ pub fn maybe_handle_help_with_pager(// Page only when stdout is a TTY; redirected help stays on stdout.// use_pager=false for -h (short help), true for --help (long help)if let Err(error) = crate::help_pager::show_help_in_pager(&help, use_pager) {- crate::handle_command_failure(error, 0, &args.join(" "), false);+ crate::handle_command_failure(error, 0, &args.join(" "));}process::exit(0);}diff --git a/src/main.rs b/src/main.rsindex b3593ba22..e3843eb95 100644--- a/src/main.rs+++ b/src/main.rs@@ -36,11 +36,11 @@ pub(crate) use invocation::{pub(crate) use crate::cli::{OutputFormat, StatuslineFormat};-use crate::output::print_json;+use crate::output::{CommandFailure, finish_output, print_json};use commands::commit::HookGate;use commands::handle_picker;-use commands::worktree::{PushKind, PushOutcome, PushResult, handle_no_ff_merge, handle_push};+use commands::worktree::{PushKind, handle_no_ff_merge, handle_push};use commands::{HookCliArgs, MergeFlagOverrides, MergeOptions, RebaseResult, SquashResult, add_approvals,clear_approvals, flag_pair, handle_alias_dry_run, handle_alias_show, handle_cache_clear,@@ -208,25 +208,15 @@ fn handle_step_command(if format == SwitchFormat::Json && (args.show_prompt || args.dry_run) {anyhow::bail!("--show-prompt / --dry-run cannot be combined with --format=json");}- let outcome = step_commit(+ step_commit(args.branch,yes,verify,args.stage,args.show_prompt,args.dry_run,- )?;- if format == SwitchFormat::Json- && let Some(outcome) = outcome- {- let payload = serde_json::json!({- "commit": outcome.sha,- "message": outcome.message,- "stage_mode": outcome.stage_mode,- });- print_json(&payload)?;- }- Ok(())+ format,+ )}StepCommand::Squash(args) => {let verify = args.hooks.resolve();@@ -250,47 +240,28 @@ fn handle_step_command(};let mut announcer = HookAnnouncer::new(&repo, false);let format = args.format;- let result = handle_squash(+ let outcome = handle_squash(args.target.as_deref(),yes,hooks,args.stage,&mut announcer,commands::PreApprovedGuidance::RunOwnGate,- )?;- announcer.flush()?;- if format == SwitchFormat::Json {- let payload = match &result {- SquashResult::Squashed {- sha,- message,- stage_mode,- } => serde_json::json!({- "outcome": "squashed",- "commit": sha,- "message": message,- "stage_mode": stage_mode,- }),- SquashResult::NoCommitsAhead(target) => serde_json::json!({- "outcome": "no_commits_ahead",- "target": target,- }),- SquashResult::AlreadySingleCommit => serde_json::json!({- "outcome": "already_single_commit",- }),- SquashResult::NoNetChanges => serde_json::json!({- "outcome": "no_net_changes",- }),- };- print_json(&payload)?;- } else {+ )+ .and_then(|result| match announcer.flush() {+ Ok(()) => Ok(result),+ Err(error) => Err(CommandFailure::with_result(error, result)),+ });+ if format != SwitchFormat::Json+ && let Ok(result) = &outcome+ {match result {SquashResult::Squashed { .. } | SquashResult::NoNetChanges => {}- SquashResult::NoCommitsAhead(branch) => {+ SquashResult::NoCommitsAhead { target } => {eprintln!("{}",info_message(cformat!(- "Nothing to squash; no commits ahead of <bold>{branch}</>"+ "Nothing to squash; no commits ahead of <bold>{target}</>")));}@@ -302,7 +273,7 @@ fn handle_step_command(}}}- Ok(())+ finish_output(outcome, format == SwitchFormat::Json)}}StepCommand::Push {@@ -312,33 +283,13 @@ fn handle_step_command(..} => {let repo = Repository::current()?;- let result = if no_ff {+ let outcome = if no_ff {let current_branch = repo.require_selected_branch("@", "step push --no-ff")?;- handle_no_ff_merge(&repo, target.as_deref(), None, ¤t_branch)?+ handle_no_ff_merge(&repo, target.as_deref(), None, ¤t_branch)} else {- handle_push(&repo, target.as_deref(), PushKind::Standalone, None)?+ handle_push(&repo, target.as_deref(), PushKind::Standalone, None)};- if format == SwitchFormat::Json {- let PushResult {- target,- commit_count,- outcome,- } = result;- let mut payload = serde_json::json!({- "target": target,- "outcome": match outcome {- PushOutcome::FastForwarded => "fast_forwarded",- PushOutcome::UpToDate => "up_to_date",- PushOutcome::MergeCommit { .. } => "merge_commit",- },- "commits": commit_count,- });- if let PushOutcome::MergeCommit { merge_sha } = outcome {- payload["merge_sha"] = serde_json::Value::String(merge_sha);- }- print_json(&payload)?;- }- Ok(())+ finish_output(outcome, format == SwitchFormat::Json)}StepCommand::Rebase { target, format } => {let result = handle_rebase(&Repository::current()?, target.as_deref())?;@@ -1020,8 +971,7 @@ fn format_command_error(error: &anyhow::Error) -> String {use std::fmt::Write;let mut out = String::new();- // An AlreadyDisplayed context retains a child failure as its source for- // structured output, but its presentation marker still suppresses stderr.+ // AlreadyDisplayed retains the source error without printing its diagnostic again.if matches!(error.downcast_ref::<WorktrunkError>(),Some(WorktrunkError::AlreadyDisplayed { .. })@@ -1145,24 +1095,7 @@ fn finish_command(verbose_level: u8, command_line: &str, error: Option<&anyhow::let _ = output::terminate_output();}-fn handle_command_failure(- error: anyhow::Error,- verbose_level: u8,- command_line: &str,- switch_json: bool,-) -> ! {- if switch_json {- // The JSON error carries what stderr shows. A child failure shows- // nothing there (the child spoke for itself), so name its exit instead.- let message = match error.interrupt_signal() {- Some(signal) => format!("Interrupted by signal {signal}"),- None => match format_command_error(&error) {- rendered if rendered.is_empty() => error.root_cause().to_string(),- rendered => rendered.trim_end().to_string(),- },- };- commands::worktree::print_switch_json_error(&message);- }+fn handle_command_failure(error: anyhow::Error, verbose_level: u8, command_line: &str) -> ! {print_command_error(&error);print_cwd_removed_hint_if_needed();@@ -1256,10 +1189,6 @@ fn main() {yes,command,} = cli;- let switch_json = matches!(- command.as_ref(),- Some(Commands::Switch(args)) if args.format == SwitchFormat::Json- );// `WORKTRUNK_VERBOSE` provides a baseline verbosity the `-v`/`-vv` flags// raise but never lower (`max`). It also drives shell completion, which// answers and returns above, before `parse_cli` — see@@ -1317,7 +1246,7 @@ fn main() {})});if let Some(Err(error)) = git_version_result {- handle_command_failure(error, verbose, &command_line, switch_json);+ handle_command_failure(error, verbose, &command_line);}{@@ -1336,7 +1265,7 @@ fn main() {#[cfg(unix)]let operation = match worktrunk::signal_forwarder::CommandOperation::start() {Ok(operation) => operation,- Err(error) => handle_command_failure(error.into(), verbose, &command_line, switch_json),+ Err(error) => handle_command_failure(error.into(), verbose, &command_line),};let result = dispatch_command(command, directory, yes);#[cfg(unix)]@@ -1347,7 +1276,7 @@ fn main() {match result {Ok(()) => finish_command(verbose, &command_line, None),- Err(error) => handle_command_failure(error, verbose, &command_line, switch_json),+ Err(error) => handle_command_failure(error, verbose, &command_line),}}diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex d61794ab6..da0723609 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -43,6 +43,8 @@ use worktrunk::styling::{progress_message, success_message, suggest_command, verbosity, warning_message,};+use super::{CommandFailure, CommandResult};+use super::shell_integration::{compute_shell_warning_reason, explicit_path_hint, git_subcommand_warning,print_shell_activation_hint, should_show_explicit_path_hint,@@ -151,9 +153,9 @@ struct BackgroundRemovalOutcome {////// Shared sequence for both detached HEAD and branch background removal paths./// The caller is responsible for output messages before this call, and hooks-/// after. An outer error means removal was neither completed nor scheduled;-/// the inner result reports branch deletion or cleanup scheduling after removal,-/// so callers register teardown before propagating it. The fate is known synchronously+/// after. An error without a partial fate means removal was neither completed+/// nor scheduled. A partial fate records branch deletion or cleanup scheduling+/// failure after removal, so callers still register teardown. The fate is known synchronously/// except on the detached fallback, whose branch-deletion child runs after this process exits.fn spawn_background_removal(repo: &Repository,@@ -161,7 +163,7 @@ fn spawn_background_removal(removal: &BackgroundRemoval<'_>,log_label: &str,fallback_mode: BackgroundFallbackMode,-) -> anyhow::Result<anyhow::Result<BranchFate>> {+) -> CommandResult<BranchFate> {let spawn = |remove_command: &[OsString], operation: InternalOp| {spawn_detached(repo,@@ -173,17 +175,24 @@ fn spawn_background_removal(.map(|_| ())};let outcome = execute_instant_removal_or_fallback(repo, removal, fallback_mode, spawn)?;+ let branch_fate = outcome.branch_fate.map_err(|error| {+ CommandFailure::with_result(error, BranchFate::Retained(RetainedReason::Failed))+ });match outcome.plan {BackgroundRemovalPlan::Staged(cleanup) => {// Cleanup was scheduled before branch deletion could wait. Preserve// the deletion error (including its interrupt signal) if both fail.- Ok(outcome.branch_fate.and_then(|fate| cleanup.map(|_| fate)))+ branch_fate.and_then(|fate| {+ cleanup+ .map(|_| fate)+ .map_err(|error| CommandFailure::with_result(error, fate))+ })}BackgroundRemovalPlan::Deferred(command) => {spawn(&command, InternalOp::Remove)?;- Ok(outcome.branch_fate)+ branch_fate}- BackgroundRemovalPlan::CompletedSynchronously => Ok(outcome.branch_fate),+ BackgroundRemovalPlan::CompletedSynchronously => branch_fate,}}@@ -1227,7 +1236,7 @@ pub fn handle_remove_output(hook_plan: &ApprovedHookPlan,quiet: bool,announcer: &mut HookAnnouncer<'_>,-) -> anyhow::Result<BranchFate> {+) -> CommandResult<BranchFate> {handle_remove_output_inner(plan, execution, stdin, hook_plan, quiet, false, announcer)}@@ -1240,7 +1249,7 @@ pub fn handle_merge_remove_output(plan: &RemovalPlan,hook_plan: &ApprovedHookPlan,announcer: &mut HookAnnouncer<'_>,-) -> anyhow::Result<BranchFate> {+) -> CommandResult<BranchFate> {handle_remove_output_inner(plan,RemovalExecution::Background(BackgroundFallbackMode::Detached),@@ -1260,7 +1269,7 @@ fn handle_remove_output_inner(quiet: bool,protect_nested_worktrees: bool,announcer: &mut HookAnnouncer<'_>,-) -> anyhow::Result<BranchFate> {+) -> CommandResult<BranchFate> {match plan {RemovalPlan::Worktree {main_path,@@ -1341,7 +1350,7 @@ fn handle_branch_only_output(branch_checked_out_at: Option<&SharedBranchCheckout>,detached_worktree: Option<&Path>,quiet: bool,-) -> anyhow::Result<BranchFate> {+) -> CommandResult<BranchFate> {let pruned = if let Some(path) = prune_entry {Repository::current()?.prune_worktree_entry(path)?;true@@ -1386,7 +1395,9 @@ fn handle_branch_only_output(if let Some(shared) = branch_checked_out_at {print_branch_checked_out_elsewhere(branch_name, shared);}- stderr().flush()?;+ stderr()+ .flush()+ .map_err(|error| CommandFailure::with_result(error, BranchFate::NotAttempted))?;return Ok(BranchFate::NotAttempted);}@@ -1411,11 +1422,15 @@ fn handle_branch_only_output(}r});- handle_branch_deletion_result(result, branch_name)?+ handle_branch_deletion_result(result, branch_name).map_err(|error| {+ CommandFailure::with_result(error, BranchFate::Retained(RetainedReason::Failed))+ })?} else if deletion_mode.is_force() {let repo = worktrunk::git::Repository::current()?;let result = execute_branch_deletion(&repo, branch_name, check_target, true);- handle_branch_deletion_result(result, branch_name)?+ handle_branch_deletion_result(result, branch_name).map_err(|error| {+ CommandFailure::with_result(error, BranchFate::Retained(RetainedReason::Failed))+ })?} else {BranchDeletionDisplay {result: BranchDeletionResult {@@ -1481,8 +1496,11 @@ fn handle_branch_only_output(}}- stderr().flush()?;- Ok(BranchFate::from_outcome(&deletion.result.outcome))+ let fate = BranchFate::from_outcome(&deletion.result.outcome);+ stderr()+ .flush()+ .map_err(|error| CommandFailure::with_result(error, fate))?;+ Ok(fate)}/// Register post-remove and post-switch hooks after worktree removal onto the@@ -1912,7 +1930,7 @@ fn handle_detached_removed_worktree_output(repo: &Repository,ctx: &WorktreeRemovalContext<'_>,announcer: &mut HookAnnouncer<'_>,-) -> anyhow::Result<BranchFate> {+) -> CommandResult<BranchFate> {let fate = if matches!(ctx.execution, RemovalExecution::Foreground) {eprintln!("{}",@@ -1979,14 +1997,23 @@ fn handle_detached_removed_worktree_output(},"detached",ctx.background_fallback(),- )?+ )};// A detached worktree was on no branch, so `{{ branch }}` stays unset for// the post-remove hooks (issue #4009).- spawn_hooks_after_remove(repo, ctx, None, announcer)?;- stderr().flush()?;- fate+ if let Err(failure) = &fate+ && failure.result.is_none()+ {+ return fate;+ }+ let finish = spawn_hooks_after_remove(repo, ctx, None, announcer)+ .and_then(|()| stderr().flush().map_err(Into::into));+ fate.and_then(|fate| {+ finish+ .map(|()| fate)+ .map_err(|error| CommandFailure::with_result(error, fate))+ })}fn handle_named_removed_worktree_foreground(@@ -1994,7 +2021,7 @@ fn handle_named_removed_worktree_foreground(ctx: &WorktreeRemovalContext<'_>,branch_name: &str,announcer: &mut HookAnnouncer<'_>,-) -> anyhow::Result<BranchFate> {+) -> CommandResult<BranchFate> {eprintln!("{}",progress_message(cformat!("Removing <bold>{branch_name}</> worktree..."))@@ -2024,31 +2051,32 @@ fn handle_named_removed_worktree_foreground(.map(cleanup_staged_with_progress).unwrap_or((0, 0));- // Worktree removal happened even if the subsequent branch deletion failed.- // Register teardown before display_info can propagate that failure.- spawn_hooks_after_remove(repo, ctx, Some(branch_name), announcer)?;-- // The observed fate, read before the display path consumes (and, on Err,- // propagates) the deletion result.+ // The worktree is gone even when branch deletion or hook setup failed.let fate = BranchFate::from_result(output.branch_result.as_ref());+ let finish = (|| -> anyhow::Result<()> {+ spawn_hooks_after_remove(repo, ctx, Some(branch_name), announcer)?;- let display_info = RemovalDisplayInfo::from_branch_result(- output.branch_result,- branch_name,- ctx.integration_reason,- ctx.target_branch,- ctx.force_worktree,- )?;+ let display_info = RemovalDisplayInfo::from_branch_result(+ output.branch_result,+ branch_name,+ ctx.integration_reason,+ ctx.target_branch,+ ctx.force_worktree,+ )?;- display_info.print_message(branch_name, true, Some(stats))?;- display_info.print_hints(branch_name, ctx.deletion_mode, ctx.integration_reason)?;- if let Some(shared) = ctx.branch_checked_out_at {- print_branch_checked_out_elsewhere(branch_name, shared);- }- print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;+ display_info.print_message(branch_name, true, Some(stats))?;+ display_info.print_hints(branch_name, ctx.deletion_mode, ctx.integration_reason)?;+ if let Some(shared) = ctx.branch_checked_out_at {+ print_branch_checked_out_elsewhere(branch_name, shared);+ }+ print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;- stderr().flush()?;- Ok(fate)+ stderr().flush()?;+ Ok(())+ })();+ finish+ .map(|()| fate)+ .map_err(|error| CommandFailure::with_result(error, fate))}fn handle_named_removed_worktree_background(@@ -2056,7 +2084,7 @@ fn handle_named_removed_worktree_background(ctx: &WorktreeRemovalContext<'_>,branch_name: &str,announcer: &mut HookAnnouncer<'_>,-) -> anyhow::Result<BranchFate> {+) -> CommandResult<BranchFate> {let display_info = RemovalDisplayInfo::from_precomputed(ctx.deletion_mode,ctx.integration_reason,@@ -2092,18 +2120,28 @@ fn handle_named_removed_worktree_background(},branch_name,ctx.background_fallback(),- )?;+ );- spawn_hooks_after_remove(repo, ctx, Some(branch_name), announcer)?;- stderr().flush()?;- fate+ // No removal took place on an early error, so there is no teardown to run.+ if let Err(failure) = &fate+ && failure.result.is_none()+ {+ return fate;+ }+ let finish = spawn_hooks_after_remove(repo, ctx, Some(branch_name), announcer)+ .and_then(|()| stderr().flush().map_err(Into::into));+ fate.and_then(|fate| {+ finish+ .map(|()| fate)+ .map_err(|error| CommandFailure::with_result(error, fate))+ })}/// Execute and narrate a [`RemovalPlan::Worktree`] plan.fn handle_removed_worktree_output(ctx: WorktreeRemovalContext<'_>,announcer: &mut HookAnnouncer<'_>,-) -> anyhow::Result<BranchFate> {+) -> CommandResult<BranchFate> {// Use main_path for discovery - the worktree being removed might be cwd,// and git operations after removal need a valid working directory.let repo = worktrunk::git::Repository::at(ctx.main_path)?;@@ -2122,11 +2160,12 @@ fn handle_removed_worktree_output(if ctx.protect_nested_worktrees&& let Some(nested) = worktrunk::git::remove::nested_worktree(&repo, ctx.worktree_path)?{- anyhow::bail!(cformat!(+ return Err(anyhow::anyhow!(cformat!("Cannot remove worktree @ <bold>{}</>; contains worktree @ <bold>{}</>",format_path_for_display(ctx.worktree_path),format_path_for_display(&nested)- ));+ ))+ .into());}// The pre-rename `ensure_clean` catches a hook-dirtied worktree, and the@@ -2186,7 +2225,7 @@ fn remove_removed_worktree_silently(repo: &Repository,ctx: &WorktreeRemovalContext<'_>,announcer: &mut HookAnnouncer<'_>,-) -> anyhow::Result<BranchFate> {+) -> CommandResult<BranchFate> {let snapshot = repo.capture_refs()?;let options = RemoveOptions {branch: ctx.branch_name.map(String::from),@@ -2208,7 +2247,8 @@ fn remove_removed_worktree_silently(// Post-remove (and post-switch when the picker cd'd away) hooks — registered// onto the caller's announcer, which `flush`es after this returns.- spawn_hooks_after_remove(repo, ctx, ctx.branch_name, announcer)?;+ spawn_hooks_after_remove(repo, ctx, ctx.branch_name, announcer)+ .map_err(|error| CommandFailure::with_result(error, fate))?;Ok(fate)}diff --git a/src/output/json.rs b/src/output/json.rsindex 8593f7bcf..eeb2bec38 100644--- a/src/output/json.rs+++ b/src/output/json.rs@@ -1,8 +1,66 @@-//! Machine-readable output for commands with a `--format=json` mode.+//! JSON serialization and partial mutation results.+//!+//! Inner operations return typed facts alongside an original failure when work+//! has already completed. Command handlers serialize their final result before+//! returning the error to main for diagnostics and native exit handling.+//! CommandFailure deliberately is not an Error: an ordinary `?` into anyhow+//! must not silently discard completed work.use anyhow::Context;use worktrunk::styling::println;+pub(crate) type CommandResult<T> = Result<T, CommandFailure<T>>;++#[derive(Debug)]+pub(crate) struct CommandFailure<T> {+ // Partial facts can be large; keep the error small without boxing successful results.+ pub(crate) result: Option<Box<T>>,+ pub(crate) error: anyhow::Error,+}++impl<T> CommandFailure<T> {+ pub(crate) fn with_result(error: impl Into<anyhow::Error>, result: T) -> Self {+ Self {+ result: Some(Box::new(result)),+ error: error.into(),+ }+ }++ pub(crate) fn map_result<U>(self, map: impl FnOnce(T) -> U) -> CommandFailure<U> {+ CommandFailure {+ result: self.result.map(|result| Box::new(map(*result))),+ error: self.error,+ }+ }+}++impl<T, E: Into<anyhow::Error>> From<E> for CommandFailure<T> {+ fn from(error: E) -> Self {+ Self {+ result: None,+ error: error.into(),+ }+ }+}++/// Finish an outer command, emitting its available result in JSON mode.+pub(crate) fn finish_output<T: serde::Serialize>(+ outcome: CommandResult<T>,+ json: bool,+) -> anyhow::Result<()> {+ let (result, error) = match outcome {+ Ok(result) => (Some(result), None),+ Err(failure) => (failure.result.map(|result| *result), Some(failure.error)),+ };+ if json && let Some(result) = result {+ print_json(&result)?;+ }+ match error {+ Some(error) => Err(error),+ None => Ok(()),+ }+}+/// Serialize a JSON answer to stdout (pretty, one trailing newline).////// Prints through anstream's `println!`, which drops a `BrokenPipe` writediff --git a/src/output/mod.rs b/src/output/mod.rsindex 2551b298d..f065a383d 100644--- a/src/output/mod.rs+++ b/src/output/mod.rs@@ -3,7 +3,9 @@//! # Architecture//!//! For regular output, use `eprintln!`/`println!` directly (from `worktrunk::styling`-//! for color support); [`print_json`] serializes a `--format=json` answer to stdout.+//! for color support). Command handlers emit JSON with [`print_json`] or+//! [`finish_output`] before returning their error to main. Inner operations+//! retain typed partial results through [`CommandResult`]. Diagnostics stay on stderr.//! This module handles the cd directive that must be communicated to the//! parent shell.//!@@ -56,4 +58,4 @@ pub(crate) use shell_integration::{// Re-export commit generation functionspub(crate) use commit_generation::prompt_commit_generation;// Re-export the JSON answer printer-pub(crate) use json::print_json;+pub(crate) use json::{CommandFailure, CommandResult, finish_output, print_json};diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rsindex a09c584d7..0d64a290c 100644--- a/tests/integration_tests/git_error_display.rs+++ b/tests/integration_tests/git_error_display.rs@@ -589,3 +589,144 @@ fn shell_init_remains_available_on_older_git() {String::from_utf8_lossy(&output.stdout));}++/// Errors before dispatch leave stdout empty and explain the failure on stderr.+#[test]+fn json_failure_before_dispatch() {+ let (_mock_bin, mut cmd) = wt_with_git_version("git version 2.42.4");+ let output = cmd.args(["list", "--format=json"]).output().unwrap();+ assert!(!output.status.success());+ assert!(output.stdout.is_empty());+ assert!(String::from_utf8_lossy(&output.stderr).contains("2.42.4"));+}++/// A dispatched command with no result leaves stdout empty on failure.+#[test]+fn json_failure_without_repository() {+ let output = wt_command()+ .args(["list", "--format=json"])+ .output()+ .unwrap();+ assert!(!output.status.success());+ assert!(output.stdout.is_empty());+ assert!(!output.stderr.is_empty());+}++/// A display-only Git failure must not hide the commit already created.+#[cfg(unix)]+#[rstest::rstest]+#[case::commit("commit", 0)]+#[case::squash_staged_changes("squash", 0)]+#[case::squash_commits("squash", 2)]+fn json_outcome_retains_commit_after_display_failure(+ #[case] command: &str,+ #[case] commits_ahead: usize,+) {+ use std::fs;+ use std::os::unix::fs::PermissionsExt;++ let repo = crate::common::TestRepo::standard();+ repo.run_git(&["checkout", "-b", "late-reporting"]);+ for index in 0..commits_ahead {+ repo.commit_in_worktree(+ repo.root_path(),+ "new.txt",+ &format!("content {index}"),+ &format!("feat: change {index}"),+ );+ }+ assert_eq!(+ repo.git_output(&["rev-list", "--count", "main..HEAD"]),+ commits_ahead.to_string(),+ );+ let previous_head = repo.git_output(&["rev-parse", "HEAD"]);+ if commits_ahead == 0 {+ fs::write(repo.root_path().join("new.txt"), "new content").unwrap();+ }++ // Keep the real commit and full-OID lookup; fail only abbreviation for+ // the success message, after the command has a complete result to retain.+ let wrapper = test_tempdir();+ let real_git = which::which("git").unwrap();+ let script = format!(+ r#"#!/bin/sh+if [ "$1 $2" = 'rev-parse --short' ]; then+ echo 'display abbreviation failed' >&2+ exit 42+fi+exec {} "$@"+"#,+ shell_escape::unix::escape(real_git.to_string_lossy()),+ );+ let wrapper_git = wrapper.path().join("git");+ fs::write(&wrapper_git, script).unwrap();+ fs::set_permissions(&wrapper_git, fs::Permissions::from_mode(0o755)).unwrap();++ let mut paths = vec![wrapper.path().to_path_buf()];+ paths.extend(std::env::split_paths(+ &std::env::var_os("PATH").unwrap_or_default(),+ ));+ let output = repo+ .wt_command()+ .env("PATH", std::env::join_paths(paths).unwrap())+ .env(+ "WORKTRUNK_COMMIT__GENERATION__COMMAND",+ "cat >/dev/null && echo 'feat: retained commit'",+ )+ .args(["step", command, "--format=json", "--no-hooks"])+ .output()+ .unwrap();++ assert!(!output.status.success(), "{output:?}");+ let head = repo.git_output(&["rev-parse", "HEAD"]);+ assert_ne!(head, previous_head, "the commit must have completed");+ let response: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(response["commit"], head, "{response}");+ assert_eq!(response["message"], "feat: retained commit", "{response}");+ assert_eq!(response["stage_mode"], "all", "{response}");+ assert_eq!(repo.git_output(&["rev-list", "--count", "main..HEAD"]), "1");+ if command == "squash" {+ assert_eq!(response["outcome"], "squashed", "{response}");+ }+ assert!(+ String::from_utf8_lossy(&output.stderr).contains("display abbreviation failed"),+ "{response}"+ );+}++/// Post-commit template validation can fail after Git has created the commit.+#[rstest::rstest]+#[case::commit("commit")]+#[case::merge("merge")]+fn json_retains_committed_result_after_invalid_post_commit_hook(#[case] command: &str) {+ let repo = crate::common::TestRepo::standard();+ repo.run_git(&["checkout", "-b", "late-reporting"]);+ let previous_head = repo.git_output(&["rev-parse", "HEAD"]);+ std::fs::write(repo.root_path().join("new.txt"), "new content").unwrap();+ repo.write_test_config("[post-commit]\ninvalid = 'echo {{ unclosed'\n");++ let mut cmd = repo.wt_command();+ if command == "commit" {+ cmd.arg("step");+ }+ cmd.args([command, "--format=json"]);+ if command == "merge" {+ cmd.arg("--no-squash");+ }+ let output = cmd.output().unwrap();++ assert!(!output.status.success(), "{output:?}");+ let head = repo.git_output(&["rev-parse", "HEAD"]);+ assert_ne!(head, previous_head, "the commit must have completed");+ let response: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ if command == "commit" {+ assert_eq!(response["commit"], head, "{response}");+ } else {+ assert_eq!(response["committed"], true, "{response}");+ assert_eq!(response["merged"], false, "{response}");+ assert_eq!(repo.git_output(&["rev-parse", "main"]), previous_head);+ }+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(stderr.contains("syntax error"), "{stderr}");+ assert!(stderr.contains("post-commit"), "{stderr}");+}diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex 93e9aca8a..90dab5fc6 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -2602,7 +2602,7 @@ fn test_merge_pre_remove_dirty_mutation_aborts_cleanup(mut repo: TestRepo) {let output = repo.wt_command().current_dir(&feature_wt)- .args(["merge", "--yes"])+ .args(["merge", "--yes", "--format=json"]).output().unwrap();@@ -2619,6 +2619,13 @@ fn test_merge_pre_remove_dirty_mutation_aborts_cleanup(mut repo: TestRepo) {"dirty feature worktree should not be removed");repo.run_git(&["rev-parse", "--verify", &format!("refs/heads/{branch}")]);+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(json["merged"], true);+ assert!(json["removed"].is_null());+ assert_eq!(+ repo.git_output(&["rev-parse", "main"]),+ repo.git_output(&["rev-parse", branch])+ );let stderr = String::from_utf8_lossy(&output.stderr);assert!(@@ -4888,6 +4895,7 @@ fn test_step_commit_json(repo: TestRepo) {);let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");let sha = parsed["commit"].as_str().expect("commit SHA");+ assert_eq!(sha, repo.git_output(&["rev-parse", "HEAD"]));assert_eq!(sha.len(), 40, "expected full 40-char SHA, got {sha}");assert_eq!(parsed["message"], "feat: add file");// Without --stage on the CLI, the resolved default ("all") is emitted —@@ -5866,6 +5874,7 @@ fn test_merge_json(repo: TestRepo) {"committed": false,"squashed": false,"rebased": false,+ "merged": true,"removed": true}"#);@@ -6398,3 +6407,104 @@ fn test_merge_retains_branch_checked_out_in_another_worktree(mut repo: TestRepo)"output should explain the branch was retained:\n{stderr}",);}++/// The final ref lookup detects concurrent changes after the target ref and+/// worktree have moved. Its failure must retain that completed work for both+/// standalone push and the composing merge command, for either push strategy.+#[cfg(unix)]+#[rstest]+#[case::push_ff(false, false)]+#[case::push_no_ff(false, true)]+#[case::merge_ff(true, false)]+#[case::merge_no_ff(true, true)]+fn json_retains_target_advance_after_post_sync_lookup_failure(+ mut repo: TestRepo,+ #[case] merge: bool,+ #[case] no_ff: bool,+) {+ use std::os::unix::fs::PermissionsExt;++ let feature = repo.add_feature();+ let before = repo.git_output(&["rev-parse", "main"]);+ let source = repo.git_output(&["rev-parse", "feature"]);+ assert_ne!(before, source);+ assert!(!repo.root_path().join("feature.txt").exists());++ let wrapper = crate::common::test_tempdir();+ let synced = wrapper.path().join("synced");+ let script = r#"#!/bin/sh+if [ "$1 $2" = 'rev-parse refs/heads/main' ] && [ -f "$WORKTRUNK_TEST_SYNCED" ]; then+ echo 'injected post-sync lookup failure' >&2+ exit 71+fi+if [ "$3" = 'read-tree' ]; then+ "$WORKTRUNK_TEST_REAL_GIT" "$@" || exit $?+ : > "$WORKTRUNK_TEST_SYNCED"+ exit 0+fi+exec "$WORKTRUNK_TEST_REAL_GIT" "$@"+"#;+ let wrapper_git = wrapper.path().join("git");+ fs::write(&wrapper_git, script).unwrap();+ fs::set_permissions(&wrapper_git, fs::Permissions::from_mode(0o755)).unwrap();+ let (path_var, path) = make_path_with_mock_bin(wrapper.path());+ let mut command = repo.wt_command();+ command+ .current_dir(&feature)+ .env(path_var, path)+ .env("WORKTRUNK_TEST_REAL_GIT", which::which("git").unwrap())+ .env("WORKTRUNK_TEST_SYNCED", &synced);+ if merge {+ command.args([+ "merge",+ "main",+ "--no-commit",+ "--no-squash",+ "--no-rebase",+ "--no-remove",+ "--no-hooks",+ "--yes",+ ]);+ } else {+ command.args(["step", "push", "main"]);+ }+ command.arg("--format=json");+ if no_ff {+ command.arg("--no-ff");+ }+ let output = command.output().unwrap();+ assert!(!output.status.success(), "{output:?}");+ assert!(synced.exists(), "the real worktree sync must have run");+ assert!(String::from_utf8_lossy(&output.stderr).contains("injected post-sync lookup failure"));+ let after = repo.git_output(&["rev-parse", "main"]);+ assert_ne!(after, before);+ assert_eq!(+ fs::read_to_string(repo.root_path().join("feature.txt")).unwrap(),+ "feature content"+ );+ if no_ff {+ assert_eq!(repo.git_output(&["rev-parse", "main^1"]), before);+ assert_eq!(repo.git_output(&["rev-parse", "main^2"]), source);+ } else {+ assert_eq!(after, source);+ }+ let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ if merge {+ assert_eq!(result["merged"], true, "{result}");+ assert_eq!(result["removed"], serde_json::Value::Null, "{result}");+ } else {+ assert_eq!(result["target"], "main");+ assert_eq!(result["commits"], 1);+ assert_eq!(+ result["outcome"],+ if no_ff {+ "merge_commit"+ } else {+ "fast_forwarded"+ }+ );+ if no_ff {+ assert_eq!(result["merge_sha"], after);+ }+ }+}diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex b18118e9d..1b4e34ce0 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -1476,7 +1476,15 @@ exec {real_git} "$@""stderr:\n{stderr}");let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();- assert_eq!(json, serde_json::json!([]), "no removal completed: {json}");+ if boundary == "status" {+ assert_eq!(json, serde_json::json!([]), "{json}");+ } else {+ assert!(!interrupted.exists(), "branch deletion follows removal");+ let items = json.as_array().unwrap();+ assert_eq!(items.len(), 1, "{json}");+ assert_eq!(items[0]["branch"], "interrupted");+ assert_eq!(items[0]["branch_outcome"], "retained_failed");+ }}#[rstest]@@ -3118,28 +3126,34 @@ approved-commands = ["echo 'hook ran' > {}"]/// background case is the load-bearing one: it's the default for `wt remove`,/// and it stages the worktree by renaming it out from under the user, so a/// missing gate there destroys the hook's output rather than refusing.+/// A refusal must neither report removal nor run post-remove teardown.#[rstest]-#[case::foreground(&["--foreground"])]-#[case::background(&[])]+#[case::foreground(&["--foreground"], false)]+#[case::background(&[], false)]+#[case::detached_background(&[], true)]fn test_pre_remove_hook_dirtying_worktree_blocks_remove(mut repo: TestRepo,#[case] execution_args: &[&str],+ #[case] detached: bool,) {- let hook = "echo dirty > hook-created.txt";- repo.write_project_config(&format!(r#"pre-remove = "{hook}""#));- repo.commit("Add config");- repo.write_test_approvals(&format!(- r#"[projects."../origin"]-approved-commands = ["{hook}"]-"#+ let post_remove_marker = repo.root_path().join("post-remove-ran.txt");+ repo.write_project_config(&format!(+ r#"pre-remove = 'echo dirty > hook-created.txt'+post-remove = 'echo removed > "{}"'+"#,+ post_remove_marker.to_slash_lossy(),));+ repo.commit("Add config");let worktree_path = repo.add_worktree("feature-hook-dirties");+ if detached {+ repo.detach_head_in_worktree("feature-hook-dirties");+ }let output = repo.wt_command()- .arg("remove")+ .args(["remove", "--yes", "--format=json"]).args(execution_args)- .arg("feature-hook-dirties")+ .arg(&worktree_path).output().unwrap();@@ -3156,6 +3170,15 @@ approved-commands = ["{hook}"]worktree_path.join("hook-created.txt").exists(),"hook-created file should remain recoverable in the worktree");+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(json, serde_json::json!([]), "no removal completed");+ // Post-remove is approved and would run in the surviving primary worktree.+ // Allow a wrongly scheduled background hook time to create its marker.+ std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);+ assert!(+ !post_remove_marker.exists(),+ "post-remove must not run when removal was refused"+ );}#[rstest]@@ -5351,6 +5374,39 @@ fn test_remove_json(mut repo: TestRepo) {});}+/// A branch lock fails deletion after the worktree was already removed.+/// The partial result must report both facts on foreground and staged removal.+#[rstest]+#[case::foreground(true)]+#[case::background(false)]+fn test_remove_json_branch_failure_has_partial_result(+ mut repo: TestRepo,+ #[case] foreground: bool,+) {+ let worktree = repo.add_worktree("feature");+ fs::write(+ repo.root_path().join(".git/refs/heads/feature.lock"),+ "locked",+ )+ .unwrap();+ let mut command = repo.wt_command();+ command.args(["remove", "feature", "--format=json", "--yes", "--no-hooks"]);+ if foreground {+ command.arg("--foreground");+ }+ let output = command.output().unwrap();+ assert!(!output.status.success(), "{output:?}");+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(json[0]["branch"], "feature");+ assert_eq!(json[0]["branch_outcome"], "retained_failed");+ assert!(+ String::from_utf8_lossy(&output.stderr).contains("lock"),+ "{json}"+ );+ assert!(!worktree.exists());+ repo.run_git(&["rev-parse", "--verify", "refs/heads/feature"]);+}+#[rstest]fn test_remove_json_branch_only(repo: TestRepo) {repo.commit("initial");@@ -5376,6 +5432,31 @@ fn test_remove_json_branch_only(repo: TestRepo) {assert_snapshot!(String::from_utf8_lossy(&output.stdout));}+/// Force-delete bypasses integration checks, but must still report a retained+/// branch when Git refuses its ref transaction.+#[rstest]+fn test_remove_json_force_branch_failure(repo: TestRepo) {+ repo.create_branch("locked-branch");+ fs::write(+ repo.root_path().join(".git/refs/heads/locked-branch.lock"),+ "locked",+ )+ .unwrap();+ let output = repo+ .wt_command()+ .args(["remove", "locked-branch", "-D", "--format=json", "--yes"])+ .output()+ .unwrap();+ assert!(!output.status.success(), "{output:?}");+ let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(result.as_array().unwrap().len(), 1, "{result}");+ assert_eq!(result[0]["branch"], "locked-branch");+ assert_eq!(result[0]["kind"], "branch_only");+ assert_eq!(result[0]["branch_outcome"], "retained_failed");+ assert!(String::from_utf8_lossy(&output.stderr).contains("lock"));+ repo.run_git(&["rev-parse", "--verify", "refs/heads/locked-branch"]);+}+/// `--format=json` carries the detached worktree too. The human output names it/// on stderr, which a script consuming stdout never sees — and "a script/// checking the exit code sees a clean run" is half of what #3769 reported.diff --git a/tests/integration_tests/step_copy_ignored.rs b/tests/integration_tests/step_copy_ignored.rsindex 7f4692607..c0283c742 100644--- a/tests/integration_tests/step_copy_ignored.rs+++ b/tests/integration_tests/step_copy_ignored.rs@@ -867,12 +867,24 @@ fn test_copy_ignored_force_overwrites(mut repo: TestRepo) {// Create existing .env in feature with different content (e.g., generated by env:setup)fs::write(feature_path.join(".env"), "OLD_SECRET=stale").unwrap();- // Without --force: existing file should NOT be overwritten- repo.wt_command()- .args(["step", "copy-ignored"])+ // An existing file is a successful skip: selected entries remain visible,+ // while counts report only actual copies.+ let output = repo+ .wt_command()+ .args(["step", "copy-ignored", "--format=json"]).current_dir(&feature_path).output().unwrap();+ assert!(output.status.success(), "{output:?}");+ let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(result["outcome"], "copied");+ assert_eq!(+ result["entries"],+ serde_json::json!([{"path": ".env", "kind": "file"}])+ );+ for count in ["files", "bytes", "reflinked", "written"] {+ assert_eq!(result[count], 0, "{result}");+ }assert_eq!(fs::read_to_string(feature_path.join(".env")).unwrap(),"OLD_SECRET=stale",@@ -1309,7 +1321,8 @@ fn test_copy_ignored_error_includes_path_directory(mut repo: TestRepo) {fs::create_dir_all(target_dir.join("sub")).unwrap();fs::write(target_dir.join("sub").join("file.txt"), "content").unwrap();- fs::write(repo.root_path().join(".gitignore"), "target/\n").unwrap();+ fs::write(repo.root_path().join("aaa-cache"), "completed").unwrap();+ fs::write(repo.root_path().join(".gitignore"), "aaa-cache\ntarget/\n").unwrap();// Create destination target/sub as read-only so file copy failslet dest_sub = feature_path.join("target").join("sub");@@ -1319,7 +1332,7 @@ fn test_copy_ignored_error_includes_path_directory(mut repo: TestRepo) {// Copy should fail — error message should mention the file pathlet output = repo.wt_command()- .args(["step", "copy-ignored"])+ .args(["step", "copy-ignored", "--format=json"]).current_dir(&feature_path).output().unwrap();@@ -1328,6 +1341,13 @@ fn test_copy_ignored_error_includes_path_directory(mut repo: TestRepo) {fs::set_permissions(&dest_sub, fs::Permissions::from_mode(0o755)).unwrap();assert!(!output.status.success());+ let response: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(response["files"], 1);+ assert_eq!(response["bytes"], 9);+ assert_eq!(+ fs::read_to_string(feature_path.join("aaa-cache")).unwrap(),+ "completed"+ );let stderr = String::from_utf8_lossy(&output.stderr);assert!(stderr.contains("copying"),diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rsindex 451969f65..a3377dbe9 100644--- a/tests/integration_tests/step_prune.rs+++ b/tests/integration_tests/step_prune.rs@@ -496,11 +496,13 @@ fn test_prune_orphan_branch_min_age_without_reflog(repo: TestRepo) {/// candidates. Two month-old packed branches in a bare clone go through a/// `git` shim that holds `packed-b`'s reflog read until `packed-a`'s deletion/// has finished, so `packed-b` is aged after that rewrite; both must still be-/// removed. Unix-only for the same `CreateProcess` shim reason as the canary-/// below.+/// removed. If that later read fails, JSON must retain the earlier removal.+/// Unix-only for the same `CreateProcess` shim reason as the canary below.#[cfg(unix)]#[rstest]-fn test_prune_removals_keep_packed_branch_ages(repo: TestRepo) {+#[case::success(false)]+#[case::scan_failure(true)]+fn test_prune_removals_keep_packed_branch_ages(repo: TestRepo, #[case] scan_failure: bool) {repo.create_branch("packed-a");repo.create_branch("packed-b");let clone = bare_clone(&repo);@@ -517,11 +519,26 @@ fn test_prune_removals_keep_packed_branch_ages(repo: TestRepo) {let barrier_dir = repo.home_path().join("barrier");std::fs::create_dir_all(&barrier_dir).unwrap();cmd.env("WT_TEST_BARRIER_DIR", &barrier_dir);+ if scan_failure {+ cmd.env("WORKTRUNK_TEST_FAIL_REFLOG_READ", "1");+ }- let output = cmd.args(["step", "prune", "--yes"]).output().unwrap();+ let output = cmd+ .args(["step", "prune", "--yes", "--format=json"])+ .output()+ .unwrap();let stderr = String::from_utf8_lossy(&output.stderr);- assert!(output.status.success(), "prune should succeed:\n{stderr}");+ assert_eq!(output.status.success(), !scan_failure, "{stderr}");+ let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ let removed = result.as_array().unwrap();+ assert_eq!(removed.len(), if scan_failure { 1 } else { 2 }, "{result}");+ assert_eq!(removed[0]["branch"], "packed-a");+ assert_eq!(removed[0]["branch_outcome"], "deleted");+ if scan_failure {+ assert!(stderr.contains("checking branch integration"), "{stderr}");+ assert!(stderr.contains("reflog read failed"), "{stderr}");+ }assert!(barrier_dir.join("deleted-packed-a").exists(),"the shim never saw packed-a deleted:\n{stderr}"@@ -538,9 +555,10 @@ fn test_prune_removals_keep_packed_branch_ages(repo: TestRepo) {.unwrap();let branches = String::from_utf8_lossy(&output.stdout);for name in ["packed-a", "packed-b"] {- assert!(- !branches.lines().any(|branch| branch == name),- "{name} should have been pruned:\n{stderr}"+ assert_eq!(+ branches.lines().any(|branch| branch == name),+ scan_failure && name == "packed-b",+ "unexpected retention of {name}:\n{stderr}");}}@@ -1232,6 +1250,53 @@ fn test_prune_json_current_worktree(mut repo: TestRepo) {});}+/// Current-worktree removal runs after the workers finish. A branch lock at+/// that point must report both the earlier removal and the removed checkout.+#[cfg(unix)]+#[rstest]+#[case::foreground(true)]+#[case::background(false)]+fn test_prune_json_current_branch_failure_retains_removals(+ mut repo: TestRepo,+ #[case] foreground: bool,+) {+ repo.commit("initial");+ let original_worktrees = repo.git_output(&["worktree", "list", "--porcelain"]);+ repo.create_branch("earlier-merged");+ let current = repo.add_worktree("current-merged");+ std::fs::write(+ repo.root_path().join(".git/refs/heads/current-merged.lock"),+ "locked",+ )+ .unwrap();++ let mut command = repo.wt_command();+ command+ .current_dir(¤t)+ .args(["step", "prune", "--min-age=0s", "--format=json", "--yes"]);+ if foreground {+ command.arg("--foreground");+ }+ let output = command.output().unwrap();+ assert!(!output.status.success(), "{output:?}");+ let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ let removed = result.as_array().unwrap();+ assert_eq!(removed.len(), 2, "{result}");+ assert_eq!(removed[0]["branch"], "earlier-merged");+ assert_eq!(removed[0]["branch_outcome"], "deleted");+ assert_eq!(removed[1]["branch"], "current-merged");+ assert_eq!(removed[1]["kind"], "current");+ assert_eq!(removed[1]["branch_outcome"], "retained_failed");+ assert!(String::from_utf8_lossy(&output.stderr).contains("lock"));+ assert_eq!(+ repo.git_output(&["worktree", "list", "--porcelain"]),+ original_worktrees+ );+ let branches = repo.git_output(&["branch", "--format=%(refname:short)"]);+ assert!(branches.lines().any(|branch| branch == "current-merged"));+ assert!(!branches.lines().any(|branch| branch == "earlier-merged"));+}+#[rstest]fn test_prune_json_orphan_branch(repo: TestRepo) {repo.commit("initial");@@ -3125,12 +3190,13 @@ fifn test_prune_removal_failure_aborts_remaining_queue(repo: TestRepo) {repo.commit("initial");+ repo.create_branch("abort-0");repo.create_branch("abort-a");repo.create_branch("abort-b");repo.create_branch("abort-c");let mut cmd = repo.wt_command();- cmd.env("RAYON_NUM_THREADS", "1"); // FIFO: abort-a dispatches first+ cmd.env("RAYON_NUM_THREADS", "1"); // FIFO: abort-0 completes before abort-a failslet git_wrapper_dir = repo.home_path().join("git-wrapper");std::fs::create_dir_all(&git_wrapper_dir).unwrap();write_failing_branch_delete_wrapper(&git_wrapper_dir, &which::which("git").unwrap());@@ -3138,7 +3204,7 @@ fn test_prune_removal_failure_aborts_remaining_queue(repo: TestRepo) {cmd.env("WT_TEST_FAIL_DELETE_BRANCH", "abort-a");let output = cmd- .args(["step", "prune", "--yes", "--min-age=0s"])+ .args(["step", "prune", "--yes", "--min-age=0s", "--format=json"]).output().unwrap();let stderr = String::from_utf8_lossy(&output.stderr);@@ -3155,6 +3221,11 @@ fn test_prune_removal_failure_aborts_remaining_queue(repo: TestRepo) {!stderr.contains("Pruned "),"no summary after an aborted run:\n{stderr}");+ let response: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ let completed = response.as_array().unwrap();+ assert_eq!(completed.len(), 1, "{response}");+ assert_eq!(completed[0]["branch"], "abort-0");+ assert_eq!(completed[0]["branch_outcome"], "deleted");let branches = repo.git_output(&["branch", "--format=%(refname:short)"]);assert!(!branches.lines().any(|b| b == "abort-a"),@@ -3261,6 +3332,10 @@ if [ "$1 $2" = "reflog show" ]; thenfisleep 0.05done+ if [ -n "$WORKTRUNK_TEST_FAIL_REFLOG_READ" ]; then+ echo 'reflog read failed' >&2+ exit 7+ fi;;esacfidiff --git a/tests/integration_tests/step_relocate.rs b/tests/integration_tests/step_relocate.rsindex 638fc3057..0b175c8d4 100644--- a/tests/integration_tests/step_relocate.rs+++ b/tests/integration_tests/step_relocate.rs@@ -348,6 +348,133 @@ command = "cat > {} && echo 'chore: auto-commit before relocate'");}+/// A clobber backup can fail after validation has already committed work.+/// Keep that commit and validation skips visible even though no worktree moved.+#[cfg(unix)]+#[rstest]+#[case::json(true)]+#[case::text(false)]+fn test_relocate_json_retains_commits_when_clobber_backup_fails(+ repo: TestRepo,+ #[case] json: bool,+) {+ let parent = worktree_parent(&repo);+ let feature = parent.join("wrong-feature");+ let locked = parent.join("wrong-locked");+ for (branch, path) in [("feature", &feature), ("locked", &locked)] {+ repo.run_git(&["worktree", "add", "-b", branch, path.to_str().unwrap()]);+ }+ repo.run_git(&[+ "worktree",+ "lock",+ "--reason",+ "in use",+ locked.to_str().unwrap(),+ ]);+ fs::write(feature.join("dirty.txt"), "work to retain").unwrap();+ let before = repo.git_output(&["rev-parse", "feature"]);++ // The destination itself is valid on Unix filesystems, but appending the+ // timestamped backup suffix exceeds the 255-byte filename limit. This+ // exercises a real rename failure without depending on permissions/root.+ let destination_name = "x".repeat(250);+ let destination = parent.join(&destination_name);+ fs::write(&destination, "existing blocker").unwrap();+ fs::write(+ repo.test_config_path(),+ format!(+ r#"+worktree-path = "../{{% if branch == 'feature' %}}{destination_name}{{% else %}}repo.{{{{ branch }}}}{{% endif %}}"+[commit.generation]+command = "cat >/dev/null && echo 'commit before failed relocation'"+"#+ ),+ )+ .unwrap();+ let mut command = repo.wt_command();+ command.args([+ "step",+ "relocate",+ "feature",+ "locked",+ "--commit",+ "--clobber",+ ]);+ if json {+ command.arg("--format=json");+ }+ let output = command.output().unwrap();+ assert!(!output.status.success(), "{output:?}");+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(stderr.contains("Failed to move"), "{stderr}");+ assert!(stderr.contains("locked: in use"), "{stderr}");+ let after = repo.git_output(&["rev-parse", "feature"]);+ assert_ne!(+ after, before,+ "validation must have committed the dirty work"+ );+ if json {+ let response: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ let commits = response["commits"].as_array().unwrap();+ assert_eq!(commits.len(), 1, "{response}");+ assert_eq!(commits[0]["branch"], "feature");+ assert_eq!(commits[0]["commit"], after);+ assert_eq!(+ response["skipped"],+ serde_json::json!([{"branch": "locked", "reason": "locked"}])+ );+ assert!(response["entries"].as_array().unwrap().is_empty());+ } else {+ assert!(output.stdout.is_empty(), "{output:?}");+ }+ assert_eq!(+ fs::read_to_string(&destination).unwrap(),+ "existing blocker"+ );+ assert!(feature.is_dir());+ assert!(locked.is_dir());+}++/// Auto-commits are durable even when validating a later worktree fails.+#[rstest]+fn test_relocate_json_retains_commits_before_validation_failure(repo: TestRepo) {+ let parent = worktree_parent(&repo);+ for branch in ["a", "b"] {+ let path = parent.join(format!("wrong-{branch}"));+ repo.run_git(&["worktree", "add", "-b", branch, path.to_str().unwrap()]);+ fs::write(path.join("dirty.txt"), "new work").unwrap();+ }+ let marker = repo.home_path().join("first-commit-generated");+ let marker = shell_escape::unix::escape(marker.to_slash_lossy());+ fs::write(+ repo.test_config_path(),+ format!(+ r#"+[commit.generation]+command = "if test -e {marker}; then exit 1; fi; touch {marker}; echo 'commit before relocation'"+"#+ ),+ )+ .unwrap();+ let output = repo+ .wt_command()+ .args(["step", "relocate", "--commit", "--format=json"])+ .output()+ .unwrap();+ assert!(!output.status.success(), "{output:?}");+ let response: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ let commits = response["commits"].as_array().unwrap();+ assert_eq!(commits.len(), 1, "{response}");+ assert_eq!(commits[0]["branch"], "a");+ assert_eq!(commits[0]["stage_mode"], "all");+ assert_eq!(commits[0]["commit"], repo.git_output(&["rev-parse", "a"]));+ assert!(response["entries"].as_array().unwrap().is_empty());+ assert!(!String::from_utf8_lossy(&output.stderr).is_empty());+ assert!(parent.join("wrong-a").is_dir());+ assert!(parent.join("wrong-b").is_dir());+ assert!(!parent.join("repo.a").exists());+}+/// Create a worktree for `branch` at `path`, stopped on an unresolved/// conflict: `git merge side` leaves the index at stages 1–3 with `<<<<<<<` on/// disk — the state `git add -A` would silently resolve.@@ -459,6 +586,14 @@ command = "cat >/dev/null && echo 'chore: auto-commit before relocate'");let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");+ let commits = parsed["commits"].as_array().unwrap();+ assert_eq!(commits.len(), 1);+ assert_eq!(commits[0]["branch"], "clean");+ assert_eq!(+ commits[0]["commit"],+ repo.git_output(&["rev-parse", "clean"])+ );+let skipped = parsed["skipped"].as_array().expect("skipped array");assert!(skipped@@ -1479,8 +1614,10 @@ worktree-path = "../{{ undefined_var }}.{{ branch }}"/// Windows user hits this too: their shell holds the cwd across the move. So the/// preservation path is reachable, and testable, only on Unix.#[rstest]+#[case::success(false)]+#[case::directive_failure(true)]#[cfg_attr(windows, ignore)]-fn test_relocate_preserves_subdir(repo: TestRepo) {+fn test_relocate_preserves_subdir(repo: TestRepo, #[case] directive_failure: bool) {let parent = worktree_parent(&repo);let (cd_path, _guard) = directive_file();@@ -1496,17 +1633,35 @@ fn test_relocate_preserves_subdir(repo: TestRepo) {]);let subdir = Path::new("apps").join("gateway");fs::create_dir_all(wrong_path.join(&subdir)).unwrap();+ fs::write(wrong_path.join(&subdir).join("dirty.txt"), "new work").unwrap();let mut cmd = repo.wt_command();+ if directive_failure {+ fs::remove_file(&cd_path).unwrap();+ fs::create_dir(&cd_path).unwrap();+ }configure_directive_file(&mut cmd, &cd_path);- cmd.args(["step", "relocate"])+ cmd.args(["step", "relocate", "--commit", "--format=json"]).current_dir(wrong_path.join(&subdir));let output = cmd.output().unwrap();- assert!(- output.status.success(),- "wt step relocate failed: {output:?}"+ assert_eq!(output.status.success(), !directive_failure, "{output:?}");+ let response: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ let entries = response["entries"].as_array().unwrap();+ assert_eq!(entries.len(), 1);+ assert_eq!(entries[0]["branch"], "feature");+ let commits = response["commits"].as_array().unwrap();+ assert_eq!(commits.len(), 1);+ assert_eq!(commits[0]["branch"], "feature");+ assert_eq!(+ commits[0]["commit"],+ repo.git_output(&["rev-parse", "feature"]));+ assert!(parent.join("repo.feature").join(&subdir).is_dir());+ if directive_failure {+ assert!(!String::from_utf8_lossy(&output.stderr).is_empty());+ return;+ }// The cd directive should land in the equivalent subdirectory of the// worktree's new location, not at its root.diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 9e86dc2bf..9f8596f1b 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -8856,7 +8856,7 @@ fn test_switch_format_json_already_at(mut repo: TestRepo) {}#[rstest]-fn test_switch_format_json_failures_emit_one_error(repo: TestRepo) {+fn test_switch_format_json_preserves_output_on_failure(repo: TestRepo) {let early = repo.wt_command().args([@@ -8869,13 +8869,11 @@ fn test_switch_format_json_failures_emit_one_error(repo: TestRepo) {.output().unwrap();assert!(!early.status.success());- let json: serde_json::Value = serde_json::from_slice(&early.stdout).unwrap();- assert_eq!(json.as_object().unwrap().len(), 1);- insta::assert_snapshot!(json["error"].as_str().expect("error is a plain string"), @"- ✗ No branch named missing-json- ↳ To create a new branch, run wt switch --create missing-json; to list branches, run wt list --branches --remotes- ");- assert!(!early.stderr.is_empty());+ assert!(early.stdout.is_empty());+ let stderr = String::from_utf8_lossy(&early.stderr)+ .ansi_strip()+ .into_owned();+ assert!(stderr.contains("No branch named missing-json"), "{stderr}");// An invalid branch name is rejected before any worktree is created.let rejected = repo@@ -8891,17 +8889,14 @@ fn test_switch_format_json_failures_emit_one_error(repo: TestRepo) {.output().unwrap();assert!(!rejected.status.success());- let json: serde_json::Value = serde_json::from_slice(&rejected.stdout).unwrap();- let error = json["error"].as_str().expect("error is a plain string");- assert!(- error.contains("Invalid branch name bad..name"),- "JSON must retain the rejection reason: {error}"- );- assert_eq!(error, error.ansi_strip());- assert!(String::from_utf8_lossy(&rejected.stderr).contains("Invalid branch name"));+ assert!(rejected.stdout.is_empty());+ let stderr = String::from_utf8_lossy(&rejected.stderr)+ .ansi_strip()+ .into_owned();+ assert!(stderr.contains("Invalid branch name bad..name"), "{stderr}");// The worktree is created before --execute fails. The result must describe- // the whole synchronous command, rather than reporting success too early.+ // the completed creation while the exit status reports the execution failure.let late = repo.wt_command().args([@@ -8920,7 +8915,17 @@ fn test_switch_format_json_failures_emit_one_error(repo: TestRepo) {.unwrap();assert_eq!(late.status.code(), Some(7));let json: serde_json::Value = serde_json::from_slice(&late.stdout).unwrap();- assert_eq!(json, serde_json::json!({ "error": "exit code 7" }));+ assert_eq!(json["action"], "created");+ assert_eq!(json["branch"], "failed-json");+ assert_eq!(+ json["path"],+ repo.root_path()+ .parent()+ .unwrap()+ .join("repo.failed-json")+ .to_string_lossy()+ .as_ref()+ );assert!(String::from_utf8_lossy(&late.stderr).contains("child-output"));assert!(repo.root_path()@@ -8931,6 +8936,32 @@ fn test_switch_format_json_failures_emit_one_error(repo: TestRepo) {);}+/// Pre-start is synchronous but runs after creation. Its failure must keep+/// the created path even though the switch pipeline did not reach its output.+#[rstest]+fn test_switch_format_json_pre_start_failure(repo: TestRepo) {+ repo.write_test_config("pre-start = \"exit 7\"\n");+ let output = repo+ .wt_command()+ .args([+ "switch",+ "--create",+ "failed-start",+ "--format=json",+ "--no-cd",+ "--yes",+ ])+ .output()+ .unwrap();+ assert!(!output.status.success());+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(json["action"], "created");+ assert_eq!(json["branch"], "failed-start");+ let path = Path::new(json["path"].as_str().unwrap());+ assert!(path.is_dir());+ assert!(String::from_utf8_lossy(&output.stderr).contains("failed"));+}+#[rstest]fn test_switch_format_json_fetch_failure(#[from(repo_with_remote)] repo: TestRepo) {let github_url = "https://github.com/owner/test-repo.git";@@ -8950,18 +8981,17 @@ fn test_switch_format_json_fetch_failure(#[from(repo_with_remote)] repo: TestRepconfigure_mock_cli_env(&mut cmd, &mock_bin);let output = cmd.output().unwrap();assert!(!output.status.success());- let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();- let message = json["error"].as_str().unwrap();+ assert!(output.stdout.is_empty());+ let message = String::from_utf8_lossy(&output.stderr);assert!(message.contains("does not appear to be a git repository"),- "{json}"+ "{message}");- assert!(message.contains(missing.to_str().unwrap()), "{json}");- assert!(json.get("action").is_none());+ assert!(message.contains(missing.to_str().unwrap()), "{message}");}#[rstest]-fn test_switch_format_json_directive_failure_emits_one_error(repo: TestRepo) {+fn test_switch_format_json_retains_result_after_directive_failure(repo: TestRepo) {// The directory cannot be opened as a CD directive file. That write runs// after the worktree has already been created.let mut cmd = repo.wt_command();@@ -8978,13 +9008,13 @@ fn test_switch_format_json_directive_failure_emits_one_error(repo: TestRepo) {.unwrap();assert!(!output.status.success());let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();- let message = json["error"].as_str().unwrap();+ let message = String::from_utf8_lossy(&output.stderr);assert!(message.contains("Failed to write the cd directive file"),"{message}");assert!(message.contains(repo.root_path().to_str().unwrap()));- assert!(json.get("action").is_none());+ assert_eq!(json["action"], "created");assert!(String::from_utf8_lossy(&output.stderr).contains("Failed to write the cd directive file"));@@ -9020,13 +9050,9 @@ fn test_switch_format_json_early_validation_errors(repo: TestRepo) {.output().unwrap();assert!(!invalid_cwd.status.success());- let json: serde_json::Value = serde_json::from_slice(&invalid_cwd.stdout).unwrap();+ assert!(invalid_cwd.stdout.is_empty());assert!(- json["error"]- .as_str()- .unwrap()- .contains("git rev-parse --git-common-dir"),- "JSON: {json}"+ String::from_utf8_lossy(&invalid_cwd.stderr).contains("git rev-parse --git-common-dir"));// A spawn failure must describe its producer, rather than expose only an@@ -9045,10 +9071,9 @@ fn test_switch_format_json_early_validation_errors(repo: TestRepo) {.unwrap();assert!(!missing_program.status.success());let json: serde_json::Value = serde_json::from_slice(&missing_program.stdout).unwrap();+ assert_eq!(json["action"], "already_at");assert!(- json["error"]- .as_str()- .unwrap()+ String::from_utf8_lossy(&missing_program.stderr).contains("Failed to execute wt-json-missing-executable-14"));}@@ -9076,13 +9101,10 @@ fn test_switch_format_json_execute_signal(repo: TestRepo) {Some(15));let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();- assert_eq!(- json,- serde_json::json!({ "error": "Interrupted by signal 15" })- );+ assert_eq!(json["action"], "already_at");// Hook interruption has its own typed signal error whose terminal display- // is deliberately silent. JSON must still describe the actual signal.+ // is deliberately silent. The exit status still reports the actual signal.repo.write_test_config("pre-switch = \"kill -INT $$\"\n");let interrupted = repo.wt_command()@@ -9113,11 +9135,7 @@ fn test_switch_format_json_execute_signal(repo: TestRepo) {.exists());assert!(!String::from_utf8_lossy(&interrupted.stderr).contains("should-not-run"));- let json: serde_json::Value = serde_json::from_slice(&interrupted.stdout).unwrap();- assert_eq!(- json,- serde_json::json!({ "error": "Interrupted by signal 2" })- );+ assert!(interrupted.stdout.is_empty());}#[rstest]@@ -9324,19 +9342,11 @@ fn test_switch_create_names_branch_left_by_failed_worktree_add(repo: TestRepo, #"expected a recovery suggestion for the leftover branch, got: {stderr}");if json {- let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();- let error = result["error"].as_str().expect("error is a plain string");- assert!(- error.contains("fatal: could not create leading directories"),- "JSON must retain Git's directory-creation error: {error}"- );+ assert!(output.stdout.is_empty());assert!(- error.contains("Branch stranded was created before the failure, with no worktree")- && error.contains("git branch -d -- stranded")- && error.contains("wt switch stranded"),- "JSON must name the leftover branch and both recovery choices: {error}"+ stderr.contains("fatal: could not create leading directories"),+ "{stderr}");- assert_eq!(error, error.ansi_strip());}}diff --git a/tests/integration_tests/switch_picker_dry_run.rs b/tests/integration_tests/switch_picker_dry_run.rsindex 9295c3084..f500c4af2 100644--- a/tests/integration_tests/switch_picker_dry_run.rs+++ b/tests/integration_tests/switch_picker_dry_run.rs@@ -39,8 +39,11 @@ fn install_summary_probe(repo: &mut TestRepo) {/// branch-only row collection, the base cache-dump path, and the `else` branch/// that inserts a config hint in place of real summaries.#[rstest]+#[case::raw(false)]+#[case::explicit_json(true)]fn test_picker_dry_run_emits_configured_rows_and_cache_json(#[from(main_only_repo)] mut repo: TestRepo,+ #[case] json: bool,) {repo.run_git(&["remote", "remove", "origin"]);repo.add_worktree("active-worktree");@@ -64,10 +67,13 @@ fn test_picker_dry_run_emits_configured_rows_and_cache_json(install_summary_probe(&mut repo);let call_log = tempfile::tempdir().unwrap();- let output = repo- .wt_command()- // No `--branches`: the config setting must drive branch collection.- .args(["switch"])+ let mut cmd = repo.wt_command();+ // No `--branches`: the config setting must drive branch collection.+ cmd.arg("switch");+ if json {+ cmd.arg("--format=json");+ }+ let output = cmd.env("WORKTRUNK_PICKER_DRY_RUN", "1")// A configured generator must still stay off while list.summary=false..env("WORKTRUNK_COMMIT__GENERATION__COMMAND", "summary-probe")diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snapindex 6ee246d74..a4c0ce97f 100644--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap@@ -123,8 +123,8 @@ Usage: [1m[36mwt switch[0m [36m[OPTIONS][0m [36m[BRANCH][0m [1m[36m[--[1m[36m--format[0m[36m [0m[36m<FORMAT>[0mOutput format[0m- JSON prints one structured result to stdout once the switch, including any --execute command, completes. Once arguments are accepted, failures print an object with an [1merror[0m string. Argument errors use stderr only. Diagnostics and --execute output go to stderr. A worktree created before a later failure remains in place. Canceling the interactive picker produces no result. Background hooks run independently of the result. Designed for tool integration (e.g., Claude Code WorktreeCreate- hooks).[0m+ JSON prints one structured result to stdout once the switch, including any --execute command, completes. A worktree created before a later failure remains in place and is included in the result. Read stdout even when the exit status is nonzero. Errors, diagnostics, and --execute output go to stderr. Failure before a result exists and canceling the interactive picker produce no result. Background hooks run independently of the result. Designed for tool integration (e.g., Claude Code+ WorktreeCreate hooks).[0m[default: text][possible values: text, json]