worktrunk 0.37.1

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
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
//! Integration tests for user-level hooks (~/.config/worktrunk/config.toml)
//!
//! User hooks differ from project hooks:
//! - Run for all repositories
//! - Execute before project hooks
//! - Don't require approval
//! - Skipped together with project hooks via --no-hooks

use crate::common::{
    TestRepo, make_snapshot_cmd, repo, resolve_git_common_dir, setup_snapshot_settings,
    wait_for_file, wait_for_file_content, wait_for_file_count,
};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use std::fs;
use std::thread;
use std::time::Duration;

// Note: Duration is still imported for SLEEP_FOR_ABSENCE_CHECK (testing command did NOT run)

/// Wait duration when checking file absence (testing command did NOT run).
const SLEEP_FOR_ABSENCE_CHECK: Duration = Duration::from_millis(500);

// ============================================================================
// User Post-Create Hook Tests
// ============================================================================

/// Helper to create snapshot for switch commands
fn snapshot_switch(test_name: &str, repo: &TestRepo, args: &[&str]) {
    let settings = setup_snapshot_settings(repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(repo, "switch", args, None);
        assert_cmd_snapshot!(test_name, cmd);
    });
}

#[rstest]
fn test_user_post_create_hook_executes(repo: TestRepo) {
    // Write user config with post-create hook (no project config)
    repo.write_test_config(
        r#"[post-create]
log = "echo 'USER_POST_CREATE_RAN' > user_hook_marker.txt"
"#,
    );

    snapshot_switch("user_post_create_executes", &repo, &["--create", "feature"]);

    // Verify user hook actually ran
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let marker_file = worktree_path.join("user_hook_marker.txt");
    assert!(
        marker_file.exists(),
        "User post-create hook should have created marker file"
    );

    let contents = fs::read_to_string(&marker_file).unwrap();
    assert!(
        contents.contains("USER_POST_CREATE_RAN"),
        "Marker file should contain expected content"
    );
}

#[rstest]
fn test_user_hooks_run_before_project_hooks(repo: TestRepo) {
    // Create project config with post-create hook
    repo.write_project_config(r#"post-create = "echo 'PROJECT_HOOK' >> hook_order.txt""#);
    repo.commit("Add project config");

    // Write user config with user hook AND pre-approve project command
    repo.write_test_config(
        r#"[post-create]
log = "echo 'USER_HOOK' >> hook_order.txt"
"#,
    );
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo 'PROJECT_HOOK' >> hook_order.txt"]
"#,
    );

    snapshot_switch("user_hooks_before_project", &repo, &["--create", "feature"]);

    // Verify execution order
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let order_file = worktree_path.join("hook_order.txt");
    assert!(order_file.exists());

    let contents = fs::read_to_string(&order_file).unwrap();
    let lines: Vec<&str> = contents.lines().collect();

    assert_eq!(lines.len(), 2);
    assert_eq!(lines[0], "USER_HOOK", "User hook should run first");
    assert_eq!(lines[1], "PROJECT_HOOK", "Project hook should run second");
}

#[rstest]
fn test_user_hooks_no_approval_required(repo: TestRepo) {
    // Write user config with hook but NO pre-approved commands
    // (unlike project hooks, user hooks don't require approval)
    repo.write_test_config(
        r#"[post-create]
setup = "echo 'NO_APPROVAL_NEEDED' > no_approval.txt"
"#,
    );

    snapshot_switch("user_hooks_no_approval", &repo, &["--create", "feature"]);

    // Verify hook ran without approval
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let marker_file = worktree_path.join("no_approval.txt");
    assert!(
        marker_file.exists(),
        "User hook should run without pre-approval"
    );
}

#[rstest]
fn test_no_hooks_flag_skips_all_hooks(repo: TestRepo) {
    // Create project config with post-create hook
    repo.write_project_config(r#"post-create = "echo 'PROJECT_HOOK' > project_marker.txt""#);
    repo.commit("Add project config");

    // Write user config with both user hook and pre-approved project command
    repo.write_test_config(
        r#"[post-create]
log = "echo 'USER_HOOK' > user_marker.txt"
"#,
    );
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo 'PROJECT_HOOK' > project_marker.txt"]
"#,
    );

    // Create worktree with --no-hooks (skips ALL hooks)
    snapshot_switch(
        "no_hooks_skips_all_hooks",
        &repo,
        &["--create", "feature", "--no-hooks"],
    );

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");

    // User hook should NOT have run
    let user_marker = worktree_path.join("user_marker.txt");
    assert!(
        !user_marker.exists(),
        "User hook should be skipped with --no-hooks"
    );

    // Project hook should also NOT have run (--no-hooks skips ALL hooks)
    let project_marker = worktree_path.join("project_marker.txt");
    assert!(
        !project_marker.exists(),
        "Project hook should also be skipped with --no-hooks"
    );
}

#[rstest]
fn test_user_post_create_hook_failure(repo: TestRepo) {
    // Write user config with failing hook
    repo.write_test_config(
        r#"[post-create]
failing = "exit 1"
"#,
    );

    // Failing pre-start hook (via deprecated post-create name) aborts with FailFast.
    // The worktree is already created before pre-start runs (it was renamed from
    // post-create), so the worktree exists but the command exits non-zero.
    snapshot_switch("user_post_create_failure", &repo, &["--create", "feature"]);

    // Worktree exists (created before pre-start ran) but the command failed
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    assert!(
        worktree_path.exists(),
        "Worktree should exist — it was created before pre-start ran"
    );
}

// ============================================================================
// User Post-Start Hook Tests (Background)
// ============================================================================

#[rstest]
fn test_user_post_start_hook_executes(repo: TestRepo) {
    // Write user config with post-start hook (background)
    repo.write_test_config(
        r#"[post-start]
bg = "echo 'USER_POST_START_RAN' > user_bg_marker.txt"
"#,
    );

    snapshot_switch("user_post_start_executes", &repo, &["--create", "feature"]);

    // Wait for background hook to complete and write content
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let marker_file = worktree_path.join("user_bg_marker.txt");
    wait_for_file_content(&marker_file);

    let contents = fs::read_to_string(&marker_file).unwrap();
    assert!(
        contents.contains("USER_POST_START_RAN"),
        "User post-start hook should have run in background"
    );
}

#[rstest]
fn test_user_post_start_skipped_with_no_hooks(repo: TestRepo) {
    // Write user config with post-start hook
    repo.write_test_config(
        r#"[post-start]
bg = "echo 'USER_BG' > user_bg_marker.txt"
"#,
    );

    snapshot_switch(
        "user_post_start_skipped_no_hooks",
        &repo,
        &["--create", "feature", "--no-hooks"],
    );

    // Wait to ensure background hook would have had time to run
    thread::sleep(SLEEP_FOR_ABSENCE_CHECK);

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let marker_file = worktree_path.join("user_bg_marker.txt");
    assert!(
        !marker_file.exists(),
        "User post-start hook should be skipped with --no-hooks"
    );
}

// ============================================================================
// User Pre-Merge Hook Tests
// ============================================================================

/// Helper for merge snapshots
fn snapshot_merge(test_name: &str, repo: &TestRepo, args: &[&str], cwd: Option<&std::path::Path>) {
    let settings = setup_snapshot_settings(repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(repo, "merge", args, cwd);
        assert_cmd_snapshot!(test_name, cmd);
    });
}

#[rstest]
fn test_user_pre_merge_hook_executes(mut repo: TestRepo) {
    // Create feature worktree with a commit
    let feature_wt =
        repo.add_worktree_with_commit("feature", "feature.txt", "feature content", "Add feature");

    // Write user config with pre-merge hook
    repo.write_test_config(
        r#"[pre-merge]
check = "echo 'USER_PRE_MERGE_RAN' > user_premerge.txt"
"#,
    );

    snapshot_merge(
        "user_pre_merge_executes",
        &repo,
        &["main", "--yes", "--no-remove"],
        Some(&feature_wt),
    );

    // Verify user hook ran
    let marker_file = feature_wt.join("user_premerge.txt");
    assert!(marker_file.exists(), "User pre-merge hook should have run");
}

#[rstest]
fn test_user_pre_merge_hook_failure_blocks_merge(mut repo: TestRepo) {
    // Create feature worktree with a commit
    let feature_wt =
        repo.add_worktree_with_commit("feature", "feature.txt", "feature content", "Add feature");

    // Write user config with failing pre-merge hook
    repo.write_test_config(
        r#"[pre-merge]
check = "exit 1"
"#,
    );

    // Failing pre-merge hook should block the merge
    snapshot_merge(
        "user_pre_merge_failure",
        &repo,
        &["main", "--yes", "--no-remove"],
        Some(&feature_wt),
    );
}

#[rstest]
fn test_user_pre_merge_skipped_with_no_hooks(mut repo: TestRepo) {
    // Create feature worktree with a commit
    let feature_wt =
        repo.add_worktree_with_commit("feature", "feature.txt", "feature content", "Add feature");

    // Write user config with pre-merge hook that creates a marker
    repo.write_test_config(
        r#"[pre-merge]
check = "echo 'USER_PRE_MERGE' > user_premerge_marker.txt"
"#,
    );

    snapshot_merge(
        "user_pre_merge_skipped_no_hooks",
        &repo,
        &["main", "--yes", "--no-remove", "--no-hooks"],
        Some(&feature_wt),
    );

    // User hook should NOT have run (--no-hooks skips all hooks)
    let marker_file = feature_wt.join("user_premerge_marker.txt");
    assert!(
        !marker_file.exists(),
        "User pre-merge hook should be skipped with --no-hooks"
    );
}

///
/// Real Ctrl-C sends SIGINT to the entire foreground process group. We simulate this by:
/// 1. Spawning wt in its own process group (so we don't kill the test runner)
/// 2. Sending SIGINT to that process group (which includes wt and its hook children)
#[rstest]
#[cfg(unix)]
fn test_pre_merge_hook_receives_sigint(repo: TestRepo) {
    use nix::sys::signal::{Signal, kill};
    use nix::unistd::Pid;
    use std::io::Read;
    use std::os::unix::process::CommandExt;
    use std::process::Stdio;

    repo.commit("Initial commit");

    // Project pre-merge hook: write start, then sleep, then write done (if not interrupted)
    repo.write_project_config(
        r#"[pre-merge]
long = "sh -c 'echo start >> hook.log; sleep 30; echo done >> hook.log'"
"#,
    );
    repo.commit("Add pre-merge hook");

    // Spawn wt in its own process group (so SIGINT to that group doesn't kill the test)
    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.args(["hook", "pre-merge", "--yes"]);
    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 hook pre-merge");

    // Wait until hook writes "start" to hook.log (verifies the hook is running)
    let hook_log = repo.root_path().join("hook.log");
    wait_for_file_content(&hook_log);

    // Send SIGINT to wt's process group (wt's PID == its PGID since it's the leader)
    // This simulates real Ctrl-C which sends SIGINT to the foreground 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 pgrp");

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

    // wt was killed by signal, so code() returns None and we check the signal
    use std::os::unix::process::ExitStatusExt;
    assert!(
        status.signal() == Some(2) || status.code() == Some(130),
        "wt should be killed by SIGINT (signal 2) or exit 130, got: {status:?}"
    );

    // Give the (killed) hook a moment; it must not append "done"
    thread::sleep(Duration::from_millis(500));

    let mut contents = String::new();
    std::fs::File::open(&hook_log)
        .unwrap()
        .read_to_string(&mut contents)
        .unwrap();
    assert!(
        contents.trim() == "start",
        "hook should not have reached 'done'; got: {contents:?}"
    );
}

#[rstest]
#[cfg(unix)]
fn test_pre_merge_hook_receives_sigterm(repo: TestRepo) {
    use nix::sys::signal::{Signal, kill};
    use nix::unistd::Pid;
    use std::io::Read;
    use std::os::unix::process::CommandExt;
    use std::process::Stdio;

    repo.commit("Initial commit");

    // Project pre-merge hook: write start, then sleep, then write done (if not interrupted)
    repo.write_project_config(
        r#"[pre-merge]
long = "sh -c 'echo start >> hook.log; sleep 30; echo done >> hook.log'"
"#,
    );
    repo.commit("Add pre-merge hook");

    // Spawn wt in its own process group (so SIGTERM to that group doesn't kill the test)
    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.args(["hook", "pre-merge", "--yes"]);
    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 hook pre-merge");

    // Wait until hook writes "start" to hook.log (verifies the hook is running)
    let hook_log = repo.root_path().join("hook.log");
    wait_for_file_content(&hook_log);

    // Send SIGTERM to wt's process group (wt's PID == its PGID since it's the leader)
    let wt_pgid = Pid::from_raw(child.id() as i32);
    kill(Pid::from_raw(-wt_pgid.as_raw()), Signal::SIGTERM)
        .expect("failed to send SIGTERM to pgrp");

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

    // wt was killed by signal, so code() returns None and we check the signal
    use std::os::unix::process::ExitStatusExt;
    assert!(
        status.signal() == Some(15) || status.code() == Some(143),
        "wt should be killed by SIGTERM (signal 15) or exit 143, got: {status:?}"
    );

    // Give the (killed) hook a moment; it must not append "done"
    thread::sleep(Duration::from_millis(500));

    let mut contents = String::new();
    std::fs::File::open(&hook_log)
        .unwrap()
        .read_to_string(&mut contents)
        .unwrap();
    assert!(
        contents.trim() == "start",
        "hook should not have reached 'done'; got: {contents:?}"
    );
}

/// A signal-derived exit in one hook step must abort the rest of the pipeline
/// rather than treating the signal like an ordinary per-step failure. Drives
/// the `handle_command_error` interrupt branch end-to-end through the hook
/// path (the for-each test in `for_each.rs` covers the worktree-loop branch).
///
/// Implementation mirrors `test_for_each_aborts_on_signal_exit`: the first
/// hook step self-signals via SIGTERM after touching a marker. SIGINT against
/// the parent wt would kill the test harness, so we drive the same
/// `ChildProcessExited { signal: Some(_), .. }` path with an in-child signal.
#[rstest]
#[cfg(unix)]
fn test_pre_merge_pipeline_aborts_on_signal_exit(repo: TestRepo) {
    repo.commit("Initial commit");

    // Two pre-merge hooks: the first writes a marker then self-signals with
    // SIGTERM; the second (which must NOT run) would write its own marker.
    repo.write_project_config(
        r#"[pre-merge]
abort = "sh -c 'echo first >> hook.log; kill -TERM $$'"
after = "sh -c 'echo second >> hook.log'"
"#,
    );
    repo.commit("Add pre-merge hooks");

    let output = crate::common::wt_command()
        .current_dir(repo.root_path())
        .args(["hook", "pre-merge", "--yes"])
        .output()
        .expect("run wt hook pre-merge");

    // 128 + SIGTERM (15) = 143
    assert_eq!(
        output.status.code(),
        Some(143),
        "expected exit 143 (SIGTERM); got {:?}\nstderr: {}",
        output.status.code(),
        String::from_utf8_lossy(&output.stderr),
    );

    let hook_log = repo.root_path().join("hook.log");
    let contents = std::fs::read_to_string(&hook_log).unwrap_or_default();
    assert_eq!(
        contents.trim(),
        "first",
        "second hook step ran after the first was killed by signal; got: {contents:?}",
    );
}

// ============================================================================
// User Post-Merge Hook Tests
// ============================================================================

#[rstest]
fn test_user_post_merge_hook_executes(mut repo: TestRepo) {
    // Create feature worktree with a commit
    let feature_wt =
        repo.add_worktree_with_commit("feature", "feature.txt", "feature content", "Add feature");

    // Write user config with post-merge hook
    repo.write_test_config(
        r#"[post-merge]
notify = "echo 'USER_POST_MERGE_RAN' > user_postmerge.txt"
"#,
    );

    snapshot_merge(
        "user_post_merge_executes",
        &repo,
        &["main", "--yes", "--no-remove"],
        Some(&feature_wt),
    );

    // Post-merge runs in the destination (main) worktree (poll for pipeline runner)
    let main_worktree = repo.root_path();
    let marker_file = main_worktree.join("user_postmerge.txt");
    wait_for_file(&marker_file);
}

// ============================================================================
// User Pre-Remove Hook Tests
// ============================================================================

/// Helper for remove snapshots
fn snapshot_remove(test_name: &str, repo: &TestRepo, args: &[&str], cwd: Option<&std::path::Path>) {
    let settings = setup_snapshot_settings(repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(repo, "remove", args, cwd);
        assert_cmd_snapshot!(test_name, cmd);
    });
}

#[rstest]
fn test_user_pre_remove_hook_executes(mut repo: TestRepo) {
    // Create a worktree to remove
    let _feature_wt = repo.add_worktree("feature");

    // Write user config with pre-remove hook
    // Hook writes to parent dir (temp dir) since the worktree itself gets removed
    repo.write_test_config(
        r#"[pre-remove]
cleanup = "echo 'USER_PRE_REMOVE_RAN' > ../user_preremove_marker.txt"
"#,
    );

    snapshot_remove(
        "user_pre_remove_executes",
        &repo,
        &["feature", "--force-delete"],
        Some(repo.root_path()),
    );

    // Verify user hook ran (writes to parent dir since worktree is being removed)
    let marker_file = repo
        .root_path()
        .parent()
        .unwrap()
        .join("user_preremove_marker.txt");
    assert!(marker_file.exists(), "User pre-remove hook should have run");
}

#[rstest]
fn test_user_pre_remove_failure_blocks_removal(mut repo: TestRepo) {
    // Create a worktree to remove
    let feature_wt = repo.add_worktree("feature");

    // Write user config with failing pre-remove hook
    repo.write_test_config(
        r#"[pre-remove]
block = "exit 1"
"#,
    );

    snapshot_remove(
        "user_pre_remove_failure",
        &repo,
        &["feature", "--force-delete"],
        Some(repo.root_path()),
    );

    // Worktree should still exist (removal blocked by failing hook)
    assert!(
        feature_wt.exists(),
        "Worktree should not be removed when pre-remove hook fails"
    );
}

#[rstest]
fn test_user_pre_remove_skipped_with_no_hooks(mut repo: TestRepo) {
    // Create a worktree to remove
    let feature_wt = repo.add_worktree("feature");

    // Write user config with pre-remove hook that would block
    repo.write_test_config(
        r#"[pre-remove]
block = "exit 1"
"#,
    );

    // With --no-hooks, all hooks (including the failing one) should be skipped
    snapshot_remove(
        "user_pre_remove_skipped_no_hooks",
        &repo,
        &["feature", "--force-delete", "--no-hooks"],
        Some(repo.root_path()),
    );

    // Worktree should be removed (hooks skipped)
    // Background removal needs time to complete
    let timeout = Duration::from_secs(5);
    let poll_interval = Duration::from_millis(50);
    let start = std::time::Instant::now();
    while feature_wt.exists() && start.elapsed() < timeout {
        thread::sleep(poll_interval);
    }
    assert!(
        !feature_wt.exists(),
        "Worktree should be removed when --no-hooks skips failing hook"
    );
}

// ============================================================================
// User Post-Remove Hook Tests
// ============================================================================

#[rstest]
fn test_user_post_remove_hook_executes(mut repo: TestRepo) {
    // Create a worktree to remove
    let _feature_wt = repo.add_worktree("feature");

    // Write user config with post-remove hook
    // Hook writes to parent dir (temp dir) since the worktree itself is removed
    repo.write_test_config(
        r#"[post-remove]
cleanup = "echo 'USER_POST_REMOVE_RAN' > ../user_postremove_marker.txt"
"#,
    );

    snapshot_remove(
        "user_post_remove_executes",
        &repo,
        &["feature", "--force-delete"],
        Some(repo.root_path()),
    );

    // Wait for background hook to complete
    let marker_file = repo
        .root_path()
        .parent()
        .unwrap()
        .join("user_postremove_marker.txt");
    crate::common::wait_for_file(&marker_file);
    assert!(
        marker_file.exists(),
        "User post-remove hook should have run"
    );
}

/// Post-remove hooks run at the primary worktree, not cwd. When removing a
/// non-current worktree from a linked worktree, the output should show `@ [path]`
/// pointing to the primary worktree where hooks execute.
#[rstest]
fn test_post_remove_hooks_run_at_primary_worktree(mut repo: TestRepo) {
    let _feature_wt = repo.add_worktree("feature");
    let other_wt = repo.add_worktree("other");

    repo.write_test_config(
        r#"[post-remove]
cleanup = "echo done"
"#,
    );

    // Remove feature from the "other" worktree (not primary)
    snapshot_remove(
        "post_remove_runs_at_primary",
        &repo,
        &["feature", "--force-delete"],
        Some(&other_wt),
    );
}

/// Verify that post-remove hook template variables reference the removed worktree,
/// not the worktree where the hook executes from.
#[rstest]
fn test_user_post_remove_template_vars_reference_removed_worktree(mut repo: TestRepo) {
    // Create a worktree with a unique commit to verify commit capture
    let feature_wt_path =
        repo.add_worktree_with_commit("feature", "feature.txt", "feature content", "Add feature");

    // Get the commit SHA of the feature worktree BEFORE removal
    let feature_commit = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .current_dir(&feature_wt_path)
        .run()
        .unwrap();
    let feature_commit = String::from_utf8_lossy(&feature_commit.stdout);
    let feature_commit = feature_commit.trim();
    let feature_short_commit = &feature_commit[..7];

    // Write user config that captures template variables to a file
    // Hook writes to parent dir (temp dir) since the worktree itself is removed
    repo.write_test_config(
        r#"[post-remove]
capture = "echo 'branch={{ branch }} worktree_path={{ worktree_path }} worktree_name={{ worktree_name }} commit={{ commit }} short_commit={{ short_commit }}' > ../postremove_vars.txt"
"#,
    );

    // Run from main worktree, remove the feature worktree
    repo.wt_command()
        .args(["remove", "feature", "--force-delete", "--yes"])
        .current_dir(repo.root_path())
        .output()
        .unwrap();

    // Wait for background hook to complete
    let vars_file = repo
        .root_path()
        .parent()
        .unwrap()
        .join("postremove_vars.txt");
    crate::common::wait_for_file_content(&vars_file);

    let content = std::fs::read_to_string(&vars_file).unwrap();

    // Verify branch is the removed branch
    assert!(
        content.contains("branch=feature"),
        "branch should be the removed branch 'feature', got: {content}"
    );

    // Extract worktree name for cross-platform comparison.
    // Hooks run in Git Bash on Windows, which converts paths to MSYS2 format
    // (/c/Users/... instead of C:\Users\... or C:/Users/...). Instead of trying
    // to match exact path formats, verify the path ends with the worktree name.
    let feature_wt_name = feature_wt_path
        .file_name()
        .unwrap()
        .to_string_lossy()
        .to_string();

    // Verify worktree_path is the removed worktree's path (not the main worktree)
    // The worktree_path in hook output should end with the worktree directory name
    assert!(
        content.contains(&format!("/{feature_wt_name} "))
            || content.contains(&format!(r"\{feature_wt_name} ")),
        "worktree_path should end with the removed worktree's name '{feature_wt_name}', got: {content}"
    );

    // Verify worktree_name is the removed worktree's directory name
    assert!(
        content.contains(&format!("worktree_name={feature_wt_name}")),
        "worktree_name should be the removed worktree's name '{feature_wt_name}', got: {content}"
    );

    // Verify commit is the removed worktree's commit (not main worktree's commit)
    assert!(
        content.contains(&format!("commit={feature_commit}")),
        "commit should be the removed worktree's commit '{feature_commit}', got: {content}"
    );

    // Verify short_commit is the first 7 chars of the removed worktree's commit
    assert!(
        content.contains(&format!("short_commit={feature_short_commit}")),
        "short_commit should be '{feature_short_commit}', got: {content}"
    );
}

#[rstest]
fn test_user_post_remove_skipped_with_no_hooks(mut repo: TestRepo) {
    // Create a worktree to remove
    let feature_wt = repo.add_worktree("feature");

    // Write user config with post-remove hook that creates a marker
    repo.write_test_config(
        r#"[post-remove]
marker = "echo 'SHOULD_NOT_RUN' > ../no_hooks_postremove.txt"
"#,
    );

    snapshot_remove(
        "user_post_remove_no_hooks",
        &repo,
        &["feature", "--force-delete", "--no-hooks"],
        Some(repo.root_path()),
    );

    // Worktree should be removed
    let timeout = Duration::from_secs(5);
    let poll_interval = Duration::from_millis(50);
    let start = std::time::Instant::now();
    while feature_wt.exists() && start.elapsed() < timeout {
        thread::sleep(poll_interval);
    }
    assert!(
        !feature_wt.exists(),
        "Worktree should be removed with --no-hooks"
    );

    // Post-remove hook should NOT have run
    let marker_file = repo
        .root_path()
        .parent()
        .unwrap()
        .join("no_hooks_postremove.txt");
    thread::sleep(Duration::from_millis(500)); // Wait to ensure hook would have run if enabled
    assert!(
        !marker_file.exists(),
        "Post-remove hook should be skipped when --no-hooks is used"
    );
}

/// Verify that post-remove hooks run during `wt merge` (which removes the worktree).
/// This tests the main production use case for post-remove hooks.
#[rstest]
fn test_user_post_remove_hook_runs_during_merge(mut repo: TestRepo) {
    // Create feature worktree with a commit
    let feature_wt =
        repo.add_worktree_with_commit("feature", "feature.txt", "feature content", "Add feature");

    // Write user config with post-remove hook
    // Hook writes to temp dir (parent of repo) since worktree is removed
    repo.write_test_config(
        r#"[post-remove]
cleanup = "echo 'POST_REMOVE_DURING_MERGE' > ../merge_postremove_marker.txt"
"#,
    );

    // Run merge from feature worktree - this should trigger post-remove hooks
    repo.wt_command()
        .args(["merge", "main", "--yes"])
        .current_dir(&feature_wt)
        .output()
        .unwrap();

    // Wait for background hook to complete
    let marker_file = repo
        .root_path()
        .parent()
        .unwrap()
        .join("merge_postremove_marker.txt");
    crate::common::wait_for_file_content(&marker_file);

    let contents = fs::read_to_string(&marker_file).unwrap();
    assert!(
        contents.contains("POST_REMOVE_DURING_MERGE"),
        "Post-remove hook should run during wt merge with expected content"
    );
}

/// When removing the current worktree (cd back to main), both post-remove and
/// post-switch hooks fire. They should appear on a single combined announcement line.
#[rstest]
fn test_combined_post_remove_and_post_switch_hooks(mut repo: TestRepo) {
    let feature_wt = repo.add_worktree("feature");

    // Configure both post-remove and post-switch user hooks
    repo.write_test_config(
        r#"[post-remove]
cleanup = "echo removed"

[post-switch]
notify = "echo switched"
"#,
    );

    // Remove from inside the feature worktree — triggers cd back to main,
    // which means changed_directory=true and both hook types fire.
    snapshot_remove(
        "combined_post_remove_and_post_switch",
        &repo,
        &["feature", "--force-delete"],
        Some(&feature_wt),
    );
}

// Note: The `return Ok(())` path in spawn_hooks_after_remove when UserConfig::load()
// fails is defensive code for an extremely rare race condition where config becomes
// invalid between command startup and hook execution. This is not easily testable
// without complex timing manipulation.

#[rstest]
fn test_standalone_hook_post_remove_invalid_template(repo: TestRepo) {
    // Write project config with invalid template syntax (unclosed braces)
    repo.write_project_config(r#"post-remove = "echo {{ invalid""#);

    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-remove", "--yes"]);

    let output = cmd.output().unwrap();
    assert!(
        !output.status.success(),
        "wt hook post-remove should fail with invalid template"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("syntax error"),
        "Error should mention template expansion failure, got: {stderr}"
    );
}

#[rstest]
fn test_standalone_hook_post_remove_name_filter_no_match(repo: TestRepo) {
    // Write project config with a named hook
    repo.write_project_config(
        r#"[post-remove]
cleanup = "echo cleanup"
"#,
    );

    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    // Use a name filter that doesn't match any configured hook
    cmd.args(["hook", "post-remove", "nonexistent", "--yes"]);

    let output = cmd.output().unwrap();
    assert!(
        !output.status.success(),
        "wt hook post-remove should fail when name filter doesn't match"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("No hook named") || stderr.contains("nonexistent"),
        "Error should mention the unmatched filter, got: {stderr}"
    );
}

// ============================================================================
// User Pre-Commit Hook Tests
// ============================================================================

#[rstest]
fn test_user_pre_commit_hook_executes(mut repo: TestRepo) {
    // Create feature worktree
    let feature_wt = repo.add_worktree("feature");

    // Add uncommitted changes (triggers pre-commit during merge)
    fs::write(feature_wt.join("uncommitted.txt"), "uncommitted content").unwrap();

    // Write user config with pre-commit hook
    repo.write_test_config(
        r#"[pre-commit]
lint = "echo 'USER_PRE_COMMIT_RAN' > user_precommit.txt"
"#,
    );

    snapshot_merge(
        "user_pre_commit_executes",
        &repo,
        &["main", "--yes", "--no-remove"],
        Some(&feature_wt),
    );

    // Verify user hook ran
    let marker_file = feature_wt.join("user_precommit.txt");
    assert!(marker_file.exists(), "User pre-commit hook should have run");
}

#[rstest]
fn test_user_pre_commit_failure_blocks_commit(mut repo: TestRepo) {
    // Create feature worktree
    let feature_wt = repo.add_worktree("feature");

    // Add uncommitted changes
    fs::write(feature_wt.join("uncommitted.txt"), "uncommitted content").unwrap();

    // Write user config with failing pre-commit hook
    repo.write_test_config(
        r#"[pre-commit]
lint = "exit 1"
"#,
    );

    // Failing pre-commit hook should block the merge
    snapshot_merge(
        "user_pre_commit_failure",
        &repo,
        &["main", "--yes", "--no-remove"],
        Some(&feature_wt),
    );
}

// ============================================================================
// User Post-Commit Hook Tests (Background, via `wt step commit`)
// ============================================================================

/// Helper for step commit snapshots
fn snapshot_step_commit(
    test_name: &str,
    repo: &TestRepo,
    args: &[&str],
    cwd: Option<&std::path::Path>,
) {
    let settings = setup_snapshot_settings(repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(repo, "step", &[], cwd);
        cmd.arg("commit");
        cmd.args(args);
        cmd.env(
            "WORKTRUNK_COMMIT__GENERATION__COMMAND",
            "cat >/dev/null && echo 'feat: test commit'",
        );
        assert_cmd_snapshot!(test_name, cmd);
    });
}

#[rstest]
fn test_user_post_commit_hook_executes(mut repo: TestRepo) {
    // Create feature worktree with staged changes
    let feature_wt = repo.add_worktree("feature");
    fs::write(feature_wt.join("new_file.txt"), "content").unwrap();

    // Write user config with post-commit hook
    repo.write_test_config(
        r#"[post-commit]
notify = "echo 'USER_POST_COMMIT_RAN' > user_postcommit.txt"
"#,
    );

    snapshot_step_commit("user_post_commit_executes", &repo, &[], Some(&feature_wt));

    // Post-commit runs in background in the worktree where the commit happened
    let marker_file = feature_wt.join("user_postcommit.txt");
    wait_for_file_content(&marker_file);

    let contents = fs::read_to_string(&marker_file).unwrap();
    assert!(
        contents.contains("USER_POST_COMMIT_RAN"),
        "User post-commit hook should have run, got: {contents}"
    );
}

#[rstest]
fn test_user_post_commit_skipped_with_no_hooks(mut repo: TestRepo) {
    // Create feature worktree with staged changes
    let feature_wt = repo.add_worktree("feature");
    fs::write(feature_wt.join("new_file.txt"), "content").unwrap();

    // Write user config with post-commit hook
    repo.write_test_config(
        r#"[post-commit]
notify = "echo 'USER_POST_COMMIT_RAN' > user_postcommit.txt"
"#,
    );

    snapshot_step_commit(
        "user_post_commit_skipped_no_hooks",
        &repo,
        &["--no-hooks"],
        Some(&feature_wt),
    );

    // Wait to ensure background hook would have had time to run
    thread::sleep(SLEEP_FOR_ABSENCE_CHECK);

    let marker_file = feature_wt.join("user_postcommit.txt");
    assert!(
        !marker_file.exists(),
        "User post-commit hook should be skipped with --no-hooks"
    );
}

#[rstest]
fn test_user_post_commit_failure_does_not_block_commit(mut repo: TestRepo) {
    // Create feature worktree with staged changes
    let feature_wt = repo.add_worktree("feature");
    fs::write(feature_wt.join("new_file.txt"), "content").unwrap();

    // Write user config with failing post-commit hook
    repo.write_test_config(
        r#"[post-commit]
failing = "exit 1"
"#,
    );

    snapshot_step_commit("user_post_commit_failure", &repo, &[], Some(&feature_wt));

    // The commit should have succeeded despite post-commit hook failure
    // (post-commit runs in background and doesn't affect exit code)
    let output = repo
        .git_command()
        .current_dir(&feature_wt)
        .args(["log", "--oneline", "-1"])
        .run()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("feat: test commit"),
        "Commit should have succeeded despite post-commit hook failure, got: {stdout}"
    );
}

// ============================================================================
// Template Variable Tests
// ============================================================================

#[rstest]
fn test_user_hook_template_variables(repo: TestRepo) {
    // Write user config with hook using template variables
    repo.write_test_config(
        r#"[post-create]
vars = "echo 'repo={{ repo }} branch={{ branch }}' > template_vars.txt"
"#,
    );

    snapshot_switch("user_hook_template_vars", &repo, &["--create", "feature"]);

    // Verify template variables were expanded
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let vars_file = worktree_path.join("template_vars.txt");
    assert!(vars_file.exists());

    let contents = fs::read_to_string(&vars_file).unwrap();
    assert!(
        contents.contains("repo=repo"),
        "Should have expanded repo variable: {}",
        contents
    );
    assert!(
        contents.contains("branch=feature"),
        "Should have expanded branch variable: {}",
        contents
    );
}

#[rstest]
fn test_hook_template_variables_from_subdirectory(repo: TestRepo) {
    // Hook that writes template variables and pwd to files so we can verify their values.
    // This tests that running from a subdirectory still resolves worktree_path to the
    // worktree root (not "." or the subdirectory) and sets hook CWD to the root.
    repo.write_project_config(
        r#"pre-merge = "echo '{{ worktree_path }}' > wt_path.txt && echo '{{ worktree_name }}' > wt_name.txt && pwd > hook_cwd.txt""#,
    );
    repo.commit("Add pre-merge hook");

    // Create a subdirectory and run the hook from there
    let subdir = repo.root_path().join("src").join("components");
    fs::create_dir_all(&subdir).unwrap();

    let output = repo
        .wt_command()
        .args(["hook", "pre-merge", "--yes"])
        .current_dir(&subdir) // override: run from subdirectory
        .output()
        .expect("Failed to run wt hook pre-merge");

    assert!(
        output.status.success(),
        "wt hook pre-merge failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // worktree_path should be the worktree root, not "." or the subdirectory.
    // On Windows, to_posix_path() converts C:\... to /c/..., so check that the path
    // is not relative rather than using is_absolute() (which rejects POSIX-style paths).
    let wt_path = fs::read_to_string(repo.root_path().join("wt_path.txt"))
        .expect("wt_path.txt should exist (hook should run from worktree root, not subdirectory)");
    let wt_path = wt_path.trim();
    assert_ne!(wt_path, ".", "worktree_path should not be relative '.'");
    assert!(
        wt_path.ends_with("repo"),
        "worktree_path should end with repo dir name, got: {wt_path}"
    );

    // worktree_name should be the directory name, not "unknown"
    let wt_name =
        fs::read_to_string(repo.root_path().join("wt_name.txt")).expect("wt_name.txt should exist");
    assert_eq!(
        wt_name.trim(),
        "repo",
        "worktree_name should be the directory name, not 'unknown'"
    );

    // Hook CWD should be the worktree root, not the subdirectory
    let hook_cwd = fs::read_to_string(repo.root_path().join("hook_cwd.txt"))
        .expect("hook_cwd.txt should exist");
    let hook_cwd = hook_cwd.trim();
    assert!(
        !hook_cwd.contains("src/components"),
        "Hook should run from worktree root, not subdirectory. CWD was: {hook_cwd}"
    );
    assert!(
        hook_cwd.ends_with("repo"),
        "Hook CWD should be worktree root, got: {hook_cwd}"
    );
}

// ============================================================================
// Combined User and Project Hooks Tests
// ============================================================================

/// Test that both user and project unnamed hooks of the same type run and get unique log names.
/// This exercises the unnamed index tracking when multiple unnamed hooks share the same hook type.
#[rstest]
fn test_user_and_project_unnamed_post_start(repo: TestRepo) {
    // Create project config with unnamed post-start hook
    repo.write_project_config(r#"post-start = "echo 'PROJECT_POST_START' > project_bg.txt""#);
    repo.commit("Add project config");

    // Write user config with unnamed hook AND pre-approve project command
    repo.write_test_config(
        r#"post-start = "echo 'USER_POST_START' > user_bg.txt"
"#,
    );
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo 'PROJECT_POST_START' > project_bg.txt"]
"#,
    );

    snapshot_switch(
        "user_and_project_unnamed_post_start",
        &repo,
        &["--create", "feature"],
    );

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");

    // Wait for both background commands
    wait_for_file(&worktree_path.join("user_bg.txt"));
    wait_for_file(&worktree_path.join("project_bg.txt"));

    // Both should have run
    assert!(
        worktree_path.join("user_bg.txt").exists(),
        "User post-start should have run"
    );
    assert!(
        worktree_path.join("project_bg.txt").exists(),
        "Project post-start should have run"
    );
}

#[rstest]
fn test_user_and_project_post_start_both_run(repo: TestRepo) {
    // Create project config with post-start hook
    repo.write_project_config(r#"post-start = "echo 'PROJECT_POST_START' > project_bg.txt""#);
    repo.commit("Add project config");

    // Write user config with user hook AND pre-approve project command
    repo.write_test_config(
        r#"[post-start]
bg = "echo 'USER_POST_START' > user_bg.txt"
"#,
    );
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo 'PROJECT_POST_START' > project_bg.txt"]
"#,
    );

    snapshot_switch(
        "user_and_project_post_start",
        &repo,
        &["--create", "feature"],
    );

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");

    // Wait for both background commands
    wait_for_file(&worktree_path.join("user_bg.txt"));
    wait_for_file(&worktree_path.join("project_bg.txt"));

    // Both should have run
    assert!(
        worktree_path.join("user_bg.txt").exists(),
        "User post-start should have run"
    );
    assert!(
        worktree_path.join("project_bg.txt").exists(),
        "Project post-start should have run"
    );
}

// ============================================================================
// Standalone Hook Execution Tests (wt hook <type>)
// ============================================================================

#[rstest]
fn test_standalone_hook_post_create(repo: TestRepo) {
    // Write project config with post-create hook
    repo.write_project_config(r#"post-create = "echo 'STANDALONE_POST_CREATE' > hook_ran.txt""#);

    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-create", "--yes"]);

    let output = cmd.output().unwrap();
    assert!(
        output.status.success(),
        "wt hook post-create should succeed"
    );

    // Hook runs in background — wait for it to write the marker file
    let marker = repo.root_path().join("hook_ran.txt");
    crate::common::wait_for_file_content(&marker);
    let content = fs::read_to_string(&marker).unwrap();
    assert!(content.contains("STANDALONE_POST_CREATE"));
}

#[rstest]
fn test_standalone_hook_pre_start_fails_on_failure(repo: TestRepo) {
    // pre-start hooks use FailFast like all other pre-* hooks — consistent with
    // the symmetric pre (blocking, fail-fast) / post (background, warn) pattern.
    repo.write_project_config(r#"pre-start = "exit 1""#);

    let output = repo
        .wt_command()
        .args(["hook", "pre-start", "--yes"])
        .output()
        .unwrap();

    assert!(
        !output.status.success(),
        "wt hook pre-start should exit non-zero when the hook fails (fail-fast, like all pre-* hooks)"
    );
}

#[rstest]
fn test_standalone_hook_post_start(repo: TestRepo) {
    // Write project config with post-start hook
    repo.write_project_config(r#"post-start = "echo 'STANDALONE_POST_START' > hook_ran.txt""#);

    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-start", "--yes"]);

    let output = cmd.output().unwrap();
    assert!(output.status.success(), "wt hook post-start should succeed");

    // Hook spawns in background - wait for marker file
    let marker = repo.root_path().join("hook_ran.txt");
    wait_for_file_content(&marker);
    let content = fs::read_to_string(&marker).unwrap();
    assert!(content.contains("STANDALONE_POST_START"));
}

#[rstest]
fn test_standalone_hook_post_start_foreground(repo: TestRepo) {
    // Write project config with post-start hook that echoes to both file and stdout
    repo.write_project_config(
        r#"post-start = "echo 'FOREGROUND_POST_START' && echo 'marker' > hook_ran.txt""#,
    );

    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-start", "--yes", "--foreground"]);

    let output = cmd.output().unwrap();
    assert!(
        output.status.success(),
        "wt hook post-start --foreground should succeed"
    );

    // With --foreground, marker file should exist immediately (no waiting)
    let marker = repo.root_path().join("hook_ran.txt");
    assert!(
        marker.exists(),
        "hook should have completed synchronously with --foreground"
    );

    // Output should contain the hook's stdout (not just spawned message)
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("FOREGROUND_POST_START"),
        "hook stdout should appear in command output with --foreground, got: {stderr}"
    );
}

#[rstest]
fn test_standalone_hook_pre_commit(repo: TestRepo) {
    // Write project config with pre-commit hook
    repo.write_project_config(r#"pre-commit = "echo 'STANDALONE_PRE_COMMIT' > hook_ran.txt""#);

    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "pre-commit", "--yes"]);

    let output = cmd.output().unwrap();
    assert!(output.status.success(), "wt hook pre-commit should succeed");

    // Hook should have run
    let marker = repo.root_path().join("hook_ran.txt");
    assert!(marker.exists(), "pre-commit hook should have run");
    let content = fs::read_to_string(&marker).unwrap();
    assert!(content.contains("STANDALONE_PRE_COMMIT"));
}

#[rstest]
fn test_standalone_hook_post_merge(repo: TestRepo) {
    // Write project config with post-merge hook
    repo.write_project_config(r#"post-merge = "echo 'STANDALONE_POST_MERGE' > hook_ran.txt""#);

    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-merge", "--yes"]);

    let output = cmd.output().unwrap();
    assert!(output.status.success(), "wt hook post-merge should succeed");

    // Hook runs in background — wait for it to write the marker file
    let marker = repo.root_path().join("hook_ran.txt");
    crate::common::wait_for_file_content(&marker);
    let content = fs::read_to_string(&marker).unwrap();
    assert!(content.contains("STANDALONE_POST_MERGE"));
}

#[rstest]
fn test_standalone_hook_pre_remove(repo: TestRepo) {
    // Write project config with pre-remove hook
    repo.write_project_config(r#"pre-remove = "echo 'STANDALONE_PRE_REMOVE' > hook_ran.txt""#);

    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "pre-remove", "--yes"]);

    let output = cmd.output().unwrap();
    assert!(output.status.success(), "wt hook pre-remove should succeed");

    // Hook should have run
    let marker = repo.root_path().join("hook_ran.txt");
    assert!(marker.exists(), "pre-remove hook should have run");
    let content = fs::read_to_string(&marker).unwrap();
    assert!(content.contains("STANDALONE_PRE_REMOVE"));
}

#[rstest]
fn test_standalone_hook_post_remove(repo: TestRepo) {
    // Write project config with post-remove hook
    repo.write_project_config(r#"post-remove = "echo 'STANDALONE_POST_REMOVE' > hook_ran.txt""#);

    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-remove", "--yes"]);

    let output = cmd.output().unwrap();
    assert!(
        output.status.success(),
        "wt hook post-remove should succeed (spawns in background)"
    );

    // Wait for background hook to complete and write content
    let marker = repo.root_path().join("hook_ran.txt");
    crate::common::wait_for_file_content(&marker);
    let content = fs::read_to_string(&marker).unwrap();
    assert!(content.contains("STANDALONE_POST_REMOVE"));
}

#[rstest]
fn test_standalone_hook_post_remove_foreground(repo: TestRepo) {
    // Write project config with post-remove hook
    repo.write_project_config(r#"post-remove = "echo 'FOREGROUND_POST_REMOVE' > hook_ran.txt""#);

    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-remove", "--yes", "--foreground"]);

    let output = cmd.output().unwrap();
    assert!(
        output.status.success(),
        "wt hook post-remove --foreground should succeed"
    );

    // Hook runs in foreground, so marker should exist immediately
    let marker = repo.root_path().join("hook_ran.txt");
    assert!(marker.exists(), "post-remove hook should have run");
    let content = fs::read_to_string(&marker).unwrap();
    assert!(content.contains("FOREGROUND_POST_REMOVE"));
}

#[rstest]
fn test_standalone_hook_no_hooks_configured(repo: TestRepo) {
    // No project config, no user config with hooks: `wt hook` should exit 0
    // with a warning — running hooks that don't exist is a no-op, not an error.
    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "pre-start", "--yes"]);

    let output = cmd.output().unwrap();
    assert!(
        output.status.success(),
        "wt hook should exit 0 when no hooks configured, got: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("No pre-start hooks configured"),
        "stderr should warn about missing hooks, got: {stderr}"
    );
}

// ============================================================================
// Dry-Run Tests
// ============================================================================

/// --dry-run shows expanded commands without executing them
#[rstest]
fn test_hook_dry_run_shows_expanded_command(repo: TestRepo) {
    repo.write_project_config(r#"pre-merge = "echo branch={{ branch }}""#);

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

    // No --yes needed: --dry-run skips approval
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "hook",
        &["pre-merge", "--dry-run"],
        Some(repo.root_path()),
    ));
}

/// --dry-run does not execute the hook command
#[rstest]
fn test_hook_dry_run_does_not_execute(repo: TestRepo) {
    repo.write_project_config(r#"post-create = "echo 'SHOULD_NOT_RUN' > hook_ran.txt""#);

    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-create", "--dry-run"]);

    let output = cmd.output().unwrap();
    assert!(output.status.success(), "dry-run should succeed");

    // Hook should NOT have run
    let marker = repo.root_path().join("hook_ran.txt");
    assert!(
        !marker.exists(),
        "dry-run should not execute the hook command"
    );
}

/// --dry-run shows named hooks with source:name labels
#[rstest]
fn test_hook_dry_run_named_hooks(repo: TestRepo) {
    repo.write_project_config(
        r#"pre-merge = [
    {lint = "pre-commit run --all-files"},
    {test = "cargo test"},
]
"#,
    );

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

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "hook",
        &["pre-merge", "--dry-run"],
        Some(repo.root_path()),
    ));
}

// ============================================================================
// Background Hook Execution Tests (post-start, post-switch)
// ============================================================================

#[rstest]
fn test_concurrent_hook_single_failure(repo: TestRepo) {
    // Write project config with a hook that writes output before failing
    repo.write_project_config(r#"post-start = "echo HOOK_OUTPUT_MARKER; exit 1""#);

    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-start", "--yes"]);

    let output = cmd.output().unwrap();
    // Background spawning always succeeds (spawn succeeded, failure is logged)
    assert!(
        output.status.success(),
        "wt hook post-start should succeed (spawns in background)"
    );

    // Wait for log files: runner log + per-command log (cmd-0, unnamed single command)
    let log_dir = resolve_git_common_dir(repo.root_path()).join("wt/logs");
    wait_for_file_count(&log_dir, "log", 2);

    // Hook logs live at `{branch}/project/post-start/{name}.log`.
    let post_start_dir = log_dir
        .join(worktrunk::path::sanitize_for_filename("main"))
        .join("project")
        .join("post-start");
    let cmd_log = fs::read_dir(&post_start_dir)
        .unwrap_or_else(|e| panic!("reading {post_start_dir:?}: {e}"))
        .filter_map(|e| e.ok())
        .find(|e| e.file_name().to_string_lossy().contains("cmd-0"))
        .expect("Should have a cmd-0 log file");

    // Wait for content to be written (command runs async)
    wait_for_file_content(&cmd_log.path());
    let log_content = fs::read_to_string(cmd_log.path()).unwrap();

    // Verify the hook actually ran and wrote output (not just that file was created)
    assert!(
        log_content.contains("HOOK_OUTPUT_MARKER"),
        "Log should contain hook output, got: {log_content}"
    );
}

#[rstest]
fn test_concurrent_hook_multiple_failures(repo: TestRepo) {
    // Write project config with multiple named hooks (table format).
    // Map configs run as a concurrent group in one pipeline runner,
    // each command producing its own log file.
    repo.write_project_config(
        r#"[post-start]
first = "echo FIRST_OUTPUT"
second = "echo SECOND_OUTPUT"
"#,
    );

    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-start", "--yes"]);

    let output = cmd.output().unwrap();
    // Background spawning always succeeds (spawn succeeded)
    assert!(
        output.status.success(),
        "wt hook post-start should succeed (spawns in background)"
    );

    // Wait for per-command log files: runner log + first + second
    let log_dir = resolve_git_common_dir(repo.root_path()).join("wt/logs");
    wait_for_file_count(&log_dir, "log", 3);

    // Hook logs live at `{branch}/project/post-start/{name}.log`.
    let post_start_dir = log_dir
        .join(worktrunk::path::sanitize_for_filename("main"))
        .join("project")
        .join("post-start");
    let log_files: Vec<_> = fs::read_dir(&post_start_dir)
        .unwrap_or_else(|e| panic!("reading {post_start_dir:?}: {e}"))
        .filter_map(|e| e.ok())
        .collect();

    // Verify each command's output is in its own log file
    for (task, expected) in [("first", "FIRST_OUTPUT"), ("second", "SECOND_OUTPUT")] {
        let log_file = log_files
            .iter()
            .find(|e| e.file_name().to_string_lossy().starts_with(task))
            .unwrap_or_else(|| panic!("should have log file for {task}"));

        wait_for_file_content(&log_file.path());
        let content = fs::read_to_string(log_file.path()).unwrap();
        assert!(
            content.contains(expected),
            "Log for {task} should contain {expected}, got: {content}"
        );
    }
}

#[rstest]
fn test_concurrent_hook_user_and_project(repo: TestRepo) {
    // Write user config with post-start hook (using table format for named hook)
    repo.write_test_config(
        r#"[post-start]
user = "echo 'USER_HOOK' > user_hook_ran.txt"
"#,
    );

    // Write project config with post-start hook
    repo.write_project_config(r#"post-start = "echo 'PROJECT_HOOK' > project_hook_ran.txt""#);

    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-start", "--yes"]);

    let output = cmd.output().unwrap();
    assert!(
        output.status.success(),
        "wt hook post-start should succeed, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Both hooks spawn in background - wait for marker files
    let user_marker = repo.root_path().join("user_hook_ran.txt");
    let project_marker = repo.root_path().join("project_hook_ran.txt");

    wait_for_file_content(&user_marker);
    wait_for_file_content(&project_marker);

    let user_content = fs::read_to_string(&user_marker).unwrap();
    let project_content = fs::read_to_string(&project_marker).unwrap();
    assert!(user_content.contains("USER_HOOK"));
    assert!(project_content.contains("PROJECT_HOOK"));
}

#[rstest]
fn test_concurrent_hook_post_switch(repo: TestRepo) {
    // Write project config with post-switch hook
    repo.write_project_config(r#"post-switch = "echo 'POST_SWITCH' > hook_ran.txt""#);

    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-switch", "--yes"]);

    let output = cmd.output().unwrap();
    assert!(
        output.status.success(),
        "wt hook post-switch should succeed"
    );

    // Hook spawns in background - wait for marker file
    let marker = repo.root_path().join("hook_ran.txt");
    wait_for_file_content(&marker);
    let content = fs::read_to_string(&marker).unwrap();
    assert!(content.contains("POST_SWITCH"));
}

#[rstest]
fn test_concurrent_hook_with_name_filter(repo: TestRepo) {
    // Write project config with multiple named hooks
    repo.write_project_config(
        r#"[post-start]
first = "echo 'FIRST' > first.txt"
second = "echo 'SECOND' > second.txt"
"#,
    );

    // Run only the "first" hook by name
    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-start", "--yes", "first"]);

    let output = cmd.output().unwrap();
    assert!(
        output.status.success(),
        "wt hook post-start --name first should succeed, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // First hook spawns in background - wait for marker file
    let first_marker = repo.root_path().join("first.txt");
    let second_marker = repo.root_path().join("second.txt");

    wait_for_file_content(&first_marker);

    // Fixed sleep for absence check - second hook should NOT have run
    thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
    assert!(!second_marker.exists(), "second hook should NOT have run");
}

#[rstest]
fn test_concurrent_hook_invalid_name_filter(repo: TestRepo) {
    // Write project config with named hooks
    repo.write_project_config(
        r#"[post-start]
first = "echo 'FIRST'"
"#,
    );

    // Try to run a non-existent hook by name
    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-start", "--yes", "nonexistent"]);

    let output = cmd.output().unwrap();
    assert!(
        !output.status.success(),
        "wt hook post-start --name nonexistent should fail"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("nonexistent") && stderr.contains("No command named"),
        "Error should mention command not found, got: {stderr}"
    );
    // Should list available commands
    assert!(
        stderr.contains("project:first"),
        "Error should list available commands, got: {stderr}"
    );
}

#[rstest]
fn test_hook_multiple_name_filters(repo: TestRepo) {
    // Write project config with three named hooks
    repo.write_project_config(
        r#"pre-merge = [
    {first = "echo FIRST"},
    {second = "echo SECOND"},
    {third = "echo THIRD"},
]
"#,
    );

    // Run only "first" and "second" by passing multiple names — "third" should not run
    assert_cmd_snapshot!(
        "hook_multiple_name_filters",
        make_snapshot_cmd(
            &repo,
            "hook",
            &["pre-merge", "first", "second", "--yes"],
            None
        )
    );
}

#[rstest]
fn test_hook_multiple_name_filters_none_match(repo: TestRepo) {
    // Write project config with named hooks
    repo.write_project_config(
        r#"[pre-merge]
first = "echo FIRST"
"#,
    );

    // Run with multiple names that don't match any configured hook
    assert_cmd_snapshot!(
        "hook_multiple_name_filters_none_match",
        make_snapshot_cmd(&repo, "hook", &["pre-merge", "foo", "bar", "--yes"], None)
    );
}

// ============================================================================
// Custom Variable (--var) Tests
// ============================================================================

#[rstest]
fn test_var_flag_overrides_template_variable(repo: TestRepo) {
    // Write user config with a hook that uses a template variable
    repo.write_test_config(
        r#"[post-create]
test = "echo '{{ target }}' > target_output.txt"
"#,
    );

    let output = repo
        .wt_command()
        .args([
            "hook",
            "post-create",
            "--yes",
            "--var",
            "target=CUSTOM_TARGET",
        ])
        .output()
        .expect("Failed to run wt hook");

    assert!(output.status.success(), "Hook should succeed");

    let output_file = repo.root_path().join("target_output.txt");
    let contents = fs::read_to_string(&output_file).unwrap();
    assert!(
        contents.contains("CUSTOM_TARGET"),
        "Variable should be overridden in hook, got: {contents}"
    );
}

#[rstest]
fn test_var_flag_multiple_variables(repo: TestRepo) {
    // Write user config with a hook that uses multiple template variables
    repo.write_test_config(
        r#"[post-create]
test = "echo '{{ target }} {{ remote }}' > multi_var_output.txt"
"#,
    );

    let output = repo
        .wt_command()
        .args([
            "hook",
            "post-create",
            "--yes",
            "--var",
            "target=FIRST",
            "--var",
            "remote=SECOND",
        ])
        .output()
        .expect("Failed to run wt hook");

    assert!(output.status.success(), "Hook should succeed");

    let output_file = repo.root_path().join("multi_var_output.txt");
    let contents = fs::read_to_string(&output_file).unwrap();
    assert!(
        contents.contains("FIRST") && contents.contains("SECOND"),
        "Both variables should be overridden, got: {contents}"
    );
}

#[rstest]
fn test_var_flag_overrides_builtin_variable(repo: TestRepo) {
    // Write user config with a hook that uses the builtin branch variable
    repo.write_test_config(
        r#"[post-create]
test = "echo '{{ branch }}' > branch_output.txt"
"#,
    );

    let output = repo
        .wt_command()
        .args([
            "hook",
            "post-create",
            "--yes",
            "--var",
            "branch=CUSTOM_BRANCH_NAME",
        ])
        .output()
        .expect("Failed to run wt hook");

    assert!(output.status.success(), "Hook should succeed");

    let output_file = repo.root_path().join("branch_output.txt");
    let contents = fs::read_to_string(&output_file).unwrap();
    assert!(
        contents.contains("CUSTOM_BRANCH_NAME"),
        "Custom variable should override builtin, got: {contents}"
    );
}

#[rstest]
fn test_var_flag_invalid_format_fails() {
    // Test that invalid KEY=VALUE format is rejected
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_wt"))
        .args(["hook", "post-create", "--var", "no_equals_sign"])
        .output()
        .expect("Failed to run wt");

    assert!(!output.status.success(), "Invalid --var format should fail");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("invalid KEY=VALUE") || stderr.contains("no `=` found"),
        "Error should mention invalid format, got: {stderr}"
    );
}

#[rstest]
fn test_var_flag_custom_variable(repo: TestRepo) {
    // Custom variable names (not built-in template vars) are accepted and
    // injected into the template context, matching alias behavior.
    repo.write_test_config(
        r#"[post-create]
test = "echo '{{ custom_var }}' > custom_var_output.txt"
"#,
    );

    let output = repo
        .wt_command()
        .args(["hook", "post-create", "--yes", "--var", "custom_var=hello"])
        .output()
        .expect("Failed to run wt hook");

    assert!(
        output.status.success(),
        "Custom variable should succeed, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let output_file = repo.root_path().join("custom_var_output.txt");
    let contents = fs::read_to_string(&output_file).unwrap();
    assert!(
        contents.contains("hello"),
        "Custom variable should be expanded, got: {contents}"
    );
}

#[rstest]
fn test_var_flag_last_value_wins(repo: TestRepo) {
    // Test that when the same variable is specified multiple times, the last value wins
    repo.write_test_config(
        r#"[post-create]
test = "echo '{{ target }}' > target_output.txt"
"#,
    );

    let output = repo
        .wt_command()
        .args([
            "hook",
            "post-create",
            "--yes",
            "--var",
            "target=FIRST",
            "--var",
            "target=SECOND",
        ])
        .output()
        .expect("Failed to run wt hook");

    assert!(output.status.success());

    let output_file = repo.root_path().join("target_output.txt");
    let contents = std::fs::read_to_string(&output_file).expect("Should have created output file");
    assert!(
        contents.contains("SECOND"),
        "Last --var value should win, got: {contents}"
    );
}

#[rstest]
fn test_var_shorthand_overrides_template_variable(repo: TestRepo) {
    // `--KEY=VALUE` is equivalent to `--var KEY=VALUE` for template variables.
    repo.write_test_config(
        r#"[post-create]
test = "echo '{{ branch }}' > shorthand_output.txt"
"#,
    );

    let output = repo
        .wt_command()
        .args(["hook", "post-create", "--yes", "--branch=SHORTHAND_BRANCH"])
        .output()
        .expect("Failed to run wt hook");

    assert!(
        output.status.success(),
        "Hook should succeed, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let output_file = repo.root_path().join("shorthand_output.txt");
    let contents = fs::read_to_string(&output_file).unwrap();
    assert!(
        contents.contains("SHORTHAND_BRANCH"),
        "Shorthand should override template variable, got: {contents}"
    );
}

#[rstest]
fn test_var_shorthand_mixed_with_long_form(repo: TestRepo) {
    // Shorthand and `--var` forms coexist in the same invocation.
    repo.write_test_config(
        r#"[post-create]
test = "echo '{{ branch }} {{ target }}' > mixed_output.txt"
"#,
    );

    let output = repo
        .wt_command()
        .args([
            "hook",
            "post-create",
            "--yes",
            "--branch=SHORT",
            "--var",
            "target=LONG",
        ])
        .output()
        .expect("Failed to run wt hook");

    assert!(output.status.success());

    let output_file = repo.root_path().join("mixed_output.txt");
    let contents = fs::read_to_string(&output_file).unwrap();
    assert!(
        contents.contains("SHORT") && contents.contains("LONG"),
        "Both forms should coexist, got: {contents}"
    );
}

#[rstest]
fn test_var_shorthand_custom_variable(repo: TestRepo) {
    // Custom variable names (not built-in template vars) are accepted and
    // injected into the template context, matching alias behavior. Hyphens in
    // variable names are canonicalized to underscores.
    repo.write_test_config(
        r#"[post-create]
test = "echo '{{ my_env }}' > custom_output.txt"
"#,
    );

    let output = repo
        .wt_command()
        .args(["hook", "post-create", "--yes", "--my-env=staging"])
        .output()
        .expect("Failed to run wt hook");

    assert!(
        output.status.success(),
        "Custom variable should succeed, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let output_file = repo.root_path().join("custom_output.txt");
    let contents = fs::read_to_string(&output_file).unwrap();
    assert!(
        contents.contains("staging"),
        "Custom variable with hyphens should be canonicalized and expanded, got: {contents}"
    );
}

#[rstest]
fn test_var_unreferenced_warning(repo: TestRepo) {
    // A --var whose key isn't referenced by any hook template should produce a
    // warning — catches typos that would otherwise silently have no effect.
    // The hook still runs.
    repo.write_test_config(
        r#"[post-create]
test = "echo '{{ branch }}' > unref_output.txt"
"#,
    );

    let output = repo
        .wt_command()
        .args(["hook", "post-create", "--yes", "--unused_var=value"])
        .output()
        .expect("Failed to run wt hook");

    assert!(
        output.status.success(),
        "Hook should still run despite the warning, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("unused_var") && stderr.contains("not referenced"),
        "Expected unreferenced-var warning, got: {stderr}"
    );
}

#[rstest]
fn test_var_unreferenced_warning_respects_name_filter(repo: TestRepo) {
    // When a name filter excludes the hook that uses the var, still warn —
    // the filtered-out hook won't run, so the var has no effect.
    repo.write_test_config(
        r#"[post-create]
alpha = "echo '{{ branch }}' > alpha.txt"
beta = "echo '{{ my_env }}' > beta.txt"
"#,
    );

    let output = repo
        .wt_command()
        .args(["hook", "post-create", "--yes", "alpha", "--my-env=staging"])
        .output()
        .expect("Failed to run wt hook");

    assert!(output.status.success());

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("my_env") && stderr.contains("not referenced"),
        "Expected warning for --my-env when only 'alpha' runs, got: {stderr}"
    );
}

#[rstest]
fn test_var_referenced_no_warning(repo: TestRepo) {
    // A --var that IS referenced by a template produces no warning.
    repo.write_test_config(
        r#"[post-create]
test = "echo '{{ my_env }}' > ref_output.txt"
"#,
    );

    let output = repo
        .wt_command()
        .args(["hook", "post-create", "--yes", "--my-env=staging"])
        .output()
        .expect("Failed to run wt hook");

    assert!(output.status.success());

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("not referenced"),
        "Expected no warning, got: {stderr}"
    );
}

#[test]
fn test_var_shorthand_does_not_leak_into_hook_show() {
    // `wt hook show` doesn't accept `--var`, so shorthand preprocessing must
    // leave its argv alone — an unknown flag should still produce clap's
    // "unexpected argument" error, not a template-variable error.
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_wt"))
        .args(["hook", "show", "--branch=feature"])
        .output()
        .expect("Failed to run wt");

    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("unexpected argument") || stderr.contains("--branch"),
        "Expected clap to reject --branch on `hook show`, got: {stderr}"
    );
}

#[rstest]
fn test_var_flag_deprecated_alias_works(repo: TestRepo) {
    // Test that deprecated variable aliases (main_worktree, repo_root, worktree) can be overridden
    repo.write_test_config(
        r#"[post-create]
test = "echo '{{ main_worktree }}' > alias_output.txt"
"#,
    );

    let output = repo
        .wt_command()
        .args([
            "hook",
            "post-create",
            "--yes",
            "--var",
            "main_worktree=/custom/path",
        ])
        .output()
        .expect("Failed to run wt hook");

    assert!(output.status.success());

    let output_file = repo.root_path().join("alias_output.txt");
    let contents = std::fs::read_to_string(&output_file).expect("Should have created output file");
    assert!(
        contents.contains("/custom/path"),
        "Deprecated alias should be overridden, got: {contents}"
    );
}

// ============================================================================
// Hook Order Preservation Tests (Issue #737)
// ============================================================================

/// Test that user hooks execute in TOML insertion order, not alphabetical
/// See: https://github.com/max-sixty/worktrunk/issues/737
#[rstest]
fn test_user_hooks_preserve_toml_order(repo: TestRepo) {
    // Write user config with hooks in specific order (NOT alphabetical: vscode, claude, copy, submodule)
    // If order were alphabetical, it would be: claude, copy, submodule, vscode
    repo.write_test_config(
        r#"[post-create]
vscode = "echo '1' >> hook_order.txt"
claude = "echo '2' >> hook_order.txt"
copy = "echo '3' >> hook_order.txt"
submodule = "echo '4' >> hook_order.txt"
"#,
    );

    snapshot_switch("user_hooks_preserve_order", &repo, &["--create", "feature"]);

    // Verify execution order by reading the output file
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let order_file = worktree_path.join("hook_order.txt");
    assert!(order_file.exists(), "hook_order.txt should be created");

    let contents = fs::read_to_string(&order_file).unwrap();
    let lines: Vec<&str> = contents.lines().collect();

    // Hooks should execute in TOML order: 1, 2, 3, 4
    assert_eq!(
        lines,
        vec!["1", "2", "3", "4"],
        "Hooks should execute in TOML insertion order (vscode, claude, copy, submodule)"
    );
}

// ============================================================================
// User Pre-Switch Hook Tests
// ============================================================================

/// Test that a pre-switch hook executes before switching to an existing worktree
#[rstest]
fn test_user_pre_switch_hook_executes(mut repo: TestRepo) {
    // Create a worktree to switch to
    let _feature_wt = repo.add_worktree("feature");

    // Write user config with pre-switch hook that creates a marker in the current worktree
    repo.write_test_config(
        r#"[pre-switch]
check = "echo 'USER_PRE_SWITCH_RAN' > pre_switch_marker.txt"
"#,
    );

    snapshot_switch("user_pre_switch_executes", &repo, &["feature"]);

    // Verify user hook ran in the source worktree (main), not the destination
    let marker_file = repo.root_path().join("pre_switch_marker.txt");
    assert!(
        marker_file.exists(),
        "User pre-switch hook should have created marker in source worktree"
    );

    let contents = fs::read_to_string(&marker_file).unwrap();
    assert!(
        contents.contains("USER_PRE_SWITCH_RAN"),
        "Marker file should contain expected content"
    );
}

/// Test that a failing pre-switch hook blocks the switch (including --create)
#[rstest]
fn test_user_pre_switch_failure_blocks_switch(repo: TestRepo) {
    // Write user config with failing pre-switch hook
    repo.write_test_config(
        r#"[pre-switch]
block = "exit 1"
"#,
    );

    // Failing pre-switch should prevent worktree creation
    snapshot_switch("user_pre_switch_failure", &repo, &["--create", "feature"]);

    // Worktree should NOT have been created
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    assert!(
        !worktree_path.exists(),
        "Worktree should not be created when pre-switch hook fails"
    );
}

/// Test that --no-hooks skips the pre-switch hook
#[rstest]
fn test_user_pre_switch_skipped_with_no_hooks(repo: TestRepo) {
    // Write user config with pre-switch hook that creates a marker
    repo.write_test_config(
        r#"[pre-switch]
check = "echo 'SHOULD_NOT_RUN' > pre_switch_marker.txt"
"#,
    );

    snapshot_switch(
        "user_pre_switch_no_hooks",
        &repo,
        &["--create", "feature", "--no-hooks"],
    );

    // Pre-switch hook should NOT have run (--no-hooks skips all hooks)
    let marker_file = repo.root_path().join("pre_switch_marker.txt");
    assert!(
        !marker_file.exists(),
        "Pre-switch hook should be skipped with --no-hooks"
    );
}

/// Test that `wt hook pre-switch` runs pre-switch hooks manually
#[rstest]
fn test_user_pre_switch_manual_hook(repo: TestRepo) {
    repo.write_test_config(
        r#"[pre-switch]
check = "echo 'MANUAL_PRE_SWITCH' > pre_switch_marker.txt"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "hook", &["pre-switch"], None);
        assert_cmd_snapshot!("user_pre_switch_manual", cmd);
    });

    let marker_file = repo.root_path().join("pre_switch_marker.txt");
    assert!(
        marker_file.exists(),
        "Manual pre-switch hook should have created marker"
    );
}

/// Test that `{{ branch }}` in pre-switch hooks is the destination branch argument, not the source.
#[rstest]
fn test_user_pre_switch_branch_var_is_destination(mut repo: TestRepo) {
    let _feature_wt = repo.add_worktree("feature-dest");

    // Write pre-switch hook that records {{ branch }} into a marker file
    repo.write_test_config(
        r#"[pre-switch]
check = "echo '{{ branch }}' > pre_switch_branch.txt"
"#,
    );

    snapshot_switch(
        "user_pre_switch_branch_destination",
        &repo,
        &["feature-dest"],
    );

    // {{ branch }} should be the destination branch, not the source (main)
    let marker_file = repo.root_path().join("pre_switch_branch.txt");
    assert!(
        marker_file.exists(),
        "Pre-switch hook should have created marker"
    );
    let contents = fs::read_to_string(&marker_file).unwrap();
    assert_eq!(
        contents.trim(),
        "feature-dest",
        "{{{{ branch }}}} should be the destination branch 'feature-dest', got: '{}'",
        contents.trim(),
    );
}

/// When removing the current worktree, post-switch hooks should fire
/// because the user is implicitly switched back to the primary worktree.
/// Regression test for https://github.com/max-sixty/worktrunk/issues/1450
///
/// Config is committed before creating the worktree, so both worktrees
/// have .config/wt.toml — isolating the bug to the deleted-cwd problem.
#[rstest]
fn test_remove_current_worktree_fires_post_switch_hook(mut repo: TestRepo) {
    // Write and commit project config BEFORE creating the worktree,
    // so the feature worktree also has .config/wt.toml
    repo.write_project_config(
        r#"post-switch = "echo 'POST_SWITCH_AFTER_REMOVE' > post_switch_marker.txt""#,
    );
    repo.commit("Add project config with post-switch hook");

    let feature_path = repo.add_worktree("feature");

    // Remove from WITHIN the feature worktree (current worktree removal)
    repo.wt_command()
        .args(["remove", "feature", "--force-delete", "--yes"])
        .current_dir(&feature_path)
        .output()
        .unwrap();

    // Post-switch hook should fire in the primary worktree
    let marker = repo.root_path().join("post_switch_marker.txt");
    wait_for_file_content(&marker);
    let content = fs::read_to_string(&marker).unwrap();
    assert!(
        content.contains("POST_SWITCH_AFTER_REMOVE"),
        "Post-switch hook should run when removing current worktree, got: {content}"
    );
}

// ==========================================================================
// Active model: directional template variables
// ==========================================================================

/// Pre-switch to existing worktree: worktree_path = destination (Active),
/// base_worktree_path = source, cwd = source.
#[rstest]
fn test_pre_switch_vars_point_to_destination(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");

    // Hook captures worktree_path, base_worktree_path, and cwd
    repo.write_test_config(
        r#"[pre-switch]
capture = "echo 'wt_path={{ worktree_path }} base={{ base }} base_wt={{ base_worktree_path }} cwd={{ cwd }}' > pre_switch_vars.txt"
"#,
    );

    repo.wt_command()
        .args(["switch", "feature", "--yes"])
        .current_dir(repo.root_path())
        .output()
        .unwrap();

    let vars_file = repo.root_path().join("pre_switch_vars.txt");
    let content = fs::read_to_string(&vars_file).unwrap();

    let feature_name = feature_path.file_name().unwrap().to_string_lossy();
    let main_name = repo
        .root_path()
        .file_name()
        .unwrap()
        .to_string_lossy()
        .to_string();

    // worktree_path should be the destination (Active)
    assert!(
        content.contains(&format!("/{feature_name} "))
            || content.contains(&format!(r"\{feature_name} ")),
        "worktree_path should point to destination '{feature_name}', got: {content}"
    );

    // base should be the source branch
    assert!(
        content.contains("base=main"),
        "base should be source branch 'main', got: {content}"
    );

    // cwd should be the source (where the hook actually runs)
    assert!(
        content.contains(&format!("/{main_name}")) || content.contains(&format!(r"\{main_name}")),
        "cwd should point to source worktree '{main_name}', got: {content}"
    );
}

/// Post-remove: target/target_worktree_path point to where user ends up.
#[rstest]
fn test_post_remove_has_target_vars(mut repo: TestRepo) {
    repo.add_worktree("feature");

    repo.write_test_config(
        r#"[post-remove]
capture = "echo 'branch={{ branch }} target={{ target }} target_wt={{ target_worktree_path }}' > ../postremove_target.txt"
"#,
    );

    repo.wt_command()
        .args(["remove", "feature", "--force-delete", "--yes"])
        .current_dir(repo.root_path())
        .output()
        .unwrap();

    let vars_file = repo
        .root_path()
        .parent()
        .unwrap()
        .join("postremove_target.txt");
    crate::common::wait_for_file_content(&vars_file);

    let content = fs::read_to_string(&vars_file).unwrap();

    // branch should be the removed branch (Active)
    assert!(
        content.contains("branch=feature"),
        "branch should be removed branch 'feature', got: {content}"
    );

    // target should be the destination branch (where user ends up)
    assert!(
        content.contains("target=main"),
        "target should be destination 'main', got: {content}"
    );

    // target_worktree_path should be the primary worktree
    let main_name = repo
        .root_path()
        .file_name()
        .unwrap()
        .to_string_lossy()
        .to_string();
    assert!(
        content.contains(&main_name),
        "target_worktree_path should contain primary worktree name '{main_name}', got: {content}"
    );
}

/// Post-switch for existing switches: base vars reference the source worktree.
#[rstest]
fn test_post_switch_has_base_vars_for_existing(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");

    // Post-switch hooks run in the DESTINATION worktree (feature), so write
    // to a path relative to the worktree that will exist after switch.
    repo.write_test_config(
        r#"[post-switch]
capture = "echo 'branch={{ branch }} base={{ base }}' > post_switch_base.txt"
"#,
    );

    repo.wt_command()
        .args(["switch", "feature", "--yes"])
        .current_dir(repo.root_path())
        .output()
        .unwrap();

    // File is written in the destination (feature) worktree
    let vars_file = feature_path.join("post_switch_base.txt");
    crate::common::wait_for_file_content(&vars_file);

    let content = fs::read_to_string(&vars_file).unwrap();

    // branch should be the destination (Active)
    assert!(
        content.contains("branch=feature"),
        "branch should be destination 'feature', got: {content}"
    );

    // base should be the source branch we switched from
    assert!(
        content.contains("base=main"),
        "base should be source 'main', got: {content}"
    );
}

/// cwd always exists on disk — even when worktree_path points to a deleted directory.
#[rstest]
fn test_cwd_always_exists_in_post_remove(mut repo: TestRepo) {
    repo.add_worktree("feature");

    repo.write_test_config(
        r#"[post-remove]
check = "test -d {{ cwd }} && echo 'cwd_exists=true' > ../cwd_check.txt || echo 'cwd_exists=false' > ../cwd_check.txt"
"#,
    );

    repo.wt_command()
        .args(["remove", "feature", "--force-delete", "--yes"])
        .current_dir(repo.root_path())
        .output()
        .unwrap();

    let check_file = repo.root_path().parent().unwrap().join("cwd_check.txt");
    crate::common::wait_for_file_content(&check_file);

    let content = fs::read_to_string(&check_file).unwrap();
    assert!(
        content.contains("cwd_exists=true"),
        "cwd should point to an existing directory, got: {content}"
    );
}

// ============================================================================
// Pipeline Tests (list form)
// ============================================================================

#[rstest]
fn test_user_post_start_pipeline_serial_ordering(repo: TestRepo) {
    // Pipeline: serial step creates a marker, concurrent step reads it.
    // Serial steps run in order, so the marker exists when the
    // concurrent step runs.
    repo.write_test_config(
        r#"post-start = [
    "echo SETUP_DONE > pipeline_marker.txt",
    { bg = "cat pipeline_marker.txt > bg_saw_marker.txt" }
]
"#,
    );

    snapshot_switch(
        "user_post_start_pipeline_ordering",
        &repo,
        &["--create", "feature"],
    );

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let bg_file = worktree_path.join("bg_saw_marker.txt");
    wait_for_file_content(&bg_file);

    let content = fs::read_to_string(&bg_file).unwrap();
    assert!(
        content.contains("SETUP_DONE"),
        "Concurrent step should see serial step's output, got: {content}"
    );
}

#[rstest]
fn test_user_post_start_pipeline_failure_skips_later_steps(repo: TestRepo) {
    // First step fails → second step should not run (pipeline aborts on failure).
    repo.write_test_config(
        r#"post-start = [
    "exit 1",
    { bg = "echo SHOULD_NOT_RUN > should_not_exist.txt" }
]
"#,
    );

    snapshot_switch(
        "user_post_start_pipeline_failure",
        &repo,
        &["--create", "feature"],
    );

    // Give background commands time to run (if they were going to)
    thread::sleep(SLEEP_FOR_ABSENCE_CHECK);

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let marker_file = worktree_path.join("should_not_exist.txt");
    assert!(
        !marker_file.exists(),
        "Later pipeline steps should NOT run after serial step failure"
    );
}

#[rstest]
fn test_user_post_start_pipeline_lazy_vars_foreground(repo: TestRepo) {
    // Pipeline step 1 sets a var, step 2 uses it via {{ vars.name }}.
    // Foreground mode exercises the in-process lazy re-expansion path
    // in run_hook_with_filter.
    repo.write_test_config(
        r#"post-start = [
    "git config worktrunk.state.main.vars.name '{{ branch | sanitize }}-postgres'",
    { db = "echo {{ vars.name }} > lazy_expanded.txt" }
]
"#,
    );

    // Run the hook in foreground on the main worktree.
    // Step 1 uses `git config` directly (avoids needing `wt` on PATH in CI).
    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-start", "--yes", "--foreground"]);

    let output = cmd.output().expect("Failed to run foreground hook");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "Foreground hook should succeed.\nstdout: {}\nstderr: {stderr}",
        String::from_utf8_lossy(&output.stdout),
    );

    // With foreground, marker file should exist immediately
    let marker_file = repo.root_path().join("lazy_expanded.txt");
    assert!(
        marker_file.exists(),
        "Foreground lazy expansion should create marker file"
    );

    let content = fs::read_to_string(&marker_file).unwrap().trim().to_string();
    assert_eq!(
        content, "main-postgres",
        "Lazy step should see var set by prior step"
    );
}

#[rstest]
fn test_user_post_start_pipeline_lazy_vars_background(repo: TestRepo) {
    // Pipeline step 1 sets a var via git config (not `wt config` — bare `wt`
    // isn't on PATH in the detached background process). Step 2 references
    // {{ vars.name }}, which is expanded just-in-time by the background
    // pipeline runner reading fresh vars from git config.
    repo.write_test_config(
        r#"post-start = [
    "git config worktrunk.state.{{ branch }}.vars.name '{{ branch | sanitize }}-postgres'",
    { db = "echo {{ vars.name }} > lazy_bg_expanded.txt" }
]
"#,
    );

    snapshot_switch(
        "user_post_start_pipeline_lazy_vars_bg",
        &repo,
        &["--create", "feature"],
    );

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let marker_file = worktree_path.join("lazy_bg_expanded.txt");
    wait_for_file_content(&marker_file);

    let content = fs::read_to_string(&marker_file).unwrap().trim().to_string();
    assert_eq!(
        content, "feature-postgres",
        "Background lazy step should see var set by prior step"
    );
}

#[rstest]
fn test_user_post_start_pipeline_concurrent_all_run(repo: TestRepo) {
    // Concurrent group: both commands should run and produce output.
    repo.write_test_config(
        r#"post-start = [
    { a = "echo AAA > concurrent_a.txt", b = "echo BBB > concurrent_b.txt" }
]
"#,
    );

    snapshot_switch(
        "user_post_start_pipeline_concurrent_all",
        &repo,
        &["--create", "feature"],
    );

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let file_a = worktree_path.join("concurrent_a.txt");
    let file_b = worktree_path.join("concurrent_b.txt");
    wait_for_file_content(&file_a);
    wait_for_file_content(&file_b);

    let a = fs::read_to_string(&file_a).unwrap();
    let b = fs::read_to_string(&file_b).unwrap();
    assert!(
        a.contains("AAA"),
        "concurrent command 'a' should run, got: {a}"
    );
    assert!(
        b.contains("BBB"),
        "concurrent command 'b' should run, got: {b}"
    );
}

#[rstest]
fn test_user_post_start_pipeline_concurrent_partial_failure(repo: TestRepo) {
    // One command in a concurrent group fails. The other should still
    // complete (pipeline waits for all children), and later steps should
    // not run (group reported as failed).
    repo.write_test_config(
        r#"post-start = [
    { fail = "exit 1", ok = "echo SURVIVED > concurrent_survivor.txt" },
    "echo SHOULD_NOT_RUN > after_concurrent.txt"
]
"#,
    );

    snapshot_switch(
        "user_post_start_pipeline_concurrent_failure",
        &repo,
        &["--create", "feature"],
    );

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");

    // The surviving command should complete despite the sibling failing.
    let survivor = worktree_path.join("concurrent_survivor.txt");
    wait_for_file_content(&survivor);
    let content = fs::read_to_string(&survivor).unwrap();
    assert!(
        content.contains("SURVIVED"),
        "Non-failing concurrent command should still complete, got: {content}"
    );

    // The step after the failed group should NOT run.
    thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
    let after = worktree_path.join("after_concurrent.txt");
    assert!(
        !after.exists(),
        "Steps after a failed concurrent group should not run"
    );
}

#[rstest]
fn test_user_post_start_pipeline_shell_escaping(repo: TestRepo) {
    // Template values containing shell metacharacters must be safely
    // escaped. Step 1 sets a var with spaces, quotes, and a dollar sign.
    // Step 2 expands it into a shell command — without shell_escape=true,
    // the value would be word-split or trigger expansion.
    repo.write_test_config(
        r#"post-start = [
    "git config worktrunk.state.{{ branch }}.vars.tricky 'hello world $HOME \"quotes\"'",
    { check = "echo {{ vars.tricky }} > escaped_output.txt" }
]
"#,
    );

    // Use foreground so we can check the result immediately.
    let mut cmd = crate::common::wt_command();
    cmd.current_dir(repo.root_path());
    cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
    cmd.args(["hook", "post-start", "--yes", "--foreground"]);

    let output = cmd.output().expect("Failed to run foreground hook");
    assert!(
        output.status.success(),
        "Hook should succeed.\nstderr: {}",
        String::from_utf8_lossy(&output.stderr),
    );

    let marker_file = repo.root_path().join("escaped_output.txt");
    assert!(marker_file.exists(), "Escaped output file should exist");

    let content = fs::read_to_string(&marker_file).unwrap().trim().to_string();
    // The value should arrive intact — not word-split, not $HOME-expanded.
    assert!(
        content.contains("hello world"),
        "Spaces should not cause word splitting, got: {content}"
    );
    assert!(
        content.contains("$HOME"),
        "$HOME should be literal, not expanded, got: {content}"
    );
    assert!(
        content.contains("\"quotes\""),
        "Quotes should survive escaping, got: {content}"
    );
}

// ============================================================================
// Pipeline hook_name isolation (Bug 2 regression test)
// ============================================================================

#[rstest]
fn test_user_post_start_pipeline_hook_name_per_step(repo: TestRepo) {
    // Each step in a pipeline should see its own hook_name, not the first step's name.
    // Before the fix, step 2 would see step 1's hook_name because the shared pipeline
    // context included hook_name from the first command's context_json.
    repo.write_test_config(
        r#"post-start = [
    { step_one = "echo {{ hook_name }} > step_one_name.txt" },
    { step_two = "echo {{ hook_name }} > step_two_name.txt" }
]
"#,
    );

    snapshot_switch(
        "user_post_start_pipeline_hook_name_per_step",
        &repo,
        &["--create", "feature"],
    );

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");

    let step_one_file = worktree_path.join("step_one_name.txt");
    let step_two_file = worktree_path.join("step_two_name.txt");
    wait_for_file_content(&step_one_file);
    wait_for_file_content(&step_two_file);

    let step_one_name = fs::read_to_string(&step_one_file)
        .unwrap()
        .trim()
        .to_string();
    let step_two_name = fs::read_to_string(&step_two_file)
        .unwrap()
        .trim()
        .to_string();
    assert_eq!(
        step_one_name, "step_one",
        "Step 1 should see its own hook_name"
    );
    assert_eq!(
        step_two_name, "step_two",
        "Step 2 should see its own hook_name, not step 1's"
    );
}

#[rstest]
fn test_user_post_switch_pipeline_via_switch_create(repo: TestRepo) {
    // Post-switch with pipeline config, triggered by `wt switch --create`.
    // This exercises the pipeline branch in `spawn_switch_background_hooks`,
    // which spawns each hook type's pipeline independently.
    repo.write_test_config(
        r#"post-switch = [
    "echo SWITCH_STEP_1 > switch_step1.txt",
    { check = "cat switch_step1.txt > switch_step2.txt" }
]
"#,
    );

    snapshot_switch(
        "user_post_switch_pipeline_via_create",
        &repo,
        &["--create", "feature"],
    );

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let step2_file = worktree_path.join("switch_step2.txt");
    wait_for_file_content(&step2_file);

    let content = fs::read_to_string(&step2_file).unwrap();
    assert!(
        content.contains("SWITCH_STEP_1"),
        "Pipeline serial ordering should be preserved for post-switch, got: {content}"
    );
}

// ============================================================================
// Post-remove pipeline (Bug 1 regression test)
// ============================================================================

#[rstest]
fn test_user_post_remove_pipeline_serial_ordering(mut repo: TestRepo) {
    // Post-remove with a pipeline config should preserve serial ordering.
    // Before the fix, prepare_post_remove_commands returned flat commands,
    // so pipeline configs lost serial/concurrent semantics.
    let _feature_wt = repo.add_worktree("feature");

    repo.write_test_config(
        r#"post-remove = [
    "echo REMOVE_STEP_1 > ../remove_step1.txt",
    "cat ../remove_step1.txt > ../remove_step2.txt"
]
"#,
    );

    snapshot_remove(
        "user_post_remove_pipeline_ordering",
        &repo,
        &["feature", "--force-delete"],
        Some(repo.root_path()),
    );

    // Step 2 reads step 1's output. With pipeline semantics, step 2 runs after step 1.
    let parent = repo.root_path().parent().unwrap();
    let step2_file = parent.join("remove_step2.txt");
    wait_for_file_content(&step2_file);

    let content = fs::read_to_string(&step2_file).unwrap();
    assert!(
        content.contains("REMOVE_STEP_1"),
        "Step 2 should see step 1's output (serial pipeline), got: {content}"
    );
}

// ============================================================================
// Name-filtered lazy template (Bug 3 regression test)
// ============================================================================

#[rstest]
fn test_standalone_hook_name_filtered_lazy_template(repo: TestRepo) {
    // A pipeline step that uses {{ vars.X }} should expand correctly when
    // name-filtered via `wt hook post-start db`. Before the fix, the flat
    // spawn path passed the raw unexpanded template to the shell.
    //
    // vars.* are read from git config, so we pre-set the value.
    repo.write_test_config(
        r#"post-start = [
    { setup = "echo setup" },
    { db = "echo {{ vars.name }} > lazy_filtered.txt" }
]
"#,
    );

    // Pre-set vars.name via git config (same mechanism as pipeline step 1 would use).
    // Test repo starts on main branch.
    repo.run_git(&["config", "worktrunk.state.main.vars.name", "test-db"]);

    // Run just the 'db' step by name. This goes through the flat background path
    // since name filtering bypasses the pipeline runner.
    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "hook", &["post-start", "db"], None);
        assert_cmd_snapshot!("standalone_hook_name_filtered_lazy_template", cmd);
    });

    let marker_file = repo.root_path().join("lazy_filtered.txt");
    wait_for_file_content(&marker_file);

    let content = fs::read_to_string(&marker_file).unwrap().trim().to_string();
    assert_eq!(
        content, "test-db",
        "Lazy template should expand {{ vars.name }} from git config"
    );
}

/// Multi-remove hook announcements include the branch name for disambiguation
#[rstest]
fn test_multi_remove_hook_announcements_include_branch(repo: TestRepo) {
    // fixture already has feature-a, feature-b, feature-c worktrees
    repo.write_test_config(
        r#"[post-remove]
cleanup = "echo done"
"#,
    );

    snapshot_remove(
        "multi_remove_hook_branch_context",
        &repo,
        &["feature-a", "feature-b", "--force-delete"],
        Some(repo.root_path()),
    );
}

/// Foreground hooks pass the directive file through to child processes,
/// so inner `wt switch --create` can write cd directives back to the
/// parent shell via the CD directive file.
#[rstest]
fn test_foreground_hook_passes_directive_file(repo: TestRepo) {
    use crate::common::{configure_directive_files, directive_files, wt_bin};

    repo.commit("initial");

    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}"
    );
    let wt_toml = wt_str.replace('\\', r"\\");

    // Pre-start hook that creates a new worktree via `wt switch --create`.
    // If the CD directive file is passed through, the inner wt will write a
    // path to it. If scrubbed, it prints the "shell integration not
    // installed" hint instead.
    repo.write_test_config(&format!(
        r#"
[pre-start]
setup = "'{wt_toml}' switch --create hook-created --no-hooks"
"#,
    ));

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

    let mut cmd = repo.wt_command();
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    // Run the pre-start hook manually in foreground
    cmd.args(["hook", "pre-start", "setup"]);
    let output = cmd.output().unwrap();

    assert!(
        output.status.success(),
        "hook 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(),
        "foreground hook running `wt switch --create` should write a path to \
         the CD directive file, got: {cd_content:?}"
    );

    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}",
    );
}