worktrunk 0.40.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
//! Integration tests for `wt step <alias>`

use crate::common::{
    TestRepo, configure_directive_files, directive_files, make_snapshot_cmd,
    make_snapshot_cmd_with_global_flags, repo, setup_snapshot_settings, wt_bin,
};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use std::io::Write;
use std::process::Stdio;

/// Alias from project config runs with template expansion (-y bypasses approval)
#[rstest]
fn test_step_alias_from_project_config(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
hello = "echo Hello from {{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "step",
        &["hello"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// `wt config alias dry-run <name>` shows the expanded command without running it
/// (no approval needed — preview never executes project commands).
#[rstest]
fn test_config_alias_dry_run(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
hello = "echo Hello from {{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "dry-run", "hello"],
        Some(&feature_path),
    ));
}

/// Unknown alias shows error with available aliases
#[rstest]
fn test_step_alias_unknown_with_available(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
hello = "echo Hello"
deploy = "make deploy"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["nonexistent"],
        Some(&feature_path),
    ));
}

/// Typo in alias name suggests the closest match
#[rstest]
fn test_step_alias_did_you_mean(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "make deploy"
hello = "echo Hello"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["deplyo"],
        Some(&feature_path),
    ));
}

/// Unknown step command with no aliases configured
#[rstest]
fn test_step_alias_unknown_no_aliases(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["deploy"],
        Some(&feature_path),
    ));
}

/// `--KEY=VALUE` binds to `{{ KEY }}` when the template references it.
#[rstest]
fn test_step_alias_binds_referenced_var(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
greet = "echo Hello {{ name }} from {{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "dry-run", "greet", "--", "--name=World"],
        Some(&feature_path),
    ));
}

/// `--KEY VALUE` (space-separated) binds the same way `--KEY=VALUE` does
/// when KEY is referenced and VALUE doesn't look like a flag.
#[rstest]
fn test_step_alias_binds_space_separated_var(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
greet = "echo Hello {{ name }} from {{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "dry-run", "greet", "--", "--name", "World"],
        Some(&feature_path),
    ));
}

/// `--KEY=VALUE` for a key the template doesn't reference forwards to
/// `{{ args }}` instead of binding silently.
#[rstest]
fn test_step_alias_unreferenced_key_forwards_to_args(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
run = "echo got {{ args }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "run",
        &["--env=staging", "foo"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// `--` is a literal-forward escape: every later token goes to `{{ args }}`,
/// so flag-shaped values that would normally bind are passed through verbatim.
#[rstest]
fn test_step_alias_double_dash_escape(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
run = "echo got {{ args }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "run",
        &["--", "--env=staging", "literal"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// `--KEY=VALUE` overrides built-in template variables. The user-supplied
/// value wins because `extra_refs` is applied after built-ins are seeded.
#[rstest]
fn test_step_alias_user_var_overshadows_builtin(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
show = "echo branch={{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "show",
        &["--branch=override"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// Multi-step pipeline: each step's `{{ KEY }}` references contribute to
/// the binding-eligible set, so a single invocation can bind both `env`
/// (referenced in step 1) and `region` (referenced in step 2).
#[rstest]
fn test_step_alias_multi_step_binds_across_pipeline(mut repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases]
deploy = [
    "echo step1 env={{ env }}",
    { publish = "echo step2 region={{ region }}" },
]
"#,
    );
    repo.commit("initial");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    let mut cmd = make_snapshot_cmd(
        &repo,
        "step",
        &["deploy", "--env=prod", "--region=us-east"],
        Some(&feature_path),
    );
    cmd.env("WORKTRUNK_TEST_SERIAL_CONCURRENT", "1");
    assert_cmd_snapshot!(cmd);
}

/// Alias command failure propagates exit code (-y bypasses approval)
#[rstest]
fn test_step_alias_exit_code(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
fail = "exit 42"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "step",
        &["fail"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// Alias from user config works
#[rstest]
fn test_step_alias_from_user_config(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");
    repo.write_test_config(
        r#"
[aliases]
greet = "echo Greetings from {{ branch }}"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["greet"],
        Some(&feature_path),
    ));
}

/// Top-level alias dispatch: `wt <name>` runs an alias when `<name>` is not
/// a built-in subcommand, with the same template-expansion and approval flow
/// as `wt step <name>`.
#[rstest]
fn test_top_level_alias_dispatch(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
hello = "echo Hello from {{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "hello",
        &[],
        Some(&feature_path),
        &["-y"],
    ));
}

/// An alias whose name matches a `wt step` built-in is unreachable via
/// `wt step <name>` (the built-in always wins) but runs from the top level
/// via `wt <name>` — there's no top-level `commit` built-in.
#[rstest]
fn test_top_level_alias_with_step_builtin_name(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
commit = "echo custom-commit"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "commit",
        &[],
        Some(&feature_path),
        &["-y"],
    ));
}

/// Top-level typo on an alias name suggests the alias in the `tip:` line,
/// matching `wt step <typo>`.
#[rstest]
fn test_top_level_alias_did_you_mean(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "make deploy"
hello = "echo Hello"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "deplyo", &[], Some(&feature_path),));
}

/// Aliases shadowed by `wt step` built-ins are filtered from the typo
/// suggestion list — `wt step commit` does not suggest a (shadowed) alias
/// named `commit`, only the real built-in.
#[rstest]
fn test_step_alias_shadows_builtin(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
commit = "echo custom-commit"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["comit"],
        Some(&feature_path),
    ));
}

/// User config aliases merge with project config aliases
#[rstest]
fn test_step_alias_merge_user_and_project(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
project-cmd = "echo from-project"
shared = "echo project-version"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");
    repo.write_test_config(
        r#"
[aliases]
user-cmd = "echo from-user"
shared = "echo user-version"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // User alias available
    assert_cmd_snapshot!(
        "user_alias",
        make_snapshot_cmd(
            &repo,
            "config",
            &["alias", "dry-run", "user-cmd"],
            Some(&feature_path),
        )
    );

    // Project alias available — dry-run never needs approval (it doesn't execute).
    assert_cmd_snapshot!(
        "project_alias",
        make_snapshot_cmd(
            &repo,
            "config",
            &["alias", "dry-run", "project-cmd"],
            Some(&feature_path),
        )
    );

    // Both definitions visible on collision: user first, then project (matches runtime order).
    assert_cmd_snapshot!(
        "user_and_project_append",
        make_snapshot_cmd(
            &repo,
            "config",
            &["alias", "dry-run", "shared"],
            Some(&feature_path),
        )
    );
}

/// Both global and per-project user aliases execute in order on name collision.
///
/// Uses project config (`.config/wt.toml`) + user config to verify the
/// project-vs-user append, since `test_aliases_accessor_appends_on_collision`
/// already covers the user-config internal append via unit test.
#[rstest]
fn test_alias_append_executes_both(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
greet = "echo PROJECT"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");
    repo.write_test_config(
        r#"
[aliases]
greet = "echo USER"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // Both commands execute: user first, then project (-y approves project alias)
    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "step",
        &["greet"],
        Some(&feature_path),
        &["-y"],
    ));
}

// ============================================================================
// Approval tests
// ============================================================================

/// Helper for alias approval snapshot tests
fn snapshot_alias_approval(
    test_name: &str,
    repo: &TestRepo,
    alias_args: &[&str],
    approve: bool,
    cwd: Option<&std::path::Path>,
) {
    let mut cmd = make_snapshot_cmd(repo, "step", alias_args, cwd);
    cmd.stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());

    let mut child = cmd.spawn().unwrap();

    {
        let stdin = child.stdin.as_mut().unwrap();
        let response = if approve { b"y\n" } else { b"n\n" };
        stdin.write_all(response).unwrap();
    }

    let output = child.wait_with_output().unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let combined = format!(
        "exit_code: {}\n----- stdout -----\n{}\n----- stderr -----\n{}",
        output.status.code().unwrap_or(-1),
        stdout,
        stderr
    );

    insta::assert_snapshot!(test_name, combined);
}

/// Project-config alias prompts for approval in non-TTY (fails with hint)
#[rstest]
fn test_alias_approval_project_config_prompts(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo deploying {{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // Without --yes, project alias triggers approval prompt (fails in non-TTY)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["deploy"],
        Some(&feature_path),
    ));
}

/// Already-approved project-config alias runs without re-prompting
#[rstest]
fn test_alias_approval_already_approved(mut repo: TestRepo) {
    // Remove origin so worktrunk uses directory name as project identifier
    repo.run_git(&["remote", "remove", "origin"]);

    repo.write_project_config(
        r#"
[aliases]
deploy = "echo deploying {{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    // Pre-approve the alias command
    repo.write_test_approvals(&format!(
        r#"[projects.'{}']
approved-commands = ["echo deploying {{{{ branch }}}}"]
"#,
        repo.project_id()
    ));

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // Should run without prompting
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["deploy"],
        Some(&feature_path),
    ));
}

/// User-config alias skips approval entirely
#[rstest]
fn test_alias_approval_user_config_skips(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");
    repo.write_test_config(
        r#"
[aliases]
deploy = "echo deploying from user config"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // User alias runs without approval
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["deploy"],
        Some(&feature_path),
    ));
}

/// User override of project alias skips approval (user is trusted)
#[rstest]
fn test_alias_approval_user_and_project_both_need_approval(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo project deploy"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");
    repo.write_test_config(
        r#"
[aliases]
deploy = "echo user deploy"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // Both run with -y: user first, then project (project needs approval)
    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "step",
        &["deploy"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// -y bypasses approval for project-config alias without saving
#[rstest]
fn test_alias_approval_yes_bypasses(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo deploying"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // First run with -y succeeds
    assert_cmd_snapshot!(
        "alias_approval_yes_first_run",
        make_snapshot_cmd_with_global_flags(
            &repo,
            "step",
            &["deploy"],
            Some(&feature_path),
            &["-y"],
        )
    );

    // Second run without -y should still prompt (-y doesn't save approval)
    assert_cmd_snapshot!(
        "alias_approval_yes_second_run_prompts",
        make_snapshot_cmd(&repo, "step", &["deploy"], Some(&feature_path),)
    );
}

// ============================================================================
// Directive file passthrough
// ============================================================================

/// `wt step <alias>` passes the parent's `WORKTRUNK_DIRECTIVE_CD_FILE` through
/// to the alias subprocess so inner `wt switch --create` calls can land the
/// user in the new worktree.
///
/// Regression test for #2075: without the passthrough, an alias that wraps
/// `wt switch --create` prints the "shell integration not installed" hint and
/// the parent shell never `cd`s into the new worktree.
#[rstest]
fn test_alias_passes_directive_file_to_subprocess(repo: TestRepo) {
    repo.commit("initial");

    // Escape the wt binary path for embedding in a sh -c command string.
    // Test temp paths never contain single quotes.
    let wt = wt_bin();
    let wt_str = wt.to_string_lossy();
    assert!(
        !wt_str.contains('\''),
        "wt binary path should not contain single quotes: {wt_str}"
    );
    // Double backslashes so the Windows path (e.g. `D:\a\worktrunk\...\wt.exe`)
    // parses as literal characters inside a TOML basic string rather than
    // being interpreted as escape sequences (`\a`, `\w`, ...).
    let wt_toml = wt_str.replace('\\', r"\\");

    // Alias body invokes the test wt binary directly (PATH lookup in the
    // subprocess shell wouldn't find it).
    repo.write_test_config(&format!(
        r#"
[aliases]
new-branch = "'{wt_toml}' switch --create alias-created"
"#
    ));

    let (cd_path, exec_path, _guard) = directive_files();

    let mut cmd = repo.wt_command();
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["step", "new-branch"]);
    let output = cmd.output().unwrap();

    assert!(
        output.status.success(),
        "wt step new-branch failed: stdout={}\nstderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );

    let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
    assert!(
        !cd_content.trim().is_empty(),
        "alias wrapping `wt switch --create` should write a path to the \
         CD directive file, got: {cd_content:?}"
    );
    assert!(
        cd_content.contains("alias-created"),
        "cd directive should target the new worktree (alias-created), got: {cd_content:?}"
    );

    // Stderr should NOT contain the "shell integration not installed" hint
    // — that hint is what appears when the inner wt can't find the directive
    // file, which is exactly the bug this test guards against.
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("shell integration"),
        "inner wt should not warn about shell integration being uninstalled, got: {stderr}",
    );
}

/// Pipeline aliases announce their structure: named serial and concurrent
/// steps appear in the "Running alias" line, joined by `;` and `,`.
///
/// `WORKTRUNK_TEST_SERIAL_CONCURRENT=1` forces the concurrent step to run
/// commands sequentially (in declaration order) so the snapshot captures a
/// deterministic interleaving — analogous to how `RAYON_NUM_THREADS=1` is
/// used in `step_prune` tests.
#[rstest]
fn test_alias_pipeline_announcement(mut repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases]
deploy = [
    { install = "echo INSTALL" },
    { build = "echo BUILD", lint = "echo LINT" },
]
"#,
    );
    repo.commit("initial");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    let mut cmd = make_snapshot_cmd(&repo, "step", &["deploy"], Some(&feature_path));
    cmd.env("WORKTRUNK_TEST_SERIAL_CONCURRENT", "1");
    assert_cmd_snapshot!(cmd);
}

/// Concurrent alias steps (named table) execute all commands
#[rstest]
fn test_alias_concurrent_steps(mut repo: TestRepo) {
    // Named table form: commands run concurrently within the step
    repo.write_test_config(
        r#"
[aliases.build]
lint = "echo LINT"
test = "echo TEST"
"#,
    );
    repo.commit("initial");
    let feature_path = repo.add_worktree("feature");

    let mut cmd = repo.wt_command();
    cmd.args(["step", "build"]).current_dir(&feature_path);
    let output = cmd.output().unwrap();

    assert!(
        output.status.success(),
        "concurrent alias failed: stderr={}",
        String::from_utf8_lossy(&output.stderr),
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    // Both commands should have run (order may vary due to concurrency)
    assert!(stderr.contains("LINT"), "expected LINT in output: {stderr}");
    assert!(stderr.contains("TEST"), "expected TEST in output: {stderr}");
}

/// Concurrent alias commands have their output streamed with a per-command
/// colored prefix label (`{name} │ …`), so multiple children's lines remain
/// attributable even when they interleave.
#[rstest]
fn test_alias_concurrent_prefixes_output(mut repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases.build]
lint = "echo HELLO_LINT"
test = "echo HELLO_TEST"
"#,
    );
    repo.commit("initial");
    let feature_path = repo.add_worktree("feature");

    let mut cmd = repo.wt_command();
    cmd.args(["step", "build"])
        .current_dir(&feature_path)
        .env("NO_COLOR", "1");
    let output = cmd.output().unwrap();

    assert!(
        output.status.success(),
        "concurrent alias failed: stderr={}",
        String::from_utf8_lossy(&output.stderr),
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    // Each command must produce a line starting with its prefixed label and
    // separated by the box-drawing `│` that the executor emits. Whitespace
    // between label and `│` varies with padding-to-widest-label.
    for (label, body) in [("lint", "HELLO_LINT"), ("test", "HELLO_TEST")] {
        let has_prefixed_line = stderr
            .lines()
            .any(|l| l.starts_with(label) && l.contains('') && l.contains(body));
        assert!(
            has_prefixed_line,
            "expected a line starting with '{label}' containing '{body}' and a '│' separator, got:\n{stderr}"
        );
    }
}

/// A failing concurrent step causes the alias to fail. Covers the error
/// propagation path in the `HookStep::Concurrent` join loop, complementing
/// the happy-path `test_alias_concurrent_steps` above.
#[rstest]
fn test_alias_concurrent_step_failure(repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases.check]
ok = "true"
fail = "exit 1"
"#,
    );
    repo.commit("initial");

    let mut cmd = repo.wt_command();
    cmd.args(["step", "check"]);
    let output = cmd.output().expect("wt step check failed to spawn");
    assert!(
        !output.status.success(),
        "wt step check should fail when a concurrent step exits non-zero"
    );
}

/// SIGINT sent to `wt step <alias>` while a concurrent group is mid-flight
/// must reach every child's process group and tear them all down — otherwise
/// Ctrl-C on a long-running concurrent alias would leave orphans behind.
///
/// We spawn the alias in its own process group, wait until BOTH children have
/// written their "start" marker (proving they're actually running concurrently),
/// send SIGINT to the group, then verify that the subsequent "done" markers
/// never appear — every child was interrupted.
#[rstest]
#[cfg(unix)]
fn test_alias_concurrent_receives_sigint(repo: TestRepo) {
    use crate::common::wait_for_file_content;
    use nix::sys::signal::{Signal, kill};
    use nix::unistd::Pid;
    use std::os::unix::process::CommandExt;
    use std::process::Stdio;

    repo.write_test_config(
        r#"
[aliases.slow]
one = "sh -c 'echo start-one >> slow_one.log; sleep 30; echo done-one >> slow_one.log'"
two = "sh -c 'echo start-two >> slow_two.log; sleep 30; echo done-two >> slow_two.log'"
"#,
    );
    repo.commit("initial");

    let mut cmd = repo.wt_command();
    cmd.args(["step", "slow"]);
    cmd.current_dir(repo.root_path());
    cmd.stdout(Stdio::null());
    cmd.stderr(Stdio::null());
    cmd.process_group(0); // wt becomes leader of its own process group
    let mut child = cmd.spawn().expect("failed to spawn wt step slow");

    // Wait until BOTH children write their start marker — proves the group
    // is running concurrently before we send the signal.
    let one_log = repo.root_path().join("slow_one.log");
    let two_log = repo.root_path().join("slow_two.log");
    wait_for_file_content(&one_log);
    wait_for_file_content(&two_log);

    // SIGINT the wt process group (wt == leader). The concurrent executor's
    // signal forwarder must propagate it to every child's process group.
    let wt_pgid = Pid::from_raw(child.id() as i32);
    kill(Pid::from_raw(-wt_pgid.as_raw()), Signal::SIGINT)
        .expect("failed to send SIGINT to wt's process group");

    let status = child.wait().expect("failed to wait for wt");

    use std::os::unix::process::ExitStatusExt;
    assert!(
        status.signal() == Some(2) || status.code() == Some(130),
        "wt should exit from SIGINT (signal 2) or with code 130, got: {status:?}"
    );

    // Grace period — the killed children must NOT reach their "done" write.
    std::thread::sleep(std::time::Duration::from_millis(500));
    for log in [&one_log, &two_log] {
        let contents = std::fs::read_to_string(log).unwrap_or_default();
        assert!(
            !contents.contains("done"),
            "sibling child reached 'done' after SIGINT, log: {contents:?}"
        );
    }
}

/// A second SIGINT (user mashing Ctrl-C) must escalate to SIGKILL on every
/// child immediately — otherwise a child that traps SIGINT keeps the group
/// alive for up to N × 400ms of per-pgid escalation, with subsequent
/// presses silently discarded.
#[rstest]
#[cfg(unix)]
fn test_alias_concurrent_second_sigint_kills(repo: TestRepo) {
    use crate::common::wait_for_file_content;
    use nix::sys::signal::{Signal, kill};
    use nix::unistd::Pid;
    use std::os::unix::process::CommandExt;
    use std::process::Stdio;

    // Both children trap SIGINT and sleep; first SIGINT does nothing
    // (graceful escalation to SIGTERM is also trapped), a second SIGINT
    // must SIGKILL the pgids and exit wt promptly.
    repo.write_test_config(
        r#"
[aliases.stubborn]
one = "sh -c 'trap \"\" INT TERM; echo start-one >> stubborn_one.log; sleep 30'"
two = "sh -c 'trap \"\" INT TERM; echo start-two >> stubborn_two.log; sleep 30'"
"#,
    );
    repo.commit("initial");

    let mut cmd = repo.wt_command();
    cmd.args(["step", "stubborn"]);
    cmd.current_dir(repo.root_path());
    cmd.stdout(Stdio::null());
    cmd.stderr(Stdio::null());
    cmd.process_group(0);
    let mut child = cmd.spawn().expect("failed to spawn wt step stubborn");

    wait_for_file_content(&repo.root_path().join("stubborn_one.log"));
    wait_for_file_content(&repo.root_path().join("stubborn_two.log"));

    let wt_pgid = Pid::from_raw(child.id() as i32);
    // First SIGINT — trapped by children; graceful path chews through
    // escalation serially.
    kill(Pid::from_raw(-wt_pgid.as_raw()), Signal::SIGINT).expect("failed to send first SIGINT");

    std::thread::sleep(std::time::Duration::from_millis(100));

    // Second SIGINT — impatient path should SIGKILL the whole tree now.
    kill(Pid::from_raw(-wt_pgid.as_raw()), Signal::SIGINT).expect("failed to send second SIGINT");

    let start = std::time::Instant::now();
    let _status = child.wait().expect("failed to wait for wt");
    let elapsed = start.elapsed();

    // With only graceful escalation (200ms × 2 grace windows × 2 pgids),
    // worst case would be ~800ms. The impatient SIGKILL should be faster
    // still. Give 3s headroom for slow CI without being so loose that a
    // regression (no SIGKILL on 2nd press) would slip through — that
    // regression would leave wt waiting ~60s for the sleeps to finish.
    assert!(
        elapsed < std::time::Duration::from_secs(3),
        "wt took too long to die after 2nd SIGINT; impatient path may not be firing: {elapsed:?}"
    );
}

/// Non-UTF-8 bytes and CRLF line endings in child output must not stall the
/// executor. Earlier code using `BufRead::lines()` returned `InvalidData` on
/// the first invalid byte and terminated the iterator, leaving the child's
/// pipe un-drained and `child.wait()` hanging forever. Also exercises the
/// `\r\n` strip path so trailing carriage returns don't render visibly.
#[rstest]
fn test_alias_concurrent_handles_non_utf8(repo: TestRepo) {
    // `printf` emits a raw 0xff byte (invalid as a lone UTF-8 sequence), a
    // CRLF-terminated line, then `yes` floods 50_000 more valid UTF-8 lines.
    // If the reader stopped at the bad byte, the pipe would fill and the
    // child would block — we'd time out.
    repo.write_test_config(
        r#"
[aliases.noisy]
mixed = "sh -c 'printf \"BEFORE\\n\\xff\\nCRLF-LINE\\r\\nAFTER\\n\"; yes PAYLOAD | head -n 50000'"
"#,
    );
    repo.commit("initial");

    let mut cmd = repo.wt_command();
    cmd.args(["step", "noisy"]);
    let output = cmd.output().expect("wt step noisy failed to spawn");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "alias should succeed despite non-UTF-8 byte, got: {status:?}\nlast 500 bytes of stderr: {tail}",
        status = output.status,
        tail = &stderr[stderr.len().saturating_sub(500)..],
    );

    // All clean lines plus all 50_000 flood lines must land — proves the
    // reader kept going past the invalid byte.
    assert!(stderr.contains("BEFORE"), "expected BEFORE in stderr");
    assert!(
        stderr.contains("AFTER"),
        "expected AFTER in stderr (reader stopped at the invalid byte)"
    );
    // CRLF line ending: the reader strips the trailing \r, so the visible
    // line is `CRLF-LINE` not `CRLF-LINE\r`. Any `\r` in the output would
    // indicate the strip didn't fire.
    assert!(
        stderr.contains("CRLF-LINE"),
        "expected CRLF-LINE (with the \\r stripped) in stderr"
    );
    assert!(
        !stderr.contains("CRLF-LINE\r"),
        "trailing \\r should have been stripped before printing"
    );
    assert_eq!(
        stderr.matches("PAYLOAD").count(),
        50_000,
        "expected 50000 PAYLOAD lines after the invalid byte, got {}",
        stderr.matches("PAYLOAD").count(),
    );
}

/// A concurrent child that produces a large volume of stdout must not
/// deadlock the executor — the reader thread has to keep draining the pipe so
/// the child can keep writing. We run two commands, each emitting ~400 KB, and
/// assert both streams land in stderr intact.
#[rstest]
fn test_alias_concurrent_large_output(repo: TestRepo) {
    // yes piped through head is a portable way to generate many lines fast.
    // Each command produces ~400 KB = 50_000 * ~8 bytes ("aaaa...\n" etc.).
    // If the reader thread were ever to stall, the child's stdout pipe would
    // fill (default ~64 KB) and the child would block forever — the test would
    // time out rather than produce a misleading pass.
    repo.write_test_config(
        r#"
[aliases.bulk]
first  = "yes 'FIRST-PAYLOAD-AAAAA' | head -n 50000"
second = "yes 'SECOND-PAYLOAD-BBBBB' | head -n 50000"
"#,
    );
    repo.commit("initial");

    let mut cmd = repo.wt_command();
    cmd.args(["step", "bulk"]);
    let output = cmd.output().expect("wt step bulk failed to spawn");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "concurrent alias with large output should exit 0, got: {status:?}\nlast 500 bytes of stderr: {tail}",
        status = output.status,
        tail = &stderr[stderr.len().saturating_sub(500)..],
    );

    // Count occurrences so we know both children's full output was streamed —
    // not truncated by a blocked pipe. 50_000 exact matches per payload.
    let first_count = stderr.matches("FIRST-PAYLOAD-AAAAA").count();
    let second_count = stderr.matches("SECOND-PAYLOAD-BBBBB").count();
    assert_eq!(
        first_count, 50_000,
        "expected 50000 occurrences of first payload in stderr, got {first_count}"
    );
    assert_eq!(
        second_count, 50_000,
        "expected 50000 occurrences of second payload in stderr, got {second_count}"
    );
}

/// Pipeline-form aliases (list of steps) run sequentially. A later step
/// referencing `{{ vars.X }}` must see vars set by an earlier step —
/// `expand_shell_template` reads `vars.*` fresh from git config on each call.
#[rstest]
fn test_alias_pipeline_vars_across_steps(repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases]
deploy = [
    "git config worktrunk.state.main.vars.target 'staging'",
    { publish = "echo target={{ vars.target }} > alias_lazy.txt" },
]
"#,
    );
    repo.commit("initial");

    let mut cmd = repo.wt_command();
    cmd.args(["step", "deploy"]);
    let output = cmd.output().expect("wt step deploy failed to spawn");
    assert!(
        output.status.success(),
        "wt step deploy failed: stdout={}\nstderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );

    let marker = repo.root_path().join("alias_lazy.txt");
    let content = std::fs::read_to_string(&marker)
        .unwrap_or_else(|e| panic!("missing marker {marker:?}: {e}"));
    assert_eq!(
        content.trim(),
        "target=staging",
        "lazy step should see var set by prior serial step"
    );
}

/// `dry-run` for a pipeline where a later step references `{{ vars.X }}` set by
/// an earlier step succeeds, mirroring the lazy execution path. The unresolved
/// `vars.*` reference is shown as the raw template since its value isn't
/// knowable until the earlier step actually runs.
#[rstest]
fn test_config_alias_dry_run_vars_across_steps(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = [
    "git config worktrunk.state.main.vars.target 'prod'",
    { publish = "echo deploying to {{ vars.target }}" },
]
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // Must succeed: dry-run must not require vars.* to be resolvable.
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "dry-run", "deploy"],
        Some(&feature_path),
    ));
}

/// `dry-run` still catches template syntax errors (e.g., `{{ vars..foo }}`) even
/// on the lazy path where `vars.*` rendering is skipped.
#[rstest]
fn test_config_alias_dry_run_catches_syntax_error(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
broken = "echo {{ vars..target }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let output = repo
        .wt_command()
        .args(["config", "alias", "dry-run", "broken"])
        .current_dir(&feature_path)
        .output()
        .unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !output.status.success(),
        "dry-run should fail on syntax error; stderr:\n{stderr}"
    );
    assert!(
        stderr.contains("syntax error"),
        "expected 'syntax error' in stderr, got:\n{stderr}"
    );
}

/// Retired `wt <alias> --dry-run` flag produces an actionable error pointing at
/// the new subcommand. Snapshots the top-level path; the shared parser covers
/// both `wt <alias>` and `wt step <alias>` dispatch routes (unit test in
/// `commands::alias::tests::test_parse_errors` verifies the message verbatim).
#[rstest]
fn test_retired_dry_run_flag(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo hi"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "deploy",
        &["--dry-run"],
        Some(&feature_path),
    ));
}

/// Retired `--dry-run` bail also fires through `wt step <alias>` — the parser
/// is shared, but this pins the `step_alias` dispatch route specifically.
#[rstest]
fn test_retired_dry_run_flag_via_step(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo hi"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["deploy", "--dry-run"],
        Some(&feature_path),
    ));
}

/// `wt <alias> --help` prints guidance rather than forwarding `--help` into
/// `{{ args }}`. Aliases have no clap-style help page; the canonical
/// inspection path is `wt config alias show / dry-run`.
#[rstest]
fn test_alias_help_flag_prints_hint(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo hi {{ args }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "deploy",
        &["--help"],
        Some(&feature_path),
    ));
}

/// `wt <alias> -- --help` bypasses the intercept and forwards `--help` into
/// the alias body — the documented escape.
#[rstest]
fn test_alias_help_flag_after_double_dash_forwards(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo {{ args }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "deploy",
        &["--", "--help"],
        Some(&feature_path),
    ));
}

/// `wt config alias show <name>` prints the configured template text, source-labeled.
#[rstest]
fn test_config_alias_show_single(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "make deploy BRANCH={{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show", "deploy"],
        Some(&feature_path),
    ));
}

/// Unknown alias name triggers a did-you-mean suggestion.
#[rstest]
fn test_config_alias_show_unknown_suggests(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "make deploy"
hello = "echo hi"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show", "deplyo"],
        Some(&feature_path),
    ));
}

/// Multi-step pipeline renders with per-step structure in the header.
#[rstest]
fn test_config_alias_show_pipeline(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[[aliases.release]]
install = "npm install"

[[aliases.release]]
build = "npm run build"
lint = "npm run lint"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show", "release"],
        Some(&feature_path),
    ));
}

/// Positional args via `wt config alias dry-run <name> -- foo bar` flow through as `{{ args }}`.
#[rstest]
fn test_config_alias_dry_run_positional_args(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
s = "wt switch {{ args }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "dry-run", "s", "--", "target-branch"],
        Some(&feature_path),
    ));
}

/// `wt config alias show <name>` with the same alias defined in both user and
/// project config prints both entries in runtime order (user first).
#[rstest]
fn test_config_alias_show_user_and_project(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo from project"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");
    repo.write_test_config(
        r#"
[aliases]
deploy = "echo from user"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show", "deploy"],
        Some(&feature_path),
    ));
}

/// Unknown alias name with no similar configured aliases shows a plain error
/// without a "did you mean" tail.
#[rstest]
fn test_config_alias_show_unknown_no_suggestions(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo hi"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // Query name shares no meaningful prefix with any configured alias — the
    // Jaro-Winkler threshold rejects it, so the error has no suggestion list.
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show", "zzzzzzzz"],
        Some(&feature_path),
    ));
}

/// `wt config alias show <name>` on an alias whose name is also a top-level
/// built-in subcommand warns that the alias is unreachable via `wt <name>`.
/// The alias is still configured, so the show output itself is shown — the
/// warning is an advisory on stderr.
#[rstest]
fn test_config_alias_show_warns_on_shadowed_name(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
list = "echo custom list"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show", "list"],
        Some(&feature_path),
    ));
}

/// `wt config alias dry-run` on a shadowed name emits the same advisory as
/// `show` — both are discovery surfaces, so both point out the shadowing.
#[rstest]
fn test_config_alias_dry_run_warns_on_shadowed_name(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
list = "echo custom list"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "dry-run", "list"],
        Some(&feature_path),
    ));
}

/// `wt step` with no subcommand lists built-in steps plus configured aliases.
///
/// Skipped on Windows: clap renders `[experimental]` subcommand tags
/// differently (markdown escaping), same reason `tests/integration_tests/help.rs`
/// is Windows-gated.
#[cfg(not(windows))]
#[rstest]
fn test_step_list_with_aliases(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "make deploy BRANCH={{ branch }}"
port = "echo http://localhost:{{ branch | hash_port }}"
squash = "this shadows the built-in"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &[], Some(&feature_path)));
}

/// `wt step` without configured aliases still works — just prints help.
#[cfg(not(windows))]
#[rstest]
fn test_step_list_no_aliases(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &[], Some(&feature_path)));
}

/// `wt step --help` includes the same Aliases section as bare `wt step`.
///
/// Without this, users running `--help` in the normal discovery flow would
/// see only built-in commands and miss their configured aliases.
#[cfg(not(windows))]
#[rstest]
fn test_step_help_includes_aliases(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "make deploy BRANCH={{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["-h"],
        Some(&feature_path)
    ));
}

/// `wt step --help` must not emit deprecation warnings or write `.new`
/// migration files when the user config contains deprecated patterns —
/// help is a discovery surface, not an execution surface, and the user
/// will see those warnings from `wt config show` and normal commands.
#[cfg(not(windows))]
#[rstest]
fn test_step_help_silent_with_deprecated_user_config(repo: TestRepo) {
    // Deprecated `main_worktree` template variable — migrated to `repo`.
    repo.write_test_config(
        r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"
"#,
    );
    let migration_file = repo.test_config_path().with_extension("toml.new");

    let output = repo.wt_command().args(["step", "--help"]).output().unwrap();

    assert!(
        output.status.success(),
        "step --help should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        stderr, "",
        "step --help must emit no stderr on deprecated user config"
    );
    assert!(
        !migration_file.exists(),
        "step --help must not write .new migration file at {}",
        migration_file.display()
    );
}

/// `wt -C <other> step --help` lists aliases from `<other>`'s project config,
/// not from the process cwd. Without applying global options before the help
/// branch, the Aliases section was rendered from the wrong repo.
#[cfg(not(windows))]
#[rstest]
fn test_step_help_honors_dash_c(repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
xyzzy = "echo nothing happens"
"#,
    );
    repo.commit("Add alias config");
    let repo_path = repo.root_path().to_path_buf();

    // Invoke from a directory that is *not* inside the repo so the alias can
    // only be discovered via -C. Using the system temp dir keeps this
    // independent of the test's working directory.
    let cwd = std::env::temp_dir();
    let mut cmd = repo.wt_command();
    cmd.current_dir(&cwd)
        .args(["-C", repo_path.to_str().unwrap(), "step", "--help"]);
    let output = cmd.output().expect("failed to run wt");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stdout.contains("xyzzy"),
        "expected `xyzzy` alias to appear in `wt -C <repo> step --help` output\n\
         stdout:\n{stdout}\nstderr:\n{stderr}"
    );
}

/// Positional args after the alias name forward to `{{ args }}` in the
/// template — space-joined and shell-escaped so args with spaces, quotes,
/// or metacharacters splice safely into a command line.
#[rstest]
fn test_step_alias_forwards_positional_args(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
run = "echo got {{ args }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "run",
        &["one", "two three", "four"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// Templates can treat `{{ args }}` as a sequence: indexing, iteration,
/// and `length` all work because `ShellArgs` reports as `ObjectRepr::Seq`.
#[rstest]
fn test_step_alias_args_sequence_access(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
show = '''echo first={{ args[0] }}; echo count={{ args | length }}; echo each={% for a in args %} {{ a }}{% endfor %}'''
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "show",
        &["alpha", "beta gamma"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// With no positionals, `{{ args }}` renders empty — the rest of the line
/// stays intact and no stray whitespace is introduced.
#[rstest]
fn test_step_alias_empty_args_renders_empty(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
run = "echo [{{ args }}]"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "run",
        &[],
        Some(&feature_path),
        &["-y"],
    ));
}

/// `wt s some-branch` with `s = "wt switch {{ args }}"` forwards the
/// positional into the expanded command. Verified via `wt config alias dry-run`
/// so the inner `wt switch` is not actually executed.
#[rstest]
fn test_top_level_alias_positional_expands_in_dry_run(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
s = "wt switch {{ args }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "dry-run", "s", "--", "target-branch"],
        Some(&feature_path),
    ));
}

/// Declining approval prevents alias execution
#[rstest]
fn test_alias_approval_decline(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo deploying"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    snapshot_alias_approval(
        "alias_approval_decline",
        &repo,
        &["deploy"],
        false,
        Some(&feature_path),
    );
}