workmux 0.1.170

An opinionated workflow tool that orchestrates git worktrees and tmux
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
use anyhow::{Context, Result};
use regex::Regex;
use std::path::Path;
use std::time::SystemTime;
use std::{thread, time::Duration};

use crate::config::MuxMode;
use crate::multiplexer::{Multiplexer, util::prefixed};
use crate::shell::shell_quote;
use crate::{cmd, git};
use tracing::{debug, info, warn};

// Re-export for use by other modules in the workflow
pub use git::get_worktree_mode;

use super::context::WorkflowContext;
use super::types::{CleanupResult, DeferredCleanup};

const WINDOW_CLOSE_DELAY_MS: u64 = 300;

/// Read the worktree's `.git` file to find the admin directory path.
///
/// Linked worktrees have a `.git` file (not directory) containing `gitdir: <path>`.
/// The path may be absolute or relative to the worktree directory.
/// Falls back to `$GIT_COMMON_DIR/worktrees/<dir_name>` if the `.git` file is missing
/// (e.g., the worktree directory was already deleted).
fn resolve_worktree_admin_dir(
    worktree_path: &Path,
    git_common_dir: &Path,
) -> Option<std::path::PathBuf> {
    let git_file = worktree_path.join(".git");
    if git_file.is_file() {
        match std::fs::read_to_string(&git_file) {
            Ok(content) => {
                if let Some(raw) = content.trim().strip_prefix("gitdir: ") {
                    let p = Path::new(raw.trim());
                    let abs = if p.is_absolute() {
                        p.to_path_buf()
                    } else {
                        worktree_path.join(p)
                    };
                    return Some(abs);
                }
                warn!(
                    path = %git_file.display(),
                    "cleanup:worktree .git file missing 'gitdir:' prefix"
                );
            }
            Err(e) => {
                warn!(
                    path = %git_file.display(),
                    error = %e,
                    "cleanup:failed to read worktree .git file"
                );
            }
        }
    }

    // Fallback: construct expected admin dir from the worktree directory name.
    // Git uses the basename of the worktree path as the admin directory name.
    worktree_path
        .file_name()
        .map(|name| git_common_dir.join("worktrees").join(name))
}

/// Best-effort recursive deletion of directory contents.
/// Used to ensure files are removed even if the directory itself is locked (e.g., CWD).
fn remove_dir_contents(path: &Path) {
    if !path.exists() {
        return;
    }

    let entries = match std::fs::read_dir(path) {
        Ok(entries) => entries,
        Err(_) => return,
    };

    for entry in entries.flatten() {
        let entry_path = entry.path();
        let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
        if is_dir {
            let _ = std::fs::remove_dir_all(&entry_path);
        } else {
            let _ = std::fs::remove_file(&entry_path);
        }
    }
}

/// Find all windows matching the base handle pattern (including duplicates).
/// Matches: {prefix}{handle} and {prefix}{handle}-{N}
fn find_matching_windows(mux: &dyn Multiplexer, prefix: &str, handle: &str) -> Result<Vec<String>> {
    let all_windows = mux.get_all_window_names()?;
    let base_name = prefixed(prefix, handle);
    let escaped_base = regex::escape(&base_name);
    let pattern = format!(r"^{}(-\d+)?$", escaped_base);
    let re = Regex::new(&pattern).expect("Invalid regex pattern");

    let matching: Vec<String> = all_windows.into_iter().filter(|w| re.is_match(w)).collect();

    Ok(matching)
}

/// Check if the current window/session matches the base handle pattern (including duplicates).
fn is_inside_matching_target(
    mux: &dyn Multiplexer,
    prefix: &str,
    handle: &str,
    mode: MuxMode,
) -> Result<Option<String>> {
    let current_name = if mode == MuxMode::Session {
        mux.current_session()
    } else {
        mux.current_window_name()?
    };

    let current_name = match current_name {
        Some(name) => name,
        None => return Ok(None),
    };

    let base_name = prefixed(prefix, handle);
    let escaped_base = regex::escape(&base_name);
    let pattern = format!(r"^{}(-\d+)?$", escaped_base);
    let re = Regex::new(&pattern).expect("Invalid regex pattern");

    if re.is_match(&current_name) {
        Ok(Some(current_name))
    } else {
        Ok(None)
    }
}

/// Centralized function to clean up tmux and git resources.
/// `branch_name` is used for git operations (branch deletion).
/// `handle` is used for tmux operations (window/session lookup/kill).
pub fn cleanup(
    context: &WorkflowContext,
    branch_name: &str,
    handle: &str,
    worktree_path: &Path,
    force: bool,
    keep_branch: bool,
    no_hooks: bool,
) -> Result<CleanupResult> {
    // Determine if this worktree was created as a session or window
    let mode = get_worktree_mode(handle);
    let is_session_mode = mode == MuxMode::Session;
    let kind = crate::multiplexer::handle::mode_label(mode);

    info!(
        branch = branch_name,
        handle = handle,
        path = %worktree_path.display(),
        force,
        keep_branch,
        mode = kind,
        "cleanup:start"
    );
    // Change the CWD to main worktree before any destructive operations.
    // This prevents "Unable to read current working directory" errors when the command
    // is run from within the worktree being deleted.
    context.chdir_to_main_worktree()?;

    let mux_running = context.mux.is_running().unwrap_or(false);

    // Check if we're running inside ANY matching target (original or duplicate)
    let current_matching_target = if mux_running {
        is_inside_matching_target(context.mux.as_ref(), &context.prefix, handle, mode)?
    } else {
        None
    };
    let running_inside_target = current_matching_target.is_some();

    let mut result = CleanupResult {
        tmux_window_killed: false,
        worktree_removed: false,
        local_branch_deleted: false,
        window_to_close_later: None,
        trash_path_to_delete: None,
        deferred_cleanup: None,
    };

    // Helper closure to perform the actual filesystem and git cleanup.
    // This avoids code duplication while enforcing the correct operational order.
    let perform_fs_git_cleanup = |result: &mut CleanupResult| -> Result<()> {
        // Resolve the admin dir before the rename so we can unlock it later.
        let worktree_admin_dir = resolve_worktree_admin_dir(worktree_path, &context.git_common_dir);

        // Run pre-remove hooks before removing the worktree directory.
        // Skip if the worktree directory doesn't exist (e.g., user manually deleted it).
        // Skip if --no-hooks is set (e.g., RPC-triggered merge).
        if worktree_path.exists() && !no_hooks {
            if let Some(pre_remove_hooks) = &context.config.pre_remove {
                info!(
                    branch = branch_name,
                    count = pre_remove_hooks.len(),
                    "cleanup:running pre-remove hooks"
                );
                // Resolve absolute paths for environment variables.
                // canonicalize() ensures symlinks are resolved and paths are absolute.
                let abs_worktree_path = worktree_path
                    .canonicalize()
                    .unwrap_or_else(|_| worktree_path.to_path_buf());
                let abs_project_root = context
                    .main_worktree_root
                    .canonicalize()
                    .unwrap_or_else(|_| context.main_worktree_root.clone());
                let worktree_path_str = abs_worktree_path.to_string_lossy();
                let project_root_str = abs_project_root.to_string_lossy();
                let hook_env = [
                    ("WORKMUX_HANDLE", handle),
                    ("WM_HANDLE", handle),
                    ("WM_WORKTREE_PATH", worktree_path_str.as_ref()),
                    ("WM_PROJECT_ROOT", project_root_str.as_ref()),
                ];
                for command in pre_remove_hooks {
                    // Run the hook with the worktree path as the working directory.
                    // This allows for relative paths like `node_modules` in the command.
                    cmd::shell_command_with_env(command, worktree_path, &hook_env).with_context(
                        || format!("Failed to run pre-remove command: '{}'", command),
                    )?;
                }
            }
        } else {
            debug!(
                path = %worktree_path.display(),
                "cleanup:skipping pre-remove hooks, worktree directory does not exist"
            );
        }

        // Track the trash path for best-effort deletion at the end
        let mut trash_path: Option<std::path::PathBuf> = None;

        // 1. Rename the worktree directory to a trash location.
        // This immediately frees the original path for reuse, even if a shell process
        // still has it as CWD (the shell's CWD moves with the rename).
        // This fixes a race condition where running `workmux remove` from inside the
        // target tmux window could leave the directory behind.
        if worktree_path.exists() {
            let parent = worktree_path.parent().unwrap_or_else(|| Path::new("."));
            let dir_name = worktree_path
                .file_name()
                .ok_or_else(|| anyhow::anyhow!("Invalid worktree path: no directory name"))?;

            // Generate unique trash name: .workmux_trash_<name>_<timestamp>
            let timestamp = SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();
            let trash_name = format!(
                ".workmux_trash_{}_{}",
                dir_name.to_string_lossy(),
                timestamp
            );
            let target_trash_path = parent.join(&trash_name);

            debug!(
                from = %worktree_path.display(),
                to = %target_trash_path.display(),
                "cleanup:renaming worktree to trash"
            );

            std::fs::rename(worktree_path, &target_trash_path).with_context(|| {
                format!(
                    "Failed to rename worktree directory to trash location '{}'. \
                    Please close any terminals or editors using this directory and try again.",
                    target_trash_path.display()
                )
            })?;

            trash_path = Some(target_trash_path);
            result.worktree_removed = true;
            info!(branch = branch_name, path = %worktree_path.display(), "cleanup:worktree directory removed");
        }

        // Clean up prompt files (handles both legacy fixed names and timestamped names)
        // Matches: workmux-prompt-{name}.md and workmux-prompt-{name}-{timestamp}.md
        let temp_dir = std::env::temp_dir();
        let prefix = format!("workmux-prompt-{}", branch_name);
        if let Ok(entries) = std::fs::read_dir(&temp_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if let Some(filename) = path.file_name().and_then(|n| n.to_str())
                    && filename.starts_with(&prefix)
                    && filename.ends_with(".md")
                {
                    if let Err(e) = std::fs::remove_file(&path) {
                        warn!(path = %path.display(), error = %e, "cleanup:failed to remove prompt file");
                    } else {
                        debug!(path = %path.display(), "cleanup:prompt file removed");
                    }
                }
            }
        }

        // 2. Remove any worktree lock before pruning.
        // Git creates a "locked" file during `git worktree add` (with content "initializing")
        // and removes it on completion. If creation was interrupted, this file persists and
        // prevents `git worktree prune` from cleaning up the metadata.
        if let Some(ref admin_dir) = worktree_admin_dir {
            let locked_file = admin_dir.join("locked");
            match std::fs::remove_file(&locked_file) {
                Ok(()) => debug!(path = %locked_file.display(), "cleanup:removed worktree lock"),
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
                Err(e) => {
                    warn!(path = %locked_file.display(), error = %e, "cleanup:failed to remove worktree lock")
                }
            }
        }

        // 3. Prune worktrees to clean up git's metadata.
        // Git will see the original path as missing since we renamed it.
        git::prune_worktrees_in(&context.git_common_dir).context("Failed to prune worktrees")?;
        debug!("cleanup:git worktrees pruned");

        // 4. Delete the local branch (unless keeping it).
        if !keep_branch {
            git::delete_branch_in(branch_name, force, &context.git_common_dir)
                .context("Failed to delete local branch")?;
            result.local_branch_deleted = true;
            info!(branch = branch_name, "cleanup:local branch deleted");
        }

        // 5. Best-effort deletion of the trash directory.
        // If the shell is inside this directory, remove_dir_all on the root might fail
        // immediately. Clearing children first ensures we reclaim the space.
        if let Some(tp) = trash_path {
            // If we're deferring window close, also defer trash deletion.
            // This prevents a race condition where processes in the window (e.g., Claude Code)
            // fail to run their stop hooks because their CWD was deleted.
            if result.window_to_close_later.is_some() {
                debug!(path = %tp.display(), "cleanup:deferring trash deletion until window close");
                result.trash_path_to_delete = Some(tp);
            } else {
                // First, aggressively clear contents to reclaim disk space
                remove_dir_contents(&tp);

                // Then try to remove the (now empty) directory
                if let Err(e) = std::fs::remove_dir(&tp) {
                    warn!(
                        path = %tp.display(),
                        error = %e,
                        "cleanup:failed to remove trash directory (likely held by active shell). \
                        The directory is empty and harmless."
                    );
                } else {
                    debug!(path = %tp.display(), "cleanup:trash directory removed");
                }
            }
        }

        Ok(())
    };

    if running_inside_target {
        let current_target = current_matching_target.unwrap();
        info!(
            branch = branch_name,
            current_target = current_target,
            kind,
            "cleanup:running inside matching target, deferring destructive cleanup",
        );

        // Find and kill all OTHER matching windows (not the current one)
        // Note: Sessions don't have duplicates like windows, so skip for session mode
        if mux_running && !is_session_mode {
            let matching_windows =
                find_matching_windows(context.mux.as_ref(), &context.prefix, handle)?;
            let mut killed_count = 0;
            for window in &matching_windows {
                if window != &current_target {
                    if let Err(e) = context.mux.kill_window(window) {
                        warn!(window = window, error = %e, "cleanup:failed to kill duplicate window");
                    } else {
                        killed_count += 1;
                        debug!(window = window, "cleanup:killed duplicate window");
                    }
                }
            }
            if killed_count > 0 {
                info!(
                    count = killed_count,
                    kind, "cleanup:killed duplicate {}s", kind
                );
            }
        }

        // Store the current window/session name for deferred close
        result.window_to_close_later = Some(current_target);

        // Run pre-remove hooks synchronously (they need the worktree intact)
        // Skip if --no-hooks is set (e.g., RPC-triggered merge).
        if worktree_path.exists()
            && !no_hooks
            && let Some(pre_remove_hooks) = &context.config.pre_remove
        {
            info!(
                branch = branch_name,
                count = pre_remove_hooks.len(),
                "cleanup:running pre-remove hooks"
            );
            let abs_worktree_path = worktree_path
                .canonicalize()
                .unwrap_or_else(|_| worktree_path.to_path_buf());
            let abs_project_root = context
                .main_worktree_root
                .canonicalize()
                .unwrap_or_else(|_| context.main_worktree_root.clone());
            let worktree_path_str = abs_worktree_path.to_string_lossy();
            let project_root_str = abs_project_root.to_string_lossy();
            let hook_env = [
                ("WORKMUX_HANDLE", handle),
                ("WM_HANDLE", handle),
                ("WM_WORKTREE_PATH", worktree_path_str.as_ref()),
                ("WM_PROJECT_ROOT", project_root_str.as_ref()),
            ];
            for command in pre_remove_hooks {
                cmd::shell_command_with_env(command, worktree_path, &hook_env)
                    .with_context(|| format!("Failed to run pre-remove command: '{}'", command))?;
            }
        }

        // Clean up prompt files immediately (harmless, doesn't affect CWD)
        let temp_dir = std::env::temp_dir();
        let prefix = format!("workmux-prompt-{}", branch_name);
        if let Ok(entries) = std::fs::read_dir(&temp_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if let Some(filename) = path.file_name().and_then(|n| n.to_str())
                    && filename.starts_with(&prefix)
                    && filename.ends_with(".md")
                {
                    if let Err(e) = std::fs::remove_file(&path) {
                        warn!(path = %path.display(), error = %e, "cleanup:failed to remove prompt file");
                    } else {
                        debug!(path = %path.display(), "cleanup:prompt file removed");
                    }
                }
            }
        }

        // Defer destructive operations (rename, prune, branch delete) until after window/session close.
        // This keeps the worktree path valid so agents can run their hooks.
        if worktree_path.exists() {
            let parent = worktree_path.parent().unwrap_or_else(|| Path::new("."));
            let dir_name = worktree_path
                .file_name()
                .ok_or_else(|| anyhow::anyhow!("Invalid worktree path: no directory name"))?;
            let timestamp = SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();
            let trash_name = format!(
                ".workmux_trash_{}_{}",
                dir_name.to_string_lossy(),
                timestamp
            );
            let trash_path = parent.join(&trash_name);

            // Resolve the admin dir before the worktree is renamed.
            let worktree_admin_dir =
                resolve_worktree_admin_dir(worktree_path, &context.git_common_dir);

            result.deferred_cleanup = Some(DeferredCleanup {
                worktree_path: worktree_path.to_path_buf(),
                trash_path,
                branch_name: branch_name.to_string(),
                handle: handle.to_string(),
                keep_branch,
                force,
                git_common_dir: context.git_common_dir.clone(),
                worktree_admin_dir,
            });
            debug!(
                worktree = %worktree_path.display(),
                kind,
                "cleanup:deferred destructive cleanup until target close",
            );
        }
    } else {
        // Not running inside any matching target, so kill it first
        if mux_running {
            if is_session_mode {
                // For session mode, kill the session directly
                let session_name = prefixed(&context.prefix, handle);
                if context.mux.session_exists(&session_name)? {
                    if let Err(e) = context.mux.kill_session(&session_name) {
                        warn!(session = session_name, error = %e, "cleanup:failed to kill session");
                    } else {
                        result.tmux_window_killed = true;
                        info!(session = session_name, "cleanup:killed session");

                        // Poll to confirm session is gone before proceeding
                        const MAX_RETRIES: u32 = 20;
                        const RETRY_DELAY: Duration = Duration::from_millis(50);
                        for _ in 0..MAX_RETRIES {
                            if !context.mux.session_exists(&session_name)? {
                                break;
                            }
                            thread::sleep(RETRY_DELAY);
                        }
                    }
                }
            } else {
                // For window mode, find and kill all matching windows (including duplicates)
                let matching_windows =
                    find_matching_windows(context.mux.as_ref(), &context.prefix, handle)?;
                let mut killed_count = 0;
                for window in &matching_windows {
                    if let Err(e) = context.mux.kill_window(window) {
                        warn!(window = window, error = %e, "cleanup:failed to kill window");
                    } else {
                        killed_count += 1;
                        debug!(window = window, "cleanup:killed window");
                    }
                }
                if killed_count > 0 {
                    result.tmux_window_killed = true;
                    info!(
                        count = killed_count,
                        handle = handle,
                        "cleanup:killed all matching windows"
                    );

                    // Poll to confirm windows are gone before proceeding
                    const MAX_RETRIES: u32 = 20;
                    const RETRY_DELAY: Duration = Duration::from_millis(50);
                    for _ in 0..MAX_RETRIES {
                        let remaining =
                            find_matching_windows(context.mux.as_ref(), &context.prefix, handle)?;
                        if remaining.is_empty() {
                            break;
                        }
                        thread::sleep(RETRY_DELAY);
                    }
                }
            }
        }
        // Now that windows/sessions are gone, clean up filesystem and git state.
        perform_fs_git_cleanup(&mut result)?;
    }

    // Clean up worktree metadata from git config.
    // Only remove immediately when not deferring -- deferred cleanup includes this
    // in the shell script so metadata survives if the deferred script fails.
    if result.deferred_cleanup.is_none()
        && let Err(e) = git::remove_worktree_meta(handle)
    {
        warn!(handle = handle, error = %e, "cleanup:failed to remove worktree metadata");
    }

    Ok(result)
}

/// Build the deferred cleanup script for rename, prune, branch delete, and trash removal.
///
/// Generates a semicolon-separated sequence of shell commands that:
/// 1. Renames the worktree directory to a trash path (frees the original path)
/// 2. Removes any worktree lock (so prune can clean up the metadata)
/// 3. Prunes git worktree metadata
/// 4. Deletes the local branch (unless `keep_branch` is set)
/// 5. Removes workmux worktree metadata from git config
/// 6. Deletes the trash directory
///
/// The returned string starts with "; " so it can be appended to other commands.
fn build_deferred_cleanup_script(dc: &DeferredCleanup) -> String {
    let wt = shell_quote(&dc.worktree_path.to_string_lossy());
    let trash = shell_quote(&dc.trash_path.to_string_lossy());
    let git_dir = shell_quote(&dc.git_common_dir.to_string_lossy());

    let mut cmds = Vec::new();
    // 1. Rename worktree to trash
    cmds.push(format!("mv {} {} >/dev/null 2>&1", wt, trash));
    // 2. Remove worktree lock if present (git worktree prune skips locked entries)
    if let Some(ref admin_dir) = dc.worktree_admin_dir
        && admin_dir.is_absolute()
    {
        let locked = shell_quote(&admin_dir.join("locked").to_string_lossy());
        cmds.push(format!("rm -f {} >/dev/null 2>&1", locked));
    }
    // 3. Prune git worktrees
    cmds.push(format!("git -C {} worktree prune >/dev/null 2>&1", git_dir));
    // 4. Delete branch (if not keeping)
    if !dc.keep_branch {
        let branch = shell_quote(&dc.branch_name);
        let force_flag = if dc.force { "-D" } else { "-d" };
        cmds.push(format!(
            "git -C {} branch {} {} >/dev/null 2>&1",
            git_dir, force_flag, branch
        ));
    }
    // 5. Remove worktree metadata from git config
    let handle = shell_quote(&dc.handle);
    cmds.push(format!(
        "git -C {} config --local --remove-section workmux.worktree.{} >/dev/null 2>&1",
        git_dir, handle
    ));
    // 6. Delete trash
    cmds.push(format!("rm -rf {} >/dev/null 2>&1", trash));

    format!("; {}", cmds.join("; "))
}

/// Navigate to the target branch window and close the source window.
/// Handles both cases: running inside the source window (async) and outside (sync).
/// `target_window_name` is the window name of the merge target.
/// `source_handle` is the window name of the branch being merged/removed.
pub fn navigate_to_target_and_close(
    mux: &dyn Multiplexer,
    prefix: &str,
    target_window_name: &str,
    source_handle: &str,
    cleanup_result: &CleanupResult,
    mode: MuxMode,
) -> Result<()> {
    use crate::multiplexer::MuxHandle;

    // Check if target window/session exists (probe both modes since target
    // may be a different mode than source, e.g. session worktree -> window main)
    let mux_running = mux.is_running()?;
    let target_full = prefixed(prefix, target_window_name);
    let (target_exists, target_mode) = if mux_running {
        let is_session = mux.session_exists(&target_full).unwrap_or(false);
        let is_window = mux
            .window_exists_by_full_name(&target_full)
            .unwrap_or(false);
        if is_session {
            (true, MuxMode::Session)
        } else if is_window {
            (true, MuxMode::Window)
        } else {
            (false, mode) // doesn't matter, target doesn't exist
        }
    } else {
        (false, mode)
    };
    let kind = crate::multiplexer::handle::mode_label(mode);

    // Prepare window names for shell commands
    // Use the actual window name from window_to_close_later when available (includes -N suffix),
    // otherwise fall back to the base prefixed name
    let source_full = cleanup_result
        .window_to_close_later
        .clone()
        .unwrap_or_else(|| prefixed(prefix, source_handle));

    // Generate backend-specific shell commands for deferred scripts.
    // Kill uses source mode, select uses target's detected mode.
    let kill_source_cmd = MuxHandle::shell_kill_cmd_full(mux, mode, &source_full).ok();
    let select_target_cmd = MuxHandle::shell_select_cmd_full(mux, target_mode, &target_full).ok();

    debug!(
        prefix = prefix,
        target_window_name = target_window_name,
        mux_running = mux_running,
        target_exists = target_exists,
        kind,
        window_to_close = ?cleanup_result.window_to_close_later,
        deferred_cleanup = cleanup_result.deferred_cleanup.is_some(),
        "navigate_to_target_and_close:entry"
    );

    if !mux_running || !target_exists {
        // If target window doesn't exist, still need to close source window if running inside it
        if let Some(ref window_to_close) = cleanup_result.window_to_close_later {
            let delay = Duration::from_millis(WINDOW_CLOSE_DELAY_MS);
            let delay_secs = format!("{:.3}", delay.as_secs_f64());

            // Build cleanup script: prefer full deferred cleanup, fall back to trash-only
            let cleanup_script = if let Some(ref dc) = cleanup_result.deferred_cleanup {
                build_deferred_cleanup_script(dc)
            } else {
                cleanup_result
                    .trash_path_to_delete
                    .as_ref()
                    .map(|tp| format!("; rm -rf {}", shell_quote(&tp.to_string_lossy())))
                    .unwrap_or_default()
            };

            // For session mode, switch to the last session before killing so
            // the client returns to where the user was previously instead of
            // tmux picking an arbitrary session.
            let switch_last_part = if mode == MuxMode::Session {
                mux.shell_switch_to_last_session_cmd()
                    .ok()
                    .map(|cmd| format!("{}; ", cmd))
                    .unwrap_or_default()
            } else {
                String::new()
            };

            let kill_part = kill_source_cmd
                .as_ref()
                .map(|cmd| format!("{}; ", cmd))
                .unwrap_or_default();

            let script = format!(
                "sleep {delay}; {switch}{kill}{cleanup}",
                delay = delay_secs,
                switch = switch_last_part,
                kill = kill_part,
                cleanup = cleanup_script.strip_prefix("; ").unwrap_or(&cleanup_script),
            );
            debug!(
                script = script,
                kind, "navigate_to_target_and_close:kill_only_script"
            );
            match mux.run_deferred_script(&script) {
                Ok(_) => info!(
                    target = window_to_close,
                    script = script,
                    kind,
                    "cleanup:scheduled target close",
                ),
                Err(e) => warn!(
                    target = window_to_close,
                    error = ?e,
                    kind,
                    "cleanup:failed to schedule target close",
                ),
            }
        }
        return Ok(());
    }

    if cleanup_result.window_to_close_later.is_some() {
        // Running inside a matching window: schedule navigation and kill together
        let delay = Duration::from_millis(WINDOW_CLOSE_DELAY_MS);
        let delay_secs = format!("{:.3}", delay.as_secs_f64());

        // Build cleanup script: prefer full deferred cleanup, fall back to trash-only
        let cleanup_script = if let Some(ref dc) = cleanup_result.deferred_cleanup {
            build_deferred_cleanup_script(dc)
        } else {
            cleanup_result
                .trash_path_to_delete
                .as_ref()
                .map(|tp| format!("; rm -rf {}", shell_quote(&tp.to_string_lossy())))
                .unwrap_or_default()
        };

        // Navigate to target window before killing source
        let select_part = select_target_cmd
            .as_ref()
            .map(|cmd| format!("{}; ", cmd))
            .unwrap_or_default();

        let kill_part = kill_source_cmd
            .as_ref()
            .map(|cmd| format!("{}; ", cmd))
            .unwrap_or_default();

        let script = format!(
            "sleep {delay}; {select}{kill}{cleanup}",
            delay = delay_secs,
            select = select_part,
            kill = kill_part,
            cleanup = cleanup_script.strip_prefix("; ").unwrap_or(&cleanup_script),
        );
        debug!(
            script = script,
            kind, "navigate_to_target_and_close:nav_and_kill_script"
        );

        match mux.run_deferred_script(&script) {
            Ok(_) => info!(
                source = source_handle,
                target = target_window_name,
                kind,
                "cleanup:scheduled navigation to target and source close",
            ),
            Err(e) => warn!(
                source = source_handle,
                error = ?e,
                kind,
                "cleanup:failed to schedule navigation and source close",
            ),
        }
    } else if !cleanup_result.tmux_window_killed {
        // Running outside and targets weren't killed yet (shouldn't happen normally)
        // but handle it for completeness
        let target = MuxHandle::new(mux, target_mode, prefix, target_window_name);
        target.select()?;
        info!(
            handle = source_handle,
            target = target_window_name,
            kind,
            "cleanup:navigated to target branch",
        );
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    fn make_deferred_cleanup(
        worktree: &str,
        trash: &str,
        branch: &str,
        handle: &str,
        git_dir: &str,
        keep_branch: bool,
        force: bool,
    ) -> DeferredCleanup {
        DeferredCleanup {
            worktree_path: PathBuf::from(worktree),
            trash_path: PathBuf::from(trash),
            branch_name: branch.to_string(),
            handle: handle.to_string(),
            keep_branch,
            force,
            git_common_dir: PathBuf::from(git_dir),
            worktree_admin_dir: None,
        }
    }

    #[test]
    fn deferred_cleanup_script_includes_all_steps() {
        let dc = make_deferred_cleanup(
            "/repo/worktrees/feature",
            "/repo/worktrees/.workmux_trash_feature_123",
            "feature",
            "feature",
            "/repo/.git",
            false,
            false,
        );

        let script = build_deferred_cleanup_script(&dc);

        assert!(script.contains(
            "mv /repo/worktrees/feature /repo/worktrees/.workmux_trash_feature_123 >/dev/null 2>&1"
        ));
        assert!(script.contains("git -C /repo/.git worktree prune >/dev/null 2>&1"));
        assert!(script.contains("git -C /repo/.git branch -d feature >/dev/null 2>&1"));
        assert!(script.contains("git -C /repo/.git config --local --remove-section workmux.worktree.feature >/dev/null 2>&1"));
        assert!(
            script.contains("rm -rf /repo/worktrees/.workmux_trash_feature_123 >/dev/null 2>&1")
        );
    }

    #[test]
    fn deferred_cleanup_script_keep_branch_skips_branch_delete() {
        let dc = make_deferred_cleanup(
            "/repo/worktrees/feature",
            "/repo/worktrees/.trash",
            "feature",
            "feature",
            "/repo/.git",
            true, // keep_branch
            false,
        );

        let script = build_deferred_cleanup_script(&dc);

        assert!(
            !script.contains("branch -d"),
            "Should not delete branch when keep_branch is set"
        );
        assert!(
            !script.contains("branch -D"),
            "Should not delete branch when keep_branch is set"
        );
        // Other steps should still be present
        assert!(script.contains("mv "));
        assert!(script.contains("worktree prune"));
        assert!(script.contains("config --local --remove-section"));
        assert!(script.contains("rm -rf"));
    }

    #[test]
    fn deferred_cleanup_script_force_uses_capital_d() {
        let dc = make_deferred_cleanup(
            "/repo/worktrees/feature",
            "/repo/worktrees/.trash",
            "feature",
            "feature",
            "/repo/.git",
            false,
            true, // force
        );

        let script = build_deferred_cleanup_script(&dc);

        assert!(
            script.contains("branch -D feature"),
            "Force delete should use -D flag"
        );
        assert!(
            !script.contains("branch -d feature"),
            "Force delete should not use -d flag"
        );
    }

    #[test]
    fn deferred_cleanup_script_quotes_paths_with_spaces() {
        let dc = make_deferred_cleanup(
            "/my repo/worktrees/my feature",
            "/my repo/worktrees/.trash_123",
            "my-feature",
            "my-feature",
            "/my repo/.git",
            false,
            false,
        );

        let script = build_deferred_cleanup_script(&dc);

        assert!(
            script.contains("'/my repo/worktrees/my feature'"),
            "Worktree path with spaces should be quoted: {script}"
        );
        assert!(
            script.contains("'/my repo/worktrees/.trash_123'"),
            "Trash path with spaces should be quoted: {script}"
        );
        assert!(
            script.contains("'/my repo/.git'"),
            "Git dir with spaces should be quoted: {script}"
        );
    }

    #[test]
    fn deferred_cleanup_script_preserves_command_order() {
        let dc = make_deferred_cleanup(
            "/repo/wt/feat",
            "/repo/wt/.trash",
            "feat",
            "feat",
            "/repo/.git",
            false,
            false,
        );

        let script = build_deferred_cleanup_script(&dc);

        // Commands must execute in this order for correctness:
        // mv (free original path) -> prune (update git metadata) ->
        // branch delete -> config remove -> rm (delete trash)
        let mv_pos = script.find("mv ").expect("should contain mv");
        let prune_pos = script.find("worktree prune").expect("should contain prune");
        let branch_pos = script.find("branch -d").expect("should contain branch -d");
        let config_pos = script
            .find("config --local --remove-section")
            .expect("should contain config remove");
        let rm_pos = script.find("rm -rf").expect("should contain rm -rf");

        assert!(mv_pos < prune_pos, "mv should precede prune");
        assert!(prune_pos < branch_pos, "prune should precede branch delete");
        assert!(
            branch_pos < config_pos,
            "branch delete should precede config remove"
        );
        assert!(config_pos < rm_pos, "config remove should precede rm");
    }

    #[test]
    fn deferred_cleanup_script_starts_with_separator() {
        let dc = make_deferred_cleanup(
            "/repo/wt/feat",
            "/repo/wt/.trash",
            "feat",
            "feat",
            "/repo/.git",
            false,
            false,
        );

        let script = build_deferred_cleanup_script(&dc);

        assert!(
            script.starts_with("; "),
            "Script should start with '; ' so it can be appended to other commands: {script}"
        );
    }

    #[test]
    fn deferred_cleanup_script_simple_paths_not_quoted() {
        let dc = make_deferred_cleanup(
            "/repo/worktrees/feature-branch",
            "/repo/worktrees/.trash_feature",
            "feature-branch",
            "feature-branch",
            "/repo/.git",
            false,
            false,
        );

        let script = build_deferred_cleanup_script(&dc);

        // Simple paths (alphanumeric, dash, underscore, dot, slash) should not be quoted
        assert!(
            script.contains("mv /repo/worktrees/feature-branch /repo/worktrees/.trash_feature"),
            "Simple paths should not be quoted: {script}"
        );
    }

    #[test]
    fn deferred_cleanup_script_removes_lock_when_admin_dir_set() {
        let mut dc = make_deferred_cleanup(
            "/repo/worktrees/feature",
            "/repo/worktrees/.trash",
            "feature",
            "feature",
            "/repo/.git",
            false,
            false,
        );
        dc.worktree_admin_dir = Some(PathBuf::from("/repo/.git/worktrees/feature"));

        let script = build_deferred_cleanup_script(&dc);

        assert!(
            script.contains("rm -f /repo/.git/worktrees/feature/locked"),
            "Should remove lock file when admin dir is set: {script}"
        );

        // Lock removal should happen after mv but before prune
        let mv_pos = script.find("mv ").unwrap();
        let lock_pos = script
            .find("rm -f /repo/.git/worktrees/feature/locked")
            .unwrap();
        let prune_pos = script.find("worktree prune").unwrap();
        assert!(mv_pos < lock_pos, "lock removal should follow mv");
        assert!(lock_pos < prune_pos, "lock removal should precede prune");
    }

    #[test]
    fn deferred_cleanup_script_no_lock_step_without_admin_dir() {
        let dc = make_deferred_cleanup(
            "/repo/worktrees/feature",
            "/repo/worktrees/.trash",
            "feature",
            "feature",
            "/repo/.git",
            false,
            false,
        );

        let script = build_deferred_cleanup_script(&dc);

        assert!(
            !script.contains("/locked"),
            "Should not have lock removal without admin dir: {script}"
        );
    }
}