worktrunk 0.36.0

A CLI for Git worktree management, designed for parallel AI agent workflows
Documentation
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
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
//! Step commands for the merge workflow and standalone worktree utilities.
//!
//! Merge steps:
//! - `step_commit` - Commit working tree changes
//! - `handle_squash` - Squash commits into one
//! - `step_show_squash_prompt` - Show squash prompt without executing
//! - `handle_rebase` - Rebase onto target branch
//! - `step_diff` - Show all changes since branching
//!
//! Standalone:
//! - `step_copy_ignored` - Copy gitignored files matching .worktreeinclude
//! - `handle_promote` - Swap a branch into the main worktree
//! - `step_prune` - Remove worktrees merged into the default branch

use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::Context;
use color_print::cformat;
use crossbeam_channel as chan;
use ignore::gitignore::GitignoreBuilder;
use rayon::prelude::*;
use worktrunk::HookType;
use worktrunk::config::{CopyIgnoredConfig, UserConfig};
use worktrunk::copy::{copy_dir_recursive, copy_leaf};
use worktrunk::git::{Repository, WorktreeInfo};
use worktrunk::path::format_path_for_display;
use worktrunk::shell_exec::Cmd;
use worktrunk::styling::{
    eprintln, format_with_gutter, hint_message, info_message, progress_message, success_message,
    verbosity, warning_message,
};

use super::command_approval::approve_hooks;
use super::commit::{CommitGenerator, CommitOptions, StageMode};
use super::context::CommandEnv;
use super::hooks::{
    HookCommandSpec, HookFailureStrategy, prepare_background_hooks, run_hook_with_filter,
    spawn_hook_pipeline,
};
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
use super::worktree::BranchDeletionMode;
use crate::output::handle_remove_output;

/// Handle `wt step commit` command
///
/// `stage` is the CLI-provided stage mode. If None, uses the effective config default.
pub fn step_commit(
    branch: Option<String>,
    yes: bool,
    verify: bool,
    stage: Option<StageMode>,
    show_prompt: bool,
) -> anyhow::Result<()> {
    // Handle --show-prompt early: just build and output the prompt
    if show_prompt {
        let repo = worktrunk::git::Repository::current()?;
        let config = UserConfig::load().context("Failed to load config")?;
        let project_id = repo.project_identifier().ok();
        let commit_config = config.commit_generation(project_id.as_deref());
        let prompt = crate::llm::build_commit_prompt(&commit_config)?;
        println!("{}", prompt);
        return Ok(());
    }

    // Load config once, run LLM setup prompt, then reuse config
    let mut config = UserConfig::load().context("Failed to load config")?;
    // One-time LLM setup prompt (errors logged internally; don't block commit)
    let _ = crate::output::prompt_commit_generation(&mut config);

    let env = match branch {
        Some(ref b) => CommandEnv::for_branch("commit", config, b)?,
        None => CommandEnv::for_action("commit", config)?,
    };
    let ctx = env.context(yes);

    // CLI flag overrides config value
    let stage_mode = stage.unwrap_or(env.resolved().commit.stage());

    // "Approve at the Gate": approve commit hooks upfront (unless --no-hooks)
    // Shadow verify: if user declines approval, skip hooks but continue commit
    let verify = if verify {
        let approved = approve_hooks(&ctx, &[HookType::PreCommit, HookType::PostCommit])?;
        if !approved {
            eprintln!(
                "{}",
                info_message("Commands declined, committing without hooks",)
            );
            false
        } else {
            true
        }
    } else {
        false // --no-hooks was passed
    };

    let mut options = CommitOptions::new(&ctx);
    options.verify = verify;
    options.stage_mode = stage_mode;
    options.show_no_squash_note = false;
    // Only warn about untracked if we're staging all
    options.warn_about_untracked = stage_mode == StageMode::All;

    options.commit()
}

/// Result of a squash operation
#[derive(Debug, Clone)]
pub enum SquashResult {
    /// Squash or commit occurred
    Squashed,
    /// Nothing to squash: no commits ahead of target branch
    NoCommitsAhead(String),
    /// Nothing to squash: already a single commit
    AlreadySingleCommit,
    /// Squash attempted but resulted in no net changes (commits canceled out)
    NoNetChanges,
}

/// Handle shared squash workflow (used by `wt step squash` and `wt merge`)
///
/// # Arguments
/// * `verify` - If true, run pre-commit hooks (false when --no-hooks flag is passed)
/// * `stage` - CLI-provided stage mode. If None, uses the effective config default.
pub fn handle_squash(
    target: Option<&str>,
    yes: bool,
    verify: bool,
    stage: Option<StageMode>,
) -> anyhow::Result<SquashResult> {
    // Load config once, run LLM setup prompt, then reuse config
    let mut config = UserConfig::load().context("Failed to load config")?;
    // One-time LLM setup prompt (errors logged internally; don't block commit)
    let _ = crate::output::prompt_commit_generation(&mut config);

    let env = CommandEnv::for_action("squash", config)?;
    let repo = &env.repo;
    // Squash requires being on a branch (can't squash in detached HEAD)
    let current_branch = env.require_branch("squash")?.to_string();
    let ctx = env.context(yes);
    let resolved = env.resolved();
    let generator = CommitGenerator::new(&resolved.commit_generation);

    // CLI flag overrides config value
    let stage_mode = stage.unwrap_or(resolved.commit.stage());

    // Check if any pre-commit hooks exist (needed for skip message and approval)
    let project_config = repo.load_project_config()?;
    let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());
    let (user_cfg, proj_cfg) = super::hooks::lookup_hook_configs(
        &user_hooks,
        project_config.as_ref(),
        HookType::PreCommit,
    );
    let any_hooks_exist = user_cfg.is_some() || proj_cfg.is_some();

    // "Approve at the Gate": approve commit hooks upfront (unless --no-hooks)
    // Shadow verify: if user declines approval, skip hooks but continue squash
    let verify = if verify {
        let approved = approve_hooks(&ctx, &[HookType::PreCommit, HookType::PostCommit])?;
        if !approved {
            eprintln!(
                "{}",
                info_message("Commands declined, squashing without hooks")
            );
            false
        } else {
            true
        }
    } else {
        // Show skip message when --no-hooks was passed and hooks exist
        if any_hooks_exist {
            eprintln!("{}", info_message("Skipping pre-commit hooks (--no-hooks)"));
        }
        false // --no-hooks was passed
    };

    // Get and validate target ref (any commit-ish for merge-base calculation)
    let integration_target = repo.require_target_ref(target)?;

    // Auto-stage changes before running pre-commit hooks so both beta and merge paths behave identically
    match stage_mode {
        StageMode::All => {
            repo.warn_if_auto_staging_untracked()?;
            repo.run_command(&["add", "-A"])
                .context("Failed to stage changes")?;
        }
        StageMode::Tracked => {
            repo.run_command(&["add", "-u"])
                .context("Failed to stage tracked changes")?;
        }
        StageMode::None => {
            // Stage nothing - use what's already staged
        }
    }

    // Run pre-commit hooks (user first, then project)
    if verify {
        let extra_vars = [("target", integration_target.as_str())];
        run_hook_with_filter(
            &ctx,
            HookCommandSpec {
                user_config: user_cfg,
                project_config: proj_cfg,
                hook_type: HookType::PreCommit,
                extra_vars: &extra_vars,
                name_filters: &[],
                display_path: crate::output::pre_hook_display_path(ctx.worktree_path),
            },
            HookFailureStrategy::FailFast,
        )
        .map_err(worktrunk::git::add_hook_skip_hint)?;
    }

    // Get merge base with target branch (required for squash)
    let merge_base = repo
        .merge_base("HEAD", &integration_target)?
        .context("Cannot squash: no common ancestor with target branch")?;

    // Count commits since merge base
    let commit_count = repo.count_commits(&merge_base, "HEAD")?;

    // Check if there are staged changes in addition to commits
    let wt = repo.current_worktree();
    let has_staged = wt.has_staged_changes()?;

    // Handle different scenarios
    if commit_count == 0 && !has_staged {
        // No commits and no staged changes - nothing to squash
        return Ok(SquashResult::NoCommitsAhead(integration_target));
    }

    if commit_count == 0 && has_staged {
        // Just staged changes, no commits - commit them directly (no squashing needed)
        generator.commit_staged_changes(&wt, true, true, stage_mode)?;
        return Ok(SquashResult::Squashed);
    }

    if commit_count == 1 && !has_staged {
        // Single commit, no staged changes - already squashed
        return Ok(SquashResult::AlreadySingleCommit);
    }

    // Either multiple commits OR single commit with staged changes - squash them
    // Get diff stats early for display in progress message
    let range = format!("{}..HEAD", merge_base);

    let commit_text = if commit_count == 1 {
        "commit"
    } else {
        "commits"
    };

    // Get total stats (commits + any working tree changes)
    let total_stats = if has_staged {
        repo.diff_stats_summary(&["diff", "--shortstat", &merge_base, "--cached"])
    } else {
        repo.diff_stats_summary(&["diff", "--shortstat", &range])
    };

    let with_changes = if has_staged {
        match stage_mode {
            StageMode::Tracked => " & tracked changes",
            _ => " & working tree changes",
        }
    } else {
        ""
    };

    // Build parenthesized content: stats only (stage mode is in message text)
    let parts = total_stats;

    let squash_progress = if parts.is_empty() {
        format!("Squashing {commit_count} {commit_text}{with_changes} into a single commit...")
    } else {
        // Gray parenthetical with separate cformat for closing paren (avoids optimizer)
        let parts_str = parts.join(", ");
        let paren_close = cformat!("<bright-black>)</>");
        cformat!(
            "Squashing {commit_count} {commit_text}{with_changes} into a single commit <bright-black>({parts_str}</>{paren_close}..."
        )
    };
    eprintln!("{}", progress_message(squash_progress));

    // Create safety backup before potentially destructive reset if there are working tree changes
    if has_staged {
        let backup_message = format!("{} → {} (squash)", current_branch, integration_target);
        let sha = wt.create_safety_backup(&backup_message)?;
        eprintln!("{}", hint_message(format!("Backup created @ {sha}")));
    }

    // Get commit subjects for the squash message
    let subjects = repo.commit_subjects(&range)?;

    // Generate squash commit message
    eprintln!(
        "{}",
        progress_message("Generating squash commit message...")
    );

    generator.emit_hint_if_needed();

    // Get current branch and repo name for template variables
    let repo_root = wt.root()?;
    let repo_name = repo_root
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("repo");

    let commit_message = crate::llm::generate_squash_message(
        &integration_target,
        &merge_base,
        &subjects,
        &current_branch,
        repo_name,
        &resolved.commit_generation,
    )?;

    // Display the generated commit message
    let formatted_message = generator.format_message_for_display(&commit_message);
    eprintln!("{}", format_with_gutter(&formatted_message, None));

    // Reset to merge base (soft reset stages all changes, including any already-staged uncommitted changes)
    //
    // TOCTOU note: Between this reset and the commit below, an external process could
    // modify the staging area. This is extremely unlikely (requires precise timing) and
    // the consequence is minor (unexpected content in squash commit). The commit message
    // generated above accurately reflects the original commits being squashed, so any
    // discrepancy would be visible in the diff. Considered acceptable risk.
    repo.run_command(&["reset", "--soft", &merge_base])
        .context("Failed to reset to merge base")?;

    // Check if there are actually any changes to commit
    if !wt.has_staged_changes()? {
        eprintln!(
            "{}",
            info_message(format!(
                "No changes after squashing {commit_count} {commit_text}"
            ))
        );
        return Ok(SquashResult::NoNetChanges);
    }

    // Commit with the generated message
    repo.run_command(&["commit", "-m", &commit_message])
        .context("Failed to create squash commit")?;

    // Get commit hash for display
    let commit_hash = repo
        .run_command(&["rev-parse", "--short", "HEAD"])?
        .trim()
        .to_string();

    // Show success immediately after completing the squash
    eprintln!(
        "{}",
        success_message(cformat!("Squashed @ <dim>{commit_hash}</>"))
    );

    // Spawn post-commit hooks in background (respects --no-hooks)
    if verify {
        let extra_vars: Vec<(&str, &str)> = vec![("target", integration_target.as_str())];
        for steps in prepare_background_hooks(&ctx, HookType::PostCommit, &extra_vars, None)? {
            spawn_hook_pipeline(&ctx, steps)?;
        }
    }

    Ok(SquashResult::Squashed)
}

/// Handle `wt step squash --show-prompt`
///
/// Builds and outputs the squash prompt without running the LLM or squashing.
pub fn step_show_squash_prompt(target: Option<&str>) -> anyhow::Result<()> {
    let repo = Repository::current()?;
    let config = UserConfig::load().context("Failed to load config")?;
    let project_id = repo.project_identifier().ok();
    let effective_config = config.commit_generation(project_id.as_deref());

    // Get and validate target ref (any commit-ish for merge-base calculation)
    let integration_target = repo.require_target_ref(target)?;

    // Get current branch
    let wt = repo.current_worktree();
    let current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());

    // Get merge base with target branch (required for generating squash message)
    let merge_base = repo
        .merge_base("HEAD", &integration_target)?
        .context("Cannot generate squash message: no common ancestor with target branch")?;

    // Get commit subjects for the squash message
    let range = format!("{}..HEAD", merge_base);
    let subjects = repo.commit_subjects(&range)?;

    // Get repo name from directory
    let repo_root = wt.root()?;
    let repo_name = repo_root
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("repo");

    let prompt = crate::llm::build_squash_prompt(
        &integration_target,
        &merge_base,
        &subjects,
        &current_branch,
        repo_name,
        &effective_config,
    )?;
    println!("{}", prompt);
    Ok(())
}

/// Result of a rebase operation
pub enum RebaseResult {
    /// Rebase occurred (either true rebase or fast-forward)
    Rebased,
    /// Already up-to-date with target branch
    UpToDate(String),
}

/// Handle shared rebase workflow (used by `wt step rebase` and `wt merge`)
pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {
    let repo = Repository::current()?;

    // Get and validate target ref (any commit-ish for rebase)
    let integration_target = repo.require_target_ref(target)?;

    // Check if already up-to-date (linear extension of target, no merge commits)
    if repo.is_rebased_onto(&integration_target)? {
        return Ok(RebaseResult::UpToDate(integration_target));
    }

    // Check if this is a fast-forward or true rebase
    let merge_base = repo
        .merge_base("HEAD", &integration_target)?
        .context("Cannot rebase: no common ancestor with target branch")?;
    let head_sha = repo.run_command(&["rev-parse", "HEAD"])?.trim().to_string();
    let is_fast_forward = merge_base == head_sha;

    // Only show progress for true rebases (fast-forwards are instant)
    if !is_fast_forward {
        eprintln!(
            "{}",
            progress_message(cformat!("Rebasing onto <bold>{integration_target}</>..."))
        );
    }

    let rebase_result = repo.run_command(&["rebase", &integration_target]);

    // If rebase failed, check if it's due to conflicts
    if let Err(e) = rebase_result {
        // Check if it's a rebase conflict
        let is_rebasing = repo
            .worktree_state()?
            .is_some_and(|s| s.starts_with("REBASING"));
        if is_rebasing {
            // Extract git's stderr output from the error
            let git_output = e.to_string();
            return Err(worktrunk::git::GitError::RebaseConflict {
                target_branch: integration_target,
                git_output,
            }
            .into());
        }
        // Not a rebase conflict, return original error
        return Err(worktrunk::git::GitError::Other {
            message: cformat!(
                "Failed to rebase onto <bold>{}</>: {}",
                integration_target,
                e
            ),
        }
        .into());
    }

    // Verify rebase completed successfully (safety check for edge cases)
    if repo.worktree_state()?.is_some() {
        return Err(worktrunk::git::GitError::RebaseConflict {
            target_branch: integration_target,
            git_output: String::new(),
        }
        .into());
    }

    // Success
    let msg = if is_fast_forward {
        cformat!("Fast-forwarded to <bold>{integration_target}</>")
    } else {
        cformat!("Rebased onto <bold>{integration_target}</>")
    };
    eprintln!("{}", success_message(msg));

    Ok(RebaseResult::Rebased)
}

/// Handle `wt step diff` command
///
/// Shows all changes since branching from the target: committed, staged, unstaged,
/// and untracked files in a single diff. Copies the real index to preserve git's stat
/// cache (avoiding re-reads of unchanged files), then registers untracked files with
/// `git add -N` so they appear in the diff.
///
/// TODO: consider adding `--stage` flag (all/tracked/none) like `step commit` to
/// control which change types are included. `tracked` would skip the temp index,
/// `none` would diff only committed changes.
pub fn step_diff(target: Option<&str>, extra_args: &[String]) -> anyhow::Result<()> {
    let repo = Repository::current()?;
    let wt = repo.current_worktree();

    // Get and validate target ref
    let integration_target = repo.require_target_ref(target)?;

    // Get merge base
    let merge_base = repo
        .merge_base("HEAD", &integration_target)?
        .context("No common ancestor with target branch")?;

    let current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());

    // Copy the real index so git's stat cache is warm for tracked files, then
    // register untracked files with `git add -N .` so they appear in the diff.
    // This avoids re-reading and hashing every tracked file during `git diff`.
    let worktree_root = wt.root()?;

    let real_index = wt.git_dir()?.join("index");
    let temp_index = tempfile::NamedTempFile::new().context("Failed to create temporary index")?;
    let temp_index_path = temp_index
        .path()
        .to_str()
        .context("Temporary index path is not valid UTF-8")?;

    std::fs::copy(&real_index, temp_index.path()).context("Failed to copy index file")?;

    // Register untracked files as intent-to-add (tracked files already have entries)
    Cmd::new("git")
        .args(["add", "--intent-to-add", "."])
        .current_dir(&worktree_root)
        .context(&current_branch)
        .env("GIT_INDEX_FILE", temp_index_path)
        .run()
        .context("Failed to register untracked files")?;

    // Stream diff to stdout — git handles pager and coloring
    let mut diff_args = vec!["diff".to_string(), merge_base];
    diff_args.extend_from_slice(extra_args);
    Cmd::new("git")
        .args(&diff_args)
        .current_dir(&worktree_root)
        .context(&current_branch)
        .env("GIT_INDEX_FILE", temp_index_path)
        .stream()?;

    Ok(())
}

/// Built-in excludes for `wt step copy-ignored`: VCS metadata + tool-state directories.
///
/// VCS directories contain internal state tied to a specific working directory.
/// Git's own `.git` is implicitly excluded (git ls-files never reports it), but
/// other VCS tools colocated with git need explicit exclusion. Tool-state
/// directories (`.conductor/`, `.worktrees/`, etc.) are project-local state that
/// shouldn't be shared between worktrees.
const BUILTIN_COPY_IGNORED_EXCLUDES: &[&str] = &[
    ".bzr/",
    ".conductor/",
    ".entire/",
    ".hg/",
    ".jj/",
    ".pi/",
    ".pijul/",
    ".sl/",
    ".svn/",
    ".worktrees/",
];

fn default_copy_ignored_excludes() -> Vec<String> {
    BUILTIN_COPY_IGNORED_EXCLUDES
        .iter()
        .map(|s| (*s).to_string())
        .collect()
}

/// Resolve the full copy-ignored config by merging built-in defaults, project
/// config (`.config/wt.toml`), and user config (global + per-project overrides).
fn resolve_copy_ignored_config(repo: &Repository) -> anyhow::Result<CopyIgnoredConfig> {
    let mut config = CopyIgnoredConfig {
        exclude: default_copy_ignored_excludes(),
    };
    if let Some(project_config) = repo.load_project_config()?
        && let Some(project_copy_ignored) = project_config.copy_ignored()
    {
        config = config.merged_with(project_copy_ignored);
    }
    let user_config = UserConfig::load().context("Failed to load config")?;
    let project_id = repo.project_identifier().ok();
    config = config.merged_with(&user_config.copy_ignored(project_id.as_deref()));
    Ok(config)
}

/// List gitignored entries in a worktree, filtered by `.worktreeinclude` and excluding
/// configured patterns, VCS metadata directories, and entries that contain nested worktrees.
///
/// Combines five steps:
/// 1. `list_ignored_entries()` — git ls-files for ignored entries
/// 2. `.worktreeinclude` filtering — only matching entries if the file exists
/// 3. `[step.copy-ignored].exclude` filtering — skip entries matching configured patterns
/// 4. Built-in exclude filtering — always skip VCS metadata and tool-state directories
/// 5. Nested worktree filtering — exclude entries containing other worktrees
fn list_and_filter_ignored_entries(
    worktree_path: &Path,
    context: &str,
    worktree_paths: &[PathBuf],
    exclude_patterns: &[String],
) -> anyhow::Result<Vec<(PathBuf, bool)>> {
    let ignored_entries = list_ignored_entries(worktree_path, context)?;

    // Filter to entries that match .worktreeinclude (or all if no file exists)
    let include_path = worktree_path.join(".worktreeinclude");
    let filtered: Vec<_> = if include_path.exists() {
        let include_matcher = {
            let mut builder = GitignoreBuilder::new(worktree_path);
            if let Some(err) = builder.add(&include_path) {
                return Err(worktrunk::git::GitError::WorktreeIncludeParseError {
                    error: err.to_string(),
                }
                .into());
            }
            builder.build().context("Failed to build include matcher")?
        };
        ignored_entries
            .into_iter()
            .filter(|(path, is_dir)| include_matcher.matched(path, *is_dir).is_ignore())
            .collect()
    } else {
        ignored_entries
    };

    // Build exclude matcher for configured patterns (if any)
    let exclude_matcher = if exclude_patterns.is_empty() {
        None
    } else {
        let mut builder = GitignoreBuilder::new(worktree_path);
        for pattern in exclude_patterns {
            builder.add_line(None, pattern).map_err(|error| {
                anyhow::anyhow!(
                    "Invalid [step.copy-ignored].exclude pattern {:?}: {}",
                    pattern,
                    error
                )
            })?;
        }
        Some(
            builder
                .build()
                .context("Failed to build copy-ignored exclude matcher")?,
        )
    };

    // Filter out excluded patterns, VCS metadata directories, and nested worktrees
    Ok(filtered
        .into_iter()
        .filter(|(path, is_dir)| {
            // Skip entries matching configured exclude patterns
            if let Some(ref matcher) = exclude_matcher {
                let relative = path.strip_prefix(worktree_path).unwrap_or(path.as_path());
                if matcher.matched(relative, *is_dir).is_ignore() {
                    return false;
                }
            }
            // Skip built-in excluded directories (.jj, .hg, .worktrees, etc.)
            if *is_dir
                && path
                    .file_name()
                    .and_then(|n| n.to_str())
                    .is_some_and(|name| {
                        BUILTIN_COPY_IGNORED_EXCLUDES
                            .iter()
                            .any(|pat| pat.trim_end_matches('/') == name)
                    })
            {
                return false;
            }
            // Skip entries that contain other worktrees
            !worktree_paths
                .iter()
                .any(|wt_path| wt_path != worktree_path && wt_path.starts_with(path))
        })
        .collect())
}

/// Handle `wt step copy-ignored` command
///
/// Copies gitignored files from a source worktree to a destination worktree.
/// If a `.worktreeinclude` file exists, only files matching both `.worktreeinclude`
/// and gitignore patterns are copied. Without `.worktreeinclude`, all gitignored
/// files are copied. Uses COW (reflink) when available for efficient copying of
/// large directories like `target/`.
pub fn step_copy_ignored(
    from: Option<&str>,
    to: Option<&str>,
    dry_run: bool,
    force: bool,
) -> anyhow::Result<()> {
    worktrunk::copy::lower_process_priority();
    let repo = Repository::current()?;
    let copy_ignored_config = resolve_copy_ignored_config(&repo)?;

    // Resolve source and destination worktree paths
    let (source_path, source_context) = match from {
        Some(branch) => {
            let path = repo.worktree_for_branch(branch)?.ok_or_else(|| {
                worktrunk::git::GitError::WorktreeNotFound {
                    branch: branch.to_string(),
                }
            })?;
            (path, branch.to_string())
        }
        None => {
            // Default source is the primary worktree (main worktree for normal repos,
            // default branch worktree for bare repos).
            let path = repo.primary_worktree()?.ok_or_else(|| {
                anyhow::anyhow!(
                    "No primary worktree found (bare repo with no default branch worktree)"
                )
            })?;
            let context = path
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_default();
            (path, context)
        }
    };

    let dest_path = match to {
        Some(branch) => repo.worktree_for_branch(branch)?.ok_or_else(|| {
            worktrunk::git::GitError::WorktreeNotFound {
                branch: branch.to_string(),
            }
        })?,
        None => repo.current_worktree().root()?,
    };

    if source_path == dest_path {
        eprintln!(
            "{}",
            info_message("Source and destination are the same worktree")
        );
        return Ok(());
    }

    let worktree_paths: Vec<PathBuf> = repo
        .list_worktrees()?
        .into_iter()
        .map(|wt| wt.path)
        .collect();
    let entries_to_copy = list_and_filter_ignored_entries(
        &source_path,
        &source_context,
        &worktree_paths,
        &copy_ignored_config.exclude,
    )?;

    if entries_to_copy.is_empty() {
        eprintln!("{}", info_message("No matching files to copy"));
        return Ok(());
    }

    let verbose = verbosity();

    // Show entries in verbose or dry-run mode
    if verbose >= 1 || dry_run {
        let items: Vec<String> = entries_to_copy
            .iter()
            .map(|(src_entry, is_dir)| {
                let relative = src_entry
                    .strip_prefix(&source_path)
                    .unwrap_or(src_entry.as_path());
                let entry_type = if *is_dir { "dir" } else { "file" };
                format!("{} ({})", format_path_for_display(relative), entry_type)
            })
            .collect();
        let entry_word = if items.len() == 1 { "entry" } else { "entries" };
        let verb = if dry_run { "Would copy" } else { "Copying" };
        eprintln!(
            "{}",
            info_message(format!(
                "{verb} {} {}:\n{}",
                items.len(),
                entry_word,
                format_with_gutter(&items.join("\n"), None)
            ))
        );
        if dry_run {
            return Ok(());
        }
    }

    let mut copied_count = 0usize;
    for (src_entry, is_dir) in &entries_to_copy {
        let relative = src_entry
            .strip_prefix(&source_path)
            .expect("git ls-files path under worktree");
        let dest_entry = dest_path.join(relative);

        if *is_dir {
            copied_count +=
                copy_dir_recursive(src_entry, &dest_entry, force).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)
                    )
                })?;
            }
            if copy_leaf(src_entry, &dest_entry, force)? {
                copied_count += 1;
            }
        }
    }

    // Show summary
    let file_word = if copied_count == 1 { "file" } else { "files" };
    eprintln!(
        "{}",
        success_message(format!("Copied {copied_count} {file_word}"))
    );

    Ok(())
}

/// List ignored entries using git ls-files
///
/// Uses `git ls-files --ignored --exclude-standard -o --directory` which:
/// - Handles all gitignore sources (global, .gitignore, .git/info/exclude, nested)
/// - Stops at directory boundaries (--directory) to avoid listing thousands of files
fn list_ignored_entries(
    worktree_path: &Path,
    context: &str,
) -> anyhow::Result<Vec<(std::path::PathBuf, bool)>> {
    let output = Cmd::new("git")
        .args([
            "ls-files",
            "--ignored",
            "--exclude-standard",
            "-o",
            "--directory",
        ])
        .current_dir(worktree_path)
        .context(context)
        .run()
        .context("Failed to run git ls-files")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git ls-files failed: {}", stderr.trim());
    }

    // Parse output: directories end with /
    let entries = String::from_utf8_lossy(&output.stdout)
        .lines()
        .map(|line| {
            let is_dir = line.ends_with('/');
            let path = worktree_path.join(line.trim_end_matches('/'));
            (path, is_dir)
        })
        .collect();

    Ok(entries)
}

/// Move a file or directory, falling back to copy+delete on cross-device errors.
fn move_entry(src: &Path, dest: &Path, is_dir: bool) -> anyhow::Result<()> {
    // Ensure parent directory exists
    if let Some(parent) = dest.parent() {
        fs::create_dir_all(parent)
            .context(format!("creating parent directory for {}", dest.display()))?;
    }

    match fs::rename(src, dest) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == ErrorKind::CrossesDevices => copy_and_remove(src, dest, is_dir),
        Err(e) => Err(anyhow::Error::from(e).context(format!(
            "moving {} to {}",
            src.display(),
            dest.display()
        ))),
    }
}

/// Copy then delete — fallback when `rename` fails with EXDEV (cross-device).
fn copy_and_remove(src: &Path, dest: &Path, is_dir: bool) -> anyhow::Result<()> {
    if is_dir {
        copy_dir_recursive(src, dest, true)?;
        fs::remove_dir_all(src).context(format!("removing source directory {}", src.display()))?;
    } else {
        copy_leaf(src, dest, true)?;

        fs::remove_file(src).context(format!("removing source file {}", src.display()))?;
    }
    Ok(())
}

const PROMOTE_STAGING_DIR: &str = "staging/promote";

/// Move gitignored files from both worktrees into a staging directory.
///
/// Called BEFORE the branch exchange because `git switch` silently overwrites
/// ignored files that collide with tracked files on the target branch.
///
/// Returns the staging directory path and the count of entries staged.
fn stage_ignored(
    repo: &Repository,
    path_a: &Path,
    entries_a: &[(PathBuf, bool)],
    path_b: &Path,
    entries_b: &[(PathBuf, bool)],
) -> anyhow::Result<(PathBuf, usize)> {
    let staging_dir = repo.wt_dir().join(PROMOTE_STAGING_DIR);
    fs::create_dir_all(&staging_dir).context("creating promote staging directory")?;

    let staging_a = staging_dir.join("a");
    let staging_b = staging_dir.join("b");
    let mut count = 0;

    // Move A's entries → staging/a
    for (src_entry, is_dir) in entries_a {
        let relative = src_entry
            .strip_prefix(path_a)
            .context("entry not under worktree A")?;
        let staging_entry = staging_a.join(relative);
        if fs::symlink_metadata(src_entry).is_ok() {
            move_entry(src_entry, &staging_entry, *is_dir)
                .context(format!("staging {}", relative.display()))?;
            count += 1;
        }
    }

    // Move B's entries → staging/b
    for (src_entry, is_dir) in entries_b {
        let relative = src_entry
            .strip_prefix(path_b)
            .context("entry not under worktree B")?;
        let staging_entry = staging_b.join(relative);
        if fs::symlink_metadata(src_entry).is_ok() {
            move_entry(src_entry, &staging_entry, *is_dir)
                .context(format!("staging {}", relative.display()))?;
            count += 1;
        }
    }

    // Clean up empty staging directory (can happen if all entries vanished
    // between listing and staging due to TOCTOU)
    if count == 0 && staging_dir.exists() {
        let _ = fs::remove_dir_all(&staging_dir);
    }

    Ok((staging_dir, count))
}

/// Distribute staged files to their new worktrees after a branch exchange.
///
/// B's original files (in staging/b) go to worktree A (which now has B's branch).
/// A's original files (in staging/a) go to worktree B (which now has A's branch).
fn distribute_staged(
    staging_dir: &Path,
    path_a: &Path,
    entries_a: &[(PathBuf, bool)],
    path_b: &Path,
    entries_b: &[(PathBuf, bool)],
) -> anyhow::Result<usize> {
    let staging_a = staging_dir.join("a");
    let staging_b = staging_dir.join("b");
    let mut count = 0;

    // Move B's staged entries → A (A now has B's branch)
    for (src_entry, is_dir) in entries_b {
        let relative = src_entry
            .strip_prefix(path_b)
            .context("entry not under worktree B")?;
        let staging_entry = staging_b.join(relative);
        let dest_entry = path_a.join(relative);
        if fs::symlink_metadata(&staging_entry).is_ok() {
            move_entry(&staging_entry, &dest_entry, *is_dir)
                .context(format!("distributing {}", relative.display()))?;
            count += 1;
        }
    }

    // Move A's staged entries → B (B now has A's branch)
    for (src_entry, is_dir) in entries_a {
        let relative = src_entry
            .strip_prefix(path_a)
            .context("entry not under worktree A")?;
        let staging_entry = staging_a.join(relative);
        let dest_entry = path_b.join(relative);
        if fs::symlink_metadata(&staging_entry).is_ok() {
            move_entry(&staging_entry, &dest_entry, *is_dir)
                .context(format!("distributing {}", relative.display()))?;
            count += 1;
        }
    }

    // Clean up staging directory (best-effort — files are already distributed)
    let _ = fs::remove_dir_all(staging_dir);

    Ok(count)
}

/// Result of a promote operation
pub enum PromoteResult {
    /// Branch was promoted successfully
    Promoted,
    /// Already in canonical state (requested branch is already in main)
    AlreadyInMain(String),
}

/// Exchange branches between two worktrees.
///
/// Steps: detach target → detach main → switch main → switch target.
/// Both worktrees must be clean (verified by caller). On failure, attempts
/// best-effort rollback — but failure here is near-impossible given the
/// preconditions (`ensure_clean` passed, branches exist, detach released locks).
fn exchange_branches(
    main_wt: &worktrunk::git::WorkingTree<'_>,
    main_branch: &str,
    target_wt: &worktrunk::git::WorkingTree<'_>,
    target_branch: &str,
) -> anyhow::Result<()> {
    let steps: &[(&worktrunk::git::WorkingTree<'_>, &[&str], &str)] = &[
        (target_wt, &["switch", "--detach"], "detach target"),
        (main_wt, &["switch", "--detach"], "detach main"),
        (main_wt, &["switch", target_branch], "switch main"),
        (target_wt, &["switch", main_branch], "switch target"),
    ];

    for (wt, args, label) in steps {
        if let Err(e) = wt.run_command(args) {
            // Best-effort rollback: try to re-attach both branches.
            let _ = main_wt.run_command(&["switch", main_branch]);
            let _ = target_wt.run_command(&["switch", target_branch]);
            return Err(e.context(format!("branch exchange failed at: {label}")));
        }
    }

    Ok(())
}

/// Handle `wt step promote` command
///
/// Promotes a branch to the main worktree, exchanging it with whatever branch is currently there.
///
/// ## Interruption recovery
///
/// The swap uses a staging directory at `.git/wt/staging/promote/` and proceeds
/// in three phases:
///
/// 1. **Stage**: move ignored files from both worktrees into staging (`a/`, `b/`)
/// 2. **Exchange**: detach + `git switch` to swap branches
/// 3. **Distribute**: move staged files to their new worktrees, then delete staging
///
/// A hard kill at any phase leaves files in staging, never deleted. The next run
/// detects the leftover directory and bails with a recovery path. A kill during
/// `git switch` may leave a worktree detached (fix: `git switch <branch>`).
pub fn handle_promote(branch: Option<&str>) -> anyhow::Result<PromoteResult> {
    use worktrunk::git::GitError;

    let repo = Repository::current()?;
    let worktrees = repo.list_worktrees()?;

    if worktrees.is_empty() {
        anyhow::bail!("No worktrees found");
    }

    // For normal repos, worktrees[0] is the main worktree
    // For bare repos, there's no main worktree - we don't support promote there
    if repo.is_bare()? {
        anyhow::bail!("wt step promote is not supported in bare repositories");
    }

    let main_wt = &worktrees[0];
    let main_path = &main_wt.path;
    let main_branch = main_wt
        .branch
        .clone()
        .ok_or_else(|| GitError::DetachedHead {
            action: Some("promote".into()),
        })?;

    // Resolve the branch to promote (default_branch computed lazily, only when needed)
    let target_branch = match branch {
        Some(b) => b.to_string(),
        None => {
            let current_wt = repo.current_worktree();
            if !current_wt.is_linked()? {
                // From main worktree with no args: restore default branch
                repo.default_branch()
                    .ok_or_else(|| anyhow::anyhow!("Could not determine default branch"))?
            } else {
                // From other worktree with no args: promote current branch
                current_wt.branch()?.ok_or_else(|| GitError::DetachedHead {
                    action: Some("promote".into()),
                })?
            }
        }
    };

    // Check if target is already in main worktree
    if target_branch == main_branch {
        return Ok(PromoteResult::AlreadyInMain(target_branch));
    }

    // Find the worktree with the target branch
    let target_wt = worktrees
        .iter()
        .skip(1) // Skip main worktree
        .find(|wt| wt.branch.as_deref() == Some(&target_branch))
        .ok_or_else(|| GitError::WorktreeNotFound {
            branch: target_branch.clone(),
        })?;

    let target_path = &target_wt.path;

    // Bail early if a leftover staging dir exists from a previous interrupted promote —
    // it may contain the user's only copy of files from the failed swap.
    // Check BEFORE ensure_clean so users see the recovery path first.
    let staging_path = repo.wt_dir().join(PROMOTE_STAGING_DIR);
    if staging_path.exists() {
        return Err(anyhow::anyhow!(
            "Files may need manual recovery from: {}\n\
             Remove it to retry: rm -rf \"{}\"",
            staging_path.display(),
            staging_path.display()
        )
        .context("Found leftover staging directory from an interrupted promote"));
    }

    // Ensure both worktrees are clean
    let main_working_tree = repo.worktree_at(main_path);
    let target_working_tree = repo.worktree_at(target_path);

    main_working_tree.ensure_clean("promote", Some(&main_branch), false)?;
    target_working_tree.ensure_clean("promote", Some(&target_branch), false)?;

    // Check if we're restoring canonical state (promoting default branch back to main worktree)
    // Only lookup default_branch if needed for messaging (already resolved if no-arg from main)
    let default_branch = repo.default_branch();
    let is_restoring = default_branch.as_ref() == Some(&target_branch);

    if is_restoring {
        // Restoring default branch to main worktree - no warning needed
        eprintln!("{}", info_message("Restoring main worktree"));
    } else {
        // Creating mismatch - show warning and how to restore
        eprintln!(
            "{}",
            warning_message("Promoting creates mismatched worktree state (shown as âš‘ in wt list)",)
        );
        // Only show restore hint if we know the default branch
        if let Some(default) = &default_branch {
            eprintln!(
                "{}",
                hint_message(cformat!(
                    "Run <underline>wt step promote {default}</> to restore canonical locations"
                ))
            );
        }
    }

    // Discover gitignored entries BEFORE branch exchange — .gitignore rules belong
    // to the current branch and will change after `git switch`.
    let worktree_paths: Vec<PathBuf> = worktrees.iter().map(|wt| wt.path.clone()).collect();
    let no_excludes: &[String] = &[];
    let main_entries =
        list_and_filter_ignored_entries(main_path, &main_branch, &worktree_paths, no_excludes)?;
    let target_entries =
        list_and_filter_ignored_entries(target_path, &target_branch, &worktree_paths, no_excludes)?;

    // Move gitignored files to staging BEFORE branch exchange.
    // `git switch` silently overwrites ignored files that collide with tracked
    // files on the target branch — staging them first prevents data loss.
    let staged = if !main_entries.is_empty() || !target_entries.is_empty() {
        let (dir, count) = stage_ignored(
            &repo,
            main_path,
            &main_entries,
            target_path,
            &target_entries,
        )
        .context(format!(
            "Failed to stage ignored files. Already-staged files may be recoverable from: {}",
            staging_path.display()
        ))?;
        if count > 0 { Some((dir, count)) } else { None }
    } else {
        None
    };

    // Exchange branches (detach both, then switch to swapped branches).
    // Failure is near-impossible (both worktrees verified clean, branches exist).
    // If it somehow fails, stale staging detection recovers on next run.
    exchange_branches(
        &main_working_tree,
        &main_branch,
        &target_working_tree,
        &target_branch,
    )?;

    // Distribute staged files to their new worktrees (after branch exchange)
    let swapped = if let Some((ref staging_dir, _)) = staged {
        distribute_staged(
            staging_dir,
            main_path,
            &main_entries,
            target_path,
            &target_entries,
        )
        .context(format!(
            "Failed to distribute staged files. Staged files may be recoverable from: {}",
            staging_dir.display()
        ))?
    } else {
        0
    };

    // Print success messages only after everything succeeded
    eprintln!(
        "{}",
        success_message(cformat!(
            "Promoted: main worktree now has <bold>{target_branch}</>; {} now has <bold>{main_branch}</>",
            worktrunk::path::format_path_for_display(target_path)
        ))
    );
    if swapped > 0 {
        let path_word = if swapped == 1 { "path" } else { "paths" };
        eprintln!(
            "{}",
            success_message(format!("Swapped {swapped} gitignored {path_word}"))
        );
    }

    Ok(PromoteResult::Promoted)
}

/// Remove worktrees and branches integrated into the default branch.
///
/// Handles four cases: live worktrees with branches (removed + branch deleted),
/// detached HEAD worktrees (directory removed, no branch to delete), stale worktree
/// entries (pruned + branch deleted), and orphan branches without worktrees (deleted).
/// Skips the main/primary worktree, locked worktrees, and worktrees younger than
/// `min_age`. Removes the current worktree last to trigger cd to primary.
pub fn step_prune(
    dry_run: bool,
    yes: bool,
    min_age: &str,
    foreground: bool,
    format: crate::cli::SwitchFormat,
) -> anyhow::Result<()> {
    let min_age_duration =
        humantime::parse_duration(min_age).context("Invalid --min-age duration")?;

    let repo = Repository::current()?;
    let config = UserConfig::load()?;

    let integration_target = match repo.integration_target() {
        Some(target) => target,
        None => {
            anyhow::bail!("cannot determine default branch");
        }
    };

    let worktrees = repo.list_worktrees()?;
    let current_root = repo.current_worktree().root()?.to_path_buf();
    let current_root = dunce::canonicalize(&current_root).unwrap_or(current_root);
    let now_secs = worktrunk::utils::epoch_now();

    let default_branch = repo.default_branch();

    // Gather candidates: integrated worktrees + integrated branch-only refs
    struct Candidate {
        /// Original index in check_items (for deterministic output ordering)
        check_idx: usize,
        /// Branch name (None for detached HEAD worktrees)
        branch: Option<String>,
        /// Display label: branch name or abbreviated commit SHA
        label: String,
        /// Worktree path (for Path-based removal of detached worktrees)
        path: Option<PathBuf>,
        /// Current worktree, other worktree, or branch-only (no worktree)
        kind: CandidateKind,
    }
    enum CandidateKind {
        Current,
        Other,
        BranchOnly,
    }

    impl CandidateKind {
        fn as_str(&self) -> &'static str {
            match self {
                CandidateKind::Current => "current",
                CandidateKind::Other => "worktree",
                CandidateKind::BranchOnly => "branch_only",
            }
        }
    }

    /// Build a human-readable count like "3 worktrees & branches".
    ///
    /// Worktree + branch is the default pair (matching progress messages'
    /// "worktree & branch" pattern). Unpaired items listed separately.
    fn prune_summary(candidates: &[Candidate]) -> String {
        let mut worktree_with_branch = 0usize;
        let mut detached_worktree = 0usize;
        let mut branch_only = 0usize;
        for c in candidates {
            match (&c.kind, &c.branch) {
                (CandidateKind::BranchOnly, _) => branch_only += 1,
                (CandidateKind::Current | CandidateKind::Other, Some(_)) => {
                    worktree_with_branch += 1;
                }
                (CandidateKind::Current | CandidateKind::Other, None) => {
                    detached_worktree += 1;
                }
            }
        }
        let mut parts = Vec::new();
        if worktree_with_branch > 0 {
            let noun = if worktree_with_branch == 1 {
                "worktree & branch"
            } else {
                "worktrees & branches"
            };
            parts.push(format!("{worktree_with_branch} {noun}"));
        }
        if detached_worktree > 0 {
            let noun = if detached_worktree == 1 {
                "worktree"
            } else {
                "worktrees"
            };
            parts.push(format!("{detached_worktree} {noun}"));
        }
        if branch_only > 0 {
            let noun = if branch_only == 1 {
                "branch"
            } else {
                "branches"
            };
            parts.push(format!("{branch_only} {noun}"));
        }
        parts.join(", ")
    }

    // For non-dry-run, approve hooks upfront so we can remove inline.
    let run_hooks = if dry_run {
        false // unused in dry-run path
    } else {
        let env = CommandEnv::for_action_branchless()?;
        let ctx = env.context(yes);
        let approved = approve_hooks(
            &ctx,
            &[
                HookType::PreRemove,
                HookType::PostRemove,
                HookType::PostSwitch,
            ],
        )?;
        if !approved {
            eprintln!("{}", info_message("Commands declined, continuing removal"));
        }
        approved
    };

    let mut removed: Vec<Candidate> = Vec::new();
    let mut deferred_current: Option<Candidate> = None;
    let mut skipped_young: Vec<String> = Vec::new();
    // Track branches seen via worktree entries so we don't double-count
    // in the orphan branch scan below.
    let mut seen_branches: std::collections::HashSet<String> = std::collections::HashSet::new();

    /// Try to remove a candidate immediately. Returns Ok(true) if removed,
    /// Ok(false) if skipped (preparation error), Err on execution error.
    fn try_remove(
        candidate: &Candidate,
        repo: &Repository,
        config: &UserConfig,
        foreground: bool,
        run_hooks: bool,
        worktrees: &[WorktreeInfo],
    ) -> anyhow::Result<bool> {
        let target = match candidate.kind {
            CandidateKind::Current => RemoveTarget::Current,
            CandidateKind::BranchOnly => RemoveTarget::Branch(
                candidate
                    .branch
                    .as_ref()
                    .context("BranchOnly candidate missing branch")?,
            ),
            CandidateKind::Other => match &candidate.branch {
                Some(branch) => RemoveTarget::Branch(branch),
                None => RemoveTarget::Path(
                    candidate
                        .path
                        .as_ref()
                        .context("detached candidate missing path")?,
                ),
            },
        };
        let plan = match repo.prepare_worktree_removal(
            target,
            BranchDeletionMode::SafeDelete,
            false,
            config,
            None,
            Some(worktrees),
        ) {
            Ok(plan) => plan,
            Err(_) => {
                // prepare_worktree_removal is the gate: if the worktree can't
                // be removed (dirty, locked, etc.), it's simply not selected.
                return Ok(false);
            }
        };
        handle_remove_output(&plan, foreground, run_hooks, true, true)?;
        Ok(true)
    }

    enum CheckSource {
        /// Worktree with directory gone (prunable)
        Prunable { branch: String },
        /// Linked worktree
        Linked { wt_idx: usize },
        /// Local branch without a worktree entry
        Orphan,
    }

    struct CheckItem {
        integration_ref: String,
        source: CheckSource,
    }

    let mut check_items: Vec<CheckItem> = Vec::new();

    for (idx, wt) in worktrees.iter().enumerate() {
        if let Some(branch) = &wt.branch {
            seen_branches.insert(branch.clone());
        }

        if wt.locked.is_some() {
            continue;
        }

        if let Some(branch) = &wt.branch
            && default_branch.as_deref() == Some(branch.as_str())
        {
            continue;
        }

        if wt.is_prunable() {
            if let Some(branch) = &wt.branch {
                check_items.push(CheckItem {
                    integration_ref: branch.clone(),
                    source: CheckSource::Prunable {
                        branch: branch.clone(),
                    },
                });
            }
            continue;
        }

        // Skip main worktree (non-linked); in bare repos all are linked,
        // so the default-branch check above is the primary guard.
        let wt_tree = repo.worktree_at(&wt.path);
        if !wt_tree.is_linked()? {
            continue;
        }

        let integration_ref = match &wt.branch {
            Some(b) if !wt.detached => b.clone(),
            _ => wt.head.clone(),
        };

        check_items.push(CheckItem {
            integration_ref,
            source: CheckSource::Linked { wt_idx: idx },
        });
    }

    for branch in repo.all_branches()? {
        if seen_branches.contains(&branch) {
            continue;
        }
        if default_branch.as_deref() == Some(branch.as_str()) {
            continue;
        }
        check_items.push(CheckItem {
            integration_ref: branch,
            source: CheckSource::Orphan,
        });
    }

    // Parallel integration checks with inline removals.
    //
    // Spawn integration checks on a background thread via rayon par_iter,
    // sending each result through a channel as it completes. The main thread
    // processes results as they arrive: age-filtering, printing "Skipped"
    // messages, and removing candidates immediately. This overlaps integration
    // checking with removal — output appears as soon as the first check
    // completes instead of waiting for all checks to finish.
    let (tx, rx) = chan::unbounded();
    let integration_refs: Vec<String> = check_items
        .iter()
        .map(|item| item.integration_ref.clone())
        .collect();

    // Intentionally detached: if the main thread returns early (error in
    // the recv loop), remaining rayon tasks silently fail to send on the
    // closed channel and the thread cleans up on its own. Empty
    // integration_refs produces an empty par_iter that completes immediately.
    let repo_clone = repo.clone();
    let target = integration_target.clone();
    std::thread::spawn(move || {
        integration_refs
            .into_par_iter()
            .enumerate()
            .for_each(|(idx, ref_name)| {
                let result = repo_clone.integration_reason(&ref_name, &target);
                let _ = tx.send((idx, result));
            });
    });

    // Collect integration context alongside candidates for dry-run display.
    struct DryRunInfo {
        reason_desc: String,
        effective_target: String,
        suffix: &'static str,
    }
    let mut dry_run_info: Vec<(Candidate, DryRunInfo)> = Vec::new();

    // Process results as they arrive from the channel.
    for (idx, result) in rx {
        let (effective_target, reason) = result?;
        let Some(reason) = reason else {
            continue;
        };

        let item = &check_items[idx];

        // Linked worktrees need special handling: age check via filesystem
        // metadata, current-worktree deferral, and path-based candidates.
        if let CheckSource::Linked { wt_idx } = &item.source {
            let wt = &worktrees[*wt_idx];
            let label = wt
                .branch
                .clone()
                .unwrap_or_else(|| format!("(detached {})", &wt.head[..7.min(wt.head.len())]));

            // Skip recently-created worktrees that look "merged" because
            // they were just created from the default branch
            if min_age_duration > Duration::ZERO {
                let wt_tree = repo.worktree_at(&wt.path);
                let git_dir = wt_tree.git_dir()?;
                let metadata = fs::metadata(&git_dir).context("Failed to read worktree git dir")?;
                let created = metadata.created().or_else(|_| {
                    fs::metadata(git_dir.join("commondir")).and_then(|m| m.modified())
                });
                if let Ok(created) = created
                    && let Ok(created_epoch) = created.duration_since(std::time::UNIX_EPOCH)
                {
                    let age = Duration::from_secs(now_secs.saturating_sub(created_epoch.as_secs()));
                    if age < min_age_duration {
                        if !dry_run {
                            eprintln!(
                                "{}",
                                info_message(format!("Skipped {label} (younger than {min_age})"))
                            );
                        }
                        skipped_young.push(label);
                        continue;
                    }
                }
            }

            let wt_path = dunce::canonicalize(&wt.path).unwrap_or(wt.path.clone());
            let is_current = wt_path == current_root;
            let candidate = Candidate {
                check_idx: idx,
                branch: if wt.detached { None } else { wt.branch.clone() },
                label,
                path: Some(wt.path.clone()),
                kind: if is_current {
                    CandidateKind::Current
                } else {
                    CandidateKind::Other
                },
            };
            if dry_run {
                let info = DryRunInfo {
                    reason_desc: reason.description().to_string(),
                    effective_target,
                    suffix: "",
                };
                dry_run_info.push((candidate, info));
            } else if is_current {
                deferred_current = Some(candidate);
            } else if try_remove(
                &candidate, &repo, &config, foreground, run_hooks, &worktrees,
            )? {
                removed.push(candidate);
            }
            continue;
        }

        // Branch-only candidates: prunable (stale worktree) and orphan branches
        let (branch, suffix) = match &item.source {
            CheckSource::Prunable { branch } => (branch, " (stale)"),
            CheckSource::Orphan => (&item.integration_ref, " (branch only)"),
            CheckSource::Linked { .. } => unreachable!(),
        };

        // Age check for orphan branches via reflog creation timestamp
        if matches!(&item.source, CheckSource::Orphan) && min_age_duration > Duration::ZERO {
            let ref_name = format!("refs/heads/{branch}");
            if let Ok(stdout) = repo.run_command(&["reflog", "show", "--format=%ct", &ref_name])
                && let Some(created_epoch) = stdout
                    .trim()
                    .lines()
                    .last()
                    .and_then(|s| s.parse::<u64>().ok())
            {
                let age = Duration::from_secs(now_secs.saturating_sub(created_epoch));
                if age < min_age_duration {
                    if !dry_run {
                        eprintln!(
                            "{}",
                            info_message(format!("Skipped {branch} (younger than {min_age})"))
                        );
                    }
                    skipped_young.push(branch.clone());
                    continue;
                }
            }
        }

        let candidate = Candidate {
            check_idx: idx,
            label: branch.clone(),
            branch: Some(branch.clone()),
            path: None,
            kind: CandidateKind::BranchOnly,
        };
        if dry_run {
            let info = DryRunInfo {
                reason_desc: reason.description().to_string(),
                effective_target,
                suffix,
            };
            dry_run_info.push((candidate, info));
        } else if try_remove(
            &candidate, &repo, &config, foreground, run_hooks, &worktrees,
        )? {
            removed.push(candidate);
        }
    }

    if dry_run {
        // Sort by original check order for deterministic output regardless of
        // channel completion order.
        dry_run_info.sort_by_key(|(c, _)| c.check_idx);

        if format == crate::cli::SwitchFormat::Json {
            let items: Vec<serde_json::Value> = dry_run_info
                .iter()
                .map(|(c, info)| {
                    serde_json::json!({
                        "branch": c.branch,
                        "path": c.path,
                        "kind": c.kind.as_str(),
                        "reason": info.reason_desc,
                        "target": info.effective_target,
                    })
                })
                .collect();
            println!("{}", serde_json::to_string_pretty(&items)?);
            return Ok(());
        }

        let mut dry_candidates = Vec::new();
        for (candidate, info) in dry_run_info {
            eprintln!(
                "{}",
                info_message(cformat!(
                    "<bold>{}</>{} — {} {}",
                    candidate.label,
                    info.suffix,
                    info.reason_desc,
                    info.effective_target
                ))
            );
            dry_candidates.push(candidate);
        }

        // Report skipped worktrees (after candidates, before summary).
        // Sort for deterministic output regardless of channel completion order.
        skipped_young.sort();
        if !skipped_young.is_empty() {
            let names = skipped_young.join(", ");
            eprintln!(
                "{}",
                info_message(format!("Skipped {names} (younger than {min_age})"))
            );
        }

        if dry_candidates.is_empty() {
            if skipped_young.is_empty() {
                eprintln!("{}", info_message("No merged worktrees to remove"));
            }
            return Ok(());
        }
        eprintln!(
            "{}",
            hint_message(format!(
                "{} would be removed (dry run)",
                prune_summary(&dry_candidates)
            ))
        );
        return Ok(());
    }

    // Remove deferred current worktree last (cd-to-primary happens here)
    if let Some(current) = deferred_current
        && try_remove(&current, &repo, &config, foreground, run_hooks, &worktrees)?
    {
        removed.push(current);
    }

    if format == crate::cli::SwitchFormat::Json {
        let items: Vec<serde_json::Value> = removed
            .iter()
            .map(|c| {
                serde_json::json!({
                    "branch": c.branch,
                    "path": c.path,
                    "kind": c.kind.as_str(),
                })
            })
            .collect();
        println!("{}", serde_json::to_string_pretty(&items)?);
    } else if removed.is_empty() {
        if skipped_young.is_empty() {
            eprintln!("{}", info_message("No merged worktrees to remove"));
        }
    } else {
        eprintln!(
            "{}",
            success_message(format!("Pruned {}", prune_summary(&removed)))
        );
    }

    Ok(())
}

/// Move worktrees to their expected paths based on the `worktree-path` template.
///
/// See `src/commands/relocate.rs` for the implementation details and algorithm.
///
/// # Flags
///
/// | Flag | Purpose |
/// |------|---------|
/// | `--dry-run` | Show what would be moved without moving |
/// | `--commit` | Auto-commit dirty worktrees with LLM-generated messages before relocating |
/// | `--clobber` | Move non-worktree paths out of the way (`<path>.bak-<timestamp>`) |
/// | `[branches...]` | Specific branches to relocate (default: all mismatched) |
pub fn step_relocate(
    branches: Vec<String>,
    dry_run: bool,
    commit: bool,
    clobber: bool,
) -> anyhow::Result<()> {
    use super::relocate::{
        GatherResult, RelocationExecutor, ValidationResult, gather_candidates, show_all_skipped,
        show_dry_run_preview, show_no_relocations_needed, show_summary, validate_candidates,
    };

    let repo = Repository::current()?;
    let config = UserConfig::load()?;
    let default_branch = repo.default_branch().unwrap_or_default();

    // Validate default branch early - needed for main worktree relocation
    if default_branch.is_empty() {
        anyhow::bail!(
            "Cannot determine default branch; set with: wt config state default-branch set main"
        );
    }
    let repo_path = repo.repo_path()?.to_path_buf();

    // Phase 1: Gather candidates (worktrees not at expected paths)
    let GatherResult {
        candidates,
        template_errors,
    } = gather_candidates(&repo, &config, &branches)?;

    if candidates.is_empty() {
        show_no_relocations_needed(template_errors);
        return Ok(());
    }

    // Dry run: show preview and exit
    if dry_run {
        show_dry_run_preview(&candidates);
        return Ok(());
    }

    // Phase 2: Validate candidates (check locked/dirty, optionally auto-commit)
    let ValidationResult { validated, skipped } =
        validate_candidates(&repo, &config, candidates, commit, &repo_path)?;

    if validated.is_empty() {
        show_all_skipped(skipped);
        return Ok(());
    }

    // Phase 3 & 4: Create executor (classifies targets) and execute relocations
    let mut executor = RelocationExecutor::new(&repo, validated, clobber)?;
    let cwd = std::env::current_dir().ok();
    executor.execute(&repo_path, &default_branch, cwd.as_deref())?;

    // Show summary
    let total_skipped = skipped + executor.skipped;
    show_summary(executor.relocated, total_skipped);

    Ok(())
}

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

    #[test]
    fn test_move_entry_file() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("source.txt");
        let dest = tmp.path().join("subdir/dest.txt");

        fs::write(&src, "content").unwrap();
        move_entry(&src, &dest, false).unwrap();

        assert!(!src.exists());
        assert_eq!(fs::read_to_string(&dest).unwrap(), "content");
    }

    #[test]
    fn test_move_entry_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("srcdir");
        let dest = tmp.path().join("nested/destdir");

        fs::create_dir_all(src.join("inner")).unwrap();
        fs::write(src.join("inner/file.txt"), "nested").unwrap();
        fs::write(src.join("root.txt"), "root").unwrap();

        move_entry(&src, &dest, true).unwrap();

        assert!(!src.exists());
        assert_eq!(
            fs::read_to_string(dest.join("inner/file.txt")).unwrap(),
            "nested"
        );
        assert_eq!(fs::read_to_string(dest.join("root.txt")).unwrap(), "root");
    }

    #[test]
    fn test_copy_and_remove_file() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("source.txt");
        let dest = tmp.path().join("dest.txt");

        fs::write(&src, "content").unwrap();
        copy_and_remove(&src, &dest, false).unwrap();

        assert!(!src.exists());
        assert_eq!(fs::read_to_string(&dest).unwrap(), "content");
    }

    #[test]
    fn test_copy_and_remove_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("srcdir");
        let dest = tmp.path().join("destdir");

        fs::create_dir_all(src.join("sub")).unwrap();
        fs::write(src.join("sub/file.txt"), "nested").unwrap();
        fs::write(src.join("root.txt"), "root").unwrap();

        copy_and_remove(&src, &dest, true).unwrap();

        assert!(!src.exists());
        assert_eq!(
            fs::read_to_string(dest.join("sub/file.txt")).unwrap(),
            "nested"
        );
        assert_eq!(fs::read_to_string(dest.join("root.txt")).unwrap(), "root");
    }
}