gwm-cli 1.6.0

git worktree manager — TUI + CLI, native libgit2, per-repo bootstrap
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
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
//! End-to-end tests that invoke the compiled `gwm` binary via assert_cmd.
//! These exercise the user-visible CLI surface (subcommands, help, errors).

mod common;

use assert_cmd::Command;
use common::init_repo;
use predicates::prelude::*;
use std::fs;
use std::path::{Path, PathBuf};

#[test]
fn help_prints_subcommands() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.arg("--help");
  // Match the subcommand-listing column exactly: clap aligns subcommand
  // names with two leading spaces and at least two trailing spaces before
  // the description. A loose `contains("cd")` would also match prose like
  // "to cd into it" in another subcommand's description.
  // `cd` is now a visible alias of `path` (clap renders it as
  // `path  ...  [alias: cd]`), so we assert the alias marker rather than a
  // separate `  cd ` row. The regex tolerates clap's singular/plural churn:
  // 4.6.1 printed `[aliases: cd]`, 4.6.2 prints `[alias: cd]` for a lone
  // alias — `alias(es)?` matches both so a cosmetic upstream change to the
  // help formatter can't break the test again.
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("  init "))
    .stdout(predicate::str::contains("  list "))
    // Issue #408: agent-session surface (list / attach / detach).
    .stdout(predicate::str::contains("  agents "))
    .stdout(predicate::str::contains("  create "))
    // Issue #83: create an issue from repo templates, then create the worktree.
    .stdout(predicate::str::contains("  new "))
    // Issue #84: render the PR body from `[pr_template]` and shell out to `gh pr create`.
    .stdout(predicate::str::contains("  pr "))
    // Issue #308: materialise an existing PR into a worktree (inbound review).
    .stdout(predicate::str::contains("  review "))
    .stdout(predicate::str::contains("  path "))
    .stdout(predicate::str::is_match(r"\[alias(es)?: cd\]").unwrap())
    .stdout(predicate::str::contains("  bootstrap "))
    // Issue #24: fetch + rebase/merge a worktree onto its upstream.
    .stdout(predicate::str::contains("  sync "))
    .stdout(predicate::str::contains("  prune "))
    .stdout(predicate::str::contains("  completions "))
    .stdout(predicate::str::contains("  shell-init "))
    .stdout(predicate::str::contains("  switch "))
    .stdout(predicate::str::contains("  tmux "))
    .stdout(predicate::str::contains("  zellij "))
    .stdout(predicate::str::contains("  doctor "))
    .stdout(predicate::str::contains("  link "))
    .stdout(predicate::str::contains("  unlink "))
    .stdout(predicate::str::contains("  open "))
    .stdout(predicate::str::contains("  status "))
    // Issue #81: declarative GitHub labels.
    .stdout(predicate::str::contains("  labels "))
    // Issue #82: declarative GitHub milestones.
    .stdout(predicate::str::contains("  milestones "))
    // Issue #95: TOFU trust ledger.
    .stdout(predicate::str::contains("  trust "))
    // Issue #86: CLI aliases (`gwm aliases list`).
    .stdout(predicate::str::contains("  aliases "))
    // Issue #89: git-config-style `.gwm.toml` editing.
    .stdout(predicate::str::contains("  config "))
    // Issue #85: gitmoji commit-prefix + commit-msg hook installer.
    .stdout(predicate::str::contains("  commit-prefix "))
    .stdout(predicate::str::contains("  hooks "))
    // Issue #29: operation journal + undo + history.
    .stdout(predicate::str::contains("  undo "))
    .stdout(predicate::str::contains("  history "))
    // Issue #87: configurable TUI keymap (`gwm tui keys`).
    .stdout(predicate::str::contains("  tui "))
    // Issue #38: long-running JSON-RPC daemon over a unix socket. The
    // subcommand is always listed (help is identical cross-platform); the
    // socket impl is `cfg(unix)`-gated and returns a clean error elsewhere.
    .stdout(predicate::str::contains("  daemon "))
    // Issue #309: first daemon consumer — compact statusline for prompts.
    .stdout(predicate::str::contains("  statusline "))
    // Issue #313: run a command in each worktree.
    .stdout(predicate::str::contains("  exec "))
    // Issue #313: report / reclaim heavy build artifacts across worktrees.
    .stdout(predicate::str::contains("  clean "));
}

// --- gitmoji (issue #85) ------------------------------------------------

#[test]
fn commit_prefix_resolves_branch_to_shortcode_form() {
  // The canonical contract: `gwm commit-prefix --branch feat/#41-foo`
  // prints `:sparkles: feat(#41):` — the prefix every commit in this
  // repo starts with. The shortcode form is the default (matches
  // most commit hooks and tooling that lint emoji on raw text).
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["commit-prefix", "--branch", "feat/#41-foo"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains(":sparkles: feat(#41):"));
}

#[test]
fn commit_prefix_unicode_emits_real_emoji() {
  // The `--unicode` flag swaps `:sparkles:` for ✨ — meant for shell
  // prompts and the commit-msg hook (which wants the final byte
  // sequence in the message body, not the shortcode form).
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["commit-prefix", "--branch", "feat/#41-foo", "--unicode"]);
  cmd.assert().success().stdout(predicate::str::contains("✨ feat(#41):"));
}

#[test]
fn commit_prefix_for_fix_branch_uses_bug_emoji() {
  // Second branch type to pin: `fix/#10-bar` ↔ `:bug:` ↔ 🐛. The two
  // most-used emojis in the history both need an end-to-end test
  // so a future refactor that breaks one trips a binary-level
  // assertion.
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["commit-prefix", "--branch", "fix/#10-bar"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains(":bug: fix(#10):"));
}

#[test]
fn commit_prefix_with_explicit_branch_honours_repo_gitmoji_overrides() {
  // Regression guard: `--branch <name>` is a scripted entry point —
  // shell prompts, AI assistants, the installed commit-msg hook —
  // but if it bypasses `.gwm.toml`'s `[gitmoji]` block the renderer
  // contradicts itself between `gwm types --gitmoji` (which loads
  // the config) and `gwm commit-prefix --branch …` (which used not
  // to). The two surfaces MUST agree.
  let (dir, _repo) = init_repo();
  let cfg = "[gitmoji]\nfeat = \":rocket:\"\n";
  std::fs::write(dir.path().join(".gwm.toml"), cfg).expect("seed .gwm.toml");

  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["commit-prefix", "--branch", "feat/#41-foo"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains(":rocket: feat(#41):"));
}

#[test]
fn commit_prefix_on_non_gwm_branch_reports_error() {
  // `gwm commit-prefix --branch random` doesn't match the
  // `<type>/#<N>-<slug>` regex — the contract is "fail loudly with a
  // pointer to the convention" rather than silently rendering a
  // bogus prefix. The user typed `--branch <name>` explicitly, so
  // there's no auto-fallback to CWD to fall back to.
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["commit-prefix", "--branch", "random"]);
  cmd.assert().failure().stderr(predicate::str::contains("random"));
}

#[test]
fn commit_prefix_unicode_normalizes_known_shortcode_override() {
  // The UX guarantee from the PR #152 follow-up: under `--unicode`,
  // a `.gwm.toml` override that supplied a known `:shortcode:` (like
  // `:rocket:`) must render as the unicode glyph (🚀), not the
  // shortcode literal. Asymmetry between this surface and
  // `gwm types --gitmoji`'s unicode column was the original bug.
  let (dir, _repo) = init_repo();
  std::fs::write(dir.path().join(".gwm.toml"), "[gitmoji]\nfeat = \":rocket:\"\n").expect("seed .gwm.toml");
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["commit-prefix", "--branch", "feat/#1-x", "--unicode"]);
  cmd.assert().success().stdout(predicate::str::contains("🚀 feat(#1):"));
}

#[test]
fn commit_prefix_unicode_leaves_unknown_shortcode_override_verbatim() {
  // Graceful degradation for shortcodes the built-in table doesn't
  // know about. `:foo:` is not in `shortcode_to_unicode`, so under
  // `--unicode` we keep the value verbatim — the surface must remain
  // usable on any user configuration without falling back to
  // `:question:`/❓ (which would hide the user's intent).
  let (dir, _repo) = init_repo();
  std::fs::write(dir.path().join(".gwm.toml"), "[gitmoji]\nfeat = \":foo:\"\n").expect("seed .gwm.toml");
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["commit-prefix", "--branch", "feat/#1-x", "--unicode"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains(":foo: feat(#1):"));
}

#[test]
fn types_gitmoji_normalizes_known_shortcode_override_in_unicode_column() {
  // Symmetry with `gwm commit-prefix --unicode`: the `gwm types
  // --gitmoji` unicode column must show the GLYPH for a known
  // shortcode override (not the shortcode literal). The shortcode
  // column still shows the literal `:rocket:` so both forms remain
  // greppable on the same row.
  let (dir, _repo) = init_repo();
  std::fs::write(dir.path().join(".gwm.toml"), "[gitmoji]\nfeat = \":rocket:\"\n").expect("seed .gwm.toml");
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.current_dir(dir.path()).args(["types", "--gitmoji"]);
  let assert = cmd.assert().success();
  let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout");
  // Find the `feat` row and check both columns on it. A per-row
  // assertion (rather than two independent `contains(...)` checks)
  // catches the regression where the glyph appears on some unrelated
  // row but `feat` still shows `:rocket:` in the unicode column.
  let feat_row = stdout
    .lines()
    .find(|l| l.trim_start().starts_with("feat "))
    .expect("feat row must be present in `gwm types --gitmoji` output");
  assert!(
    feat_row.contains("🚀"),
    "feat unicode column must be normalised to 🚀, got: {feat_row:?}"
  );
  assert!(
    feat_row.contains(":rocket:"),
    "feat shortcode column must still be :rocket:, got: {feat_row:?}"
  );
}

#[test]
fn types_with_gitmoji_flag_includes_emoji_columns() {
  // `gwm types --gitmoji` extends the existing per-type list with
  // two more columns: the unicode emoji and the shortcode form. The
  // shortcode is asserted via `:sparkles:` (textual, deterministic);
  // the unicode column is asserted via the ✨ character.
  let dir = tempfile::TempDir::new().unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.current_dir(dir.path()).args(["types", "--gitmoji"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("feat"))
    .stdout(predicate::str::contains(":sparkles:"))
    .stdout(predicate::str::contains(""))
    .stdout(predicate::str::contains(":bug:"))
    .stdout(predicate::str::contains("🐛"));
}

#[test]
fn types_without_gitmoji_flag_does_not_include_emoji_columns() {
  // Backwards compatibility: `gwm types` (no flag) must NOT spill
  // shortcodes into its output — every scripted parser of the
  // pre-#85 surface depends on the two-column layout.
  let dir = tempfile::TempDir::new().unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.current_dir(dir.path()).arg("types");
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("feat"))
    .stdout(predicate::str::contains(":sparkles:").not())
    .stdout(predicate::str::contains("").not());
}

#[test]
fn hooks_install_commit_msg_creates_executable_hook() {
  // `gwm hooks install commit-msg` writes `.git/hooks/commit-msg` and
  // exits 0. We assert on the resulting file (not the stdout
  // message), so the test is robust to cosmetic copy changes.
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.current_dir(dir.path()).args(["hooks", "install", "commit-msg"]);
  cmd.assert().success();

  let hook = dir.path().join(".git").join("hooks").join("commit-msg");
  assert!(hook.exists(), "commit-msg hook must exist after `gwm hooks install`");
  #[cfg(unix)]
  {
    use std::os::unix::fs::PermissionsExt;
    let mode = std::fs::metadata(&hook).expect("stat hook").permissions().mode();
    assert!(mode & 0o100 != 0, "hook must be executable by owner");
  }
}

#[test]
fn hooks_install_commit_msg_refuses_existing_hook_without_force() {
  // Idempotent-safe contract: a pre-existing `commit-msg` (husky,
  // commitlint, …) is left intact and the command exits non-zero
  // with a clear pointer to `--force`.
  let (dir, _repo) = init_repo();
  let hooks_dir = dir.path().join(".git").join("hooks");
  std::fs::create_dir_all(&hooks_dir).expect("hooks dir");
  let hook_path = hooks_dir.join("commit-msg");
  std::fs::write(&hook_path, "#!/bin/sh\necho 'pre-existing hook'\n").expect("seed hook");

  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.current_dir(dir.path()).args(["hooks", "install", "commit-msg"]);
  cmd.assert().failure().stderr(predicate::str::contains("--force"));

  let body = std::fs::read_to_string(&hook_path).expect("read seeded hook");
  assert!(
    body.contains("pre-existing hook"),
    "seeded hook must not be overwritten on the refusal path"
  );
}

#[test]
fn hooks_install_commit_msg_force_overwrites() {
  // The escape hatch.
  let (dir, _repo) = init_repo();
  let hooks_dir = dir.path().join(".git").join("hooks");
  std::fs::create_dir_all(&hooks_dir).expect("hooks dir");
  let hook_path = hooks_dir.join("commit-msg");
  std::fs::write(&hook_path, "#!/bin/sh\necho 'old'\n").expect("seed hook");

  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["hooks", "install", "commit-msg", "--force"]);
  cmd.assert().success();

  let body = std::fs::read_to_string(&hook_path).expect("read installed hook");
  assert!(
    body.contains("gwm commit-msg hook"),
    "installed hook must carry the gwm marker; got {:?}",
    body
  );
}

// --- labels (issue #81) -------------------------------------------------

#[test]
fn labels_help_lists_list_and_push() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["labels", "--help"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("list"))
    .stdout(predicate::str::contains("push"));
}

#[test]
fn labels_list_outside_git_repo_fails() {
  let dir = tempfile::TempDir::new().unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["labels", "list"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("not inside a git repository"));
}

#[test]
fn labels_list_with_no_declared_labels_is_a_no_op() {
  // The no-op fast path: no `[[labels]]` in .gwm.toml ⇒ don't shell
  // out to `gh`, just print a single line and exit 0. The test
  // doesn't need `gh` on PATH to pass — that's the whole point.
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["labels", "list"])
    .assert()
    .success()
    .stdout(predicate::str::contains("0 labels declared"));
}

// --- sync (issue #24) -------------------------------------------------------

#[test]
fn sync_unknown_pattern_errors() {
  // A pattern that resolves to no worktree must fail loudly with the
  // worktree name, not silently no-op.
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["sync", "does-not-exist"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("does-not-exist"));
}

#[test]
fn sync_in_repo_without_upstream_reports_missing_upstream() {
  // `gwm sync` with no pattern targets the CWD worktree. A fresh repo
  // on `main` with no remote has no upstream → clear, actionable error.
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .arg("sync")
    .assert()
    .failure()
    .stderr(predicate::str::contains("upstream"));
}

#[test]
fn sync_from_subdir_names_the_worktree_root_not_the_subdir() {
  // Regression for the Copilot nit on #172: run from a subdirectory,
  // the success line must name the worktree root (the dir tracking the
  // upstream), not the CWD basename. Set up a bare origin + tracking
  // clone so `gwm sync` reaches the "up to date" success print.
  use std::process::Command as Git;

  fn git(dir: &Path, args: &[&str]) {
    let out = Git::new("git")
      .arg("-C")
      .arg(dir)
      .args(["-c", "commit.gpgsign=false"])
      .args(args)
      .env("GIT_AUTHOR_NAME", "t")
      .env("GIT_AUTHOR_EMAIL", "t@t")
      .env("GIT_COMMITTER_NAME", "t")
      .env("GIT_COMMITTER_EMAIL", "t@t")
      .output()
      .unwrap();
    assert!(
      out.status.success(),
      "git {:?}: {}",
      args,
      String::from_utf8_lossy(&out.stderr)
    );
  }

  let td = tempfile::TempDir::new().unwrap();
  let origin = td.path().join("origin");
  let wt = td.path().join("my-worktree");
  std::fs::create_dir_all(&origin).unwrap();
  Git::new("git")
    .args(["init", "--bare", "-b", "main"])
    .arg(&origin)
    .output()
    .unwrap();
  Git::new("git").args(["init", "-b", "main"]).arg(&wt).output().unwrap();
  git(&wt, &["config", "user.email", "t@t"]);
  git(&wt, &["config", "user.name", "t"]);
  std::fs::write(wt.join("file.txt"), "base\n").unwrap();
  git(&wt, &["add", "-A"]);
  git(&wt, &["commit", "-m", "init"]);
  git(&wt, &["remote", "add", "origin", origin.to_str().unwrap()]);
  git(&wt, &["push", "-u", "origin", "main"]);

  let sub = wt.join("src/deep");
  std::fs::create_dir_all(&sub).unwrap();

  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(&sub)
    .arg("sync")
    .assert()
    .success()
    // Names the worktree root dir, not the "deep" subdir we ran from.
    .stdout(predicate::str::contains("my-worktree"))
    .stdout(predicate::str::contains("deep").not());
}

#[test]
fn labels_push_with_no_declared_labels_is_a_no_op() {
  // Same fast path as `list`. Push must not call `gh` when there's
  // nothing to push — that would surface `gh: not found` to users
  // who haven't yet configured `[[labels]]` and tried the command.
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["labels", "push"])
    .assert()
    .success()
    .stdout(predicate::str::contains("0 labels declared"));
}

#[test]
fn labels_push_dry_run_with_no_declared_labels_succeeds() {
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["labels", "push", "--dry-run"])
    .assert()
    .success()
    .stdout(predicate::str::contains("0 labels declared"));
}

#[test]
fn labels_list_surfaces_invalid_color_with_label_name() {
  // A typo in `color` must be caught at resolve time with the label
  // name in the error message — otherwise the user has to grep their
  // config to find which entry is broken.
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    r#"
[[labels]]
name = "bug"
color = "not-a-hex"
"#,
  )
  .unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["labels", "list"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("bug"))
    .stderr(predicate::str::contains("not-a-hex"));
}

// --- milestones (issue #82) ---------------------------------------------

#[test]
fn milestones_help_lists_list_and_push() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["milestones", "--help"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("list"))
    .stdout(predicate::str::contains("push"));
}

#[test]
fn milestones_list_outside_git_repo_fails() {
  let dir = tempfile::TempDir::new().unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["milestones", "list"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("not inside a git repository"));
}

#[test]
fn milestones_list_with_no_declared_is_a_no_op() {
  // No `[[milestones]]` in .gwm.toml ⇒ don't shell out to `gh`. The
  // test passes without `gh` on PATH — that's the whole point of the
  // fast path.
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["milestones", "list"])
    .assert()
    .success()
    .stdout(predicate::str::contains("0 milestones declared"));
}

#[test]
fn milestones_push_with_no_declared_is_a_no_op() {
  // Same fast path as `list`. Push must not call `gh` when there's
  // nothing to push.
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["milestones", "push"])
    .assert()
    .success()
    .stdout(predicate::str::contains("0 milestones declared"));
}

#[test]
fn milestones_push_dry_run_with_no_declared_succeeds() {
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["milestones", "push", "--dry-run"])
    .assert()
    .success()
    .stdout(predicate::str::contains("0 milestones declared"));
}

#[test]
fn milestones_list_surfaces_invalid_due_on_with_title() {
  // A typo in `due_on` must be caught at resolve time with the
  // milestone title in the error message — otherwise the user has to
  // grep their config to find the offending entry.
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    r#"
[[milestones]]
title = "v0.7.0"
due_on = "not-a-date"
"#,
  )
  .unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["milestones", "list"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("v0.7.0"));
}

#[test]
fn milestones_list_surfaces_invalid_state_with_title() {
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    r#"
[[milestones]]
title = "v0.7.0"
state = "draft"
"#,
  )
  .unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["milestones", "list"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("v0.7.0"))
    .stderr(predicate::str::contains("draft"));
}

#[test]
fn switch_alias_s_resolves_to_switch() {
  // Issue #22: `gwm s` is the daily-driver alias for `gwm switch`. Resolving
  // `gwm s --help` to the switch help text proves the alias is wired in.
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["s", "--help"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("Open an interactive picker"));
}

#[test]
fn top_level_help_advertises_switch_alias() {
  // The visible alias must show up in the top-level help summary so users
  // discover `gwm s` without reading the subcommand-specific page. `aliases?`
  // tolerates clap's singular/plural rendering (4.6.1 `[aliases: s]`, 4.6.2
  // `[alias: s]`).
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.arg("--help");
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("switch").and(predicate::str::is_match(r"\[alias(es)?: s\]").unwrap()));
}

#[test]
fn switch_outside_git_repo_fails() {
  // Same contract as the other repo-bound subcommands: bail out with a
  // clear error rather than dropping the user into an empty TUI.
  let dir = tempfile::TempDir::new().unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .arg("switch")
    .assert()
    .failure()
    .stderr(predicate::str::contains("not inside a git repository"));
}

#[test]
fn doctor_on_fresh_repo_prints_checks() {
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  // Exit code is intentionally not asserted to be 0: in environments
  // without `lazygit` on PATH (most CI runners) or a pre-existing
  // `~/cc-worktree/` parent, the report legitimately surfaces Warning
  // entries and exits 1. But we still bound the contract — anything
  // other than 0 (all green) or 1 (warning) on a vanilla fresh repo
  // means the doctor is over-flagging (or panicking, which would also
  // produce a non-0/1 code) and we want the test to fail loudly.
  // The 0/1/2 mapping is unit-tested in `tests/doctor_tests.rs`.
  cmd
    .current_dir(dir.path())
    .arg("doctor")
    .assert()
    .code(predicate::in_iter([0_i32, 1]))
    .stdout(predicate::str::contains(""))
    .stdout(predicate::str::contains(".gwm.toml"))
    .stdout(predicate::str::contains("base directory writable"));
}

#[test]
fn doctor_outside_git_repo_fails() {
  let dir = tempfile::TempDir::new().unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .arg("doctor")
    .assert()
    .failure()
    .stderr(predicate::str::contains("not inside a git repository"));
}

#[test]
fn doctor_exits_one_when_review_binary_missing() {
  // Issue #75: configuring [review] with a binary that's not on $PATH
  // must produce a Warning (exit code 1), not a Failed (exit code 2).
  // Review is opt-in — a CI pre-commit hook gated on `gwm doctor`
  // should still let the user push when only the review tool is
  // missing locally.
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    r#"
[review]
command = "definitely-not-on-path-review-cli {base}..{head}"
"#,
  )
  .unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .arg("doctor")
    .assert()
    .code(1)
    .stdout(predicate::str::contains("definitely-not-on-path-review-cli"));
}

#[test]
fn doctor_exits_two_on_invalid_config() {
  let (dir, _repo) = init_repo();
  std::fs::write(dir.path().join(".gwm.toml"), "broken = [unterminated").unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .arg("doctor")
    .assert()
    .code(2)
    .stdout(predicate::str::contains(""));
}

#[test]
fn version_flag() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.arg("--version");
  cmd.assert().success().stdout(predicate::str::contains("gwm"));
}

#[test]
fn types_lists_branch_types() {
  // Outside any repo (the temp cwd of `assert_cmd` is typically not a
  // git repo on CI runners) `gwm types` must still list the built-in
  // defaults and surface the `built-in defaults` footer so users can
  // tell they're not looking at a `.gwm.toml` override.
  let dir = tempfile::TempDir::new().unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.current_dir(dir.path()).arg("types");
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("feat"))
    .stdout(predicate::str::contains("fix"))
    .stdout(predicate::str::contains("hotfix"))
    .stdout(predicate::str::contains("chore"))
    .stdout(predicate::str::contains("(source: built-in defaults)"));
}

#[test]
fn types_lists_configured_branch_types_from_dot_gwm_toml() {
  // When `.gwm.toml` carries a `[[branch_types]]` block, `gwm types`
  // must reflect the override verbatim and update its source footer.
  // The legacy entries that aren't in the override must NOT bleed
  // through (e.g. `hotfix` is part of the built-in defaults but is
  // intentionally absent from this repo's list).
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    r#"
[[branch_types]]
name = "feat"
description = "Feature"

[[branch_types]]
name = "migration"
description = "Database migration"
"#,
  )
  .unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.current_dir(dir.path()).arg("types");
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("feat"))
    .stdout(predicate::str::contains("migration"))
    .stdout(predicate::str::contains("Database migration"))
    .stdout(predicate::str::contains("(source: .gwm.toml)"))
    .stdout(predicate::str::contains("hotfix").not());
}

#[test]
fn types_inside_bare_repo_falls_back_to_built_in_defaults() {
  // Bare repos have no `workdir()`, so there's no place to look for a
  // `.gwm.toml`. Regression: previously `cmd_types` would propagate a
  // misleading `NotInGitRepo` error here even though `discover_repo`
  // succeeded. The fallback is identical to the "outside any repo"
  // branch — the built-in defaults with a `(source: built-in
  // defaults)` footer.
  let dir = tempfile::TempDir::new().unwrap();
  git2::Repository::init_bare(dir.path()).expect("init bare repo");
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.current_dir(dir.path()).arg("types");
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("feat"))
    .stdout(predicate::str::contains("hotfix"))
    .stdout(predicate::str::contains("(source: built-in defaults)"));
}

#[test]
fn create_outside_git_repo_fails() {
  let dir = tempfile::TempDir::new().unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.current_dir(dir.path()).arg("list");
  cmd
    .assert()
    .failure()
    .stderr(predicate::str::contains("not inside a git repository"));
}

#[test]
fn list_detect_pr_flag_adds_pr_column_with_detected_number() {
  // E2E (issue #181): `gwm list --detect-pr` shows a PR column populated
  // by `gh pr list` detection for each worktree's branch.
  let (dir, repo) = init_repo();
  repo.remote("origin", "https://github.com/kbrdn1/gwm-cli.git").unwrap();

  let fake_bin = tempfile::TempDir::new().unwrap();
  let fake_gh = write_dispatch_gh(fake_bin.path(), r#"[{"number":128}]"#, r#"{}"#);

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_GH", &fake_gh)
    .env("PATH", prepend_path(fake_bin.path()))
    .args(["list", "--detect-pr"])
    .assert()
    .success()
    .stdout(predicate::str::contains("PR"))
    .stdout(predicate::str::contains("#128"));
}

// --- GitLab dispatch, end to end (issue #419) -----------------------------

#[cfg(unix)]
#[test]
fn list_detect_pr_dispatches_to_glab_on_a_gitlab_origin() {
  // The forge split's most basic observable claim, and until now only
  // covered by argv unit tests: a GitLab origin must reach `glab`, with
  // the MR vocabulary and the `--repo` selector, not `gh`.
  let (dir, repo) = init_repo();
  repo.remote("origin", "https://gitlab.com/group/proj.git").unwrap();

  let fake_bin = tempfile::TempDir::new().unwrap();
  let log = fake_bin.path().join("calls.log");
  let fake_glab = write_recording_glab(
    fake_bin.path(),
    r#"[{"iid":128,"project_id":7,"source_project_id":7}]"#,
    "{}",
  );

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_GLAB", &fake_glab)
    .env("GWM_FAKE_LOG", &log)
    .env("PATH", prepend_path(fake_bin.path()))
    .args(["list", "--detect-pr"])
    .assert()
    .success()
    .stdout(predicate::str::contains("#128"));

  let calls = fs::read_to_string(&log).unwrap();
  assert!(calls.contains("ARGV:mr list"), "must speak MR, not PR: {calls}");
  assert!(
    calls.contains("--repo group/proj"),
    "must target the origin slug: {calls}"
  );
}

#[cfg(unix)]
#[test]
fn the_glab_child_does_not_inherit_the_environment_that_would_retarget_it() {
  // The end-to-end counterpart to the unit tests on `glab_env_remove`,
  // and the reason this harness exists: rounds 4, 7, 9 and 10 each found
  // an inherited variable that silently redirected the CLI, and every
  // fix was verified only against a pure function. This asserts the
  // contract where it actually matters — on the spawned process.
  //
  // `GITLAB_TOKEN` is in here as the negative control: tier 3 of the
  // rule says authentication is never stripped, so a test that only
  // checked "things are cleared" could pass while breaking every auth.
  let (dir, repo) = init_repo();
  repo.remote("origin", "https://gitlab.com/group/proj.git").unwrap();

  let fake_bin = tempfile::TempDir::new().unwrap();
  let log = fake_bin.path().join("calls.log");
  let fake_glab = write_recording_glab(fake_bin.path(), "[]", "{}");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_GLAB", &fake_glab)
    .env("GWM_FAKE_LOG", &log)
    .env("PATH", prepend_path(fake_bin.path()))
    // Exported by the user, pointing somewhere else entirely.
    .env("GITLAB_REPO", "someone-else/private")
    .env("GITLAB_GROUP", "someone-else")
    .env("GITLAB_TOKEN", "keep-me")
    // Outranks the host pin inside glab, and points at another tenant.
    .env("GITLAB_API_HOST", "https://api.gitlab.example.com")
    .env("GL_HOST", "https://gitlab.other.example")
    // Would downgrade the pinned https instance to cleartext.
    .env("API_PROTOCOL", "http")
    .args(["list", "--detect-pr"])
    .assert()
    .success();

  let calls = fs::read_to_string(&log).unwrap();
  assert!(
    calls.contains("GITLAB_REPO:<unset>"),
    "selector must be cleared: {calls}"
  );
  assert!(
    calls.contains("GITLAB_GROUP:<unset>"),
    "selector must be cleared: {calls}"
  );
  assert!(
    calls.contains("GITLAB_HOST:https://gitlab.com"),
    "an authoritative origin must be pinned: {calls}"
  );
  assert!(
    calls.contains("GITLAB_TOKEN:keep-me"),
    "authentication is the user's to set and must survive: {calls}"
  );
  // Behind the pin all three of these have a replacement: glab falls
  // back to `apiHost = repoHost`, `GITLAB_HOST` already outranks the
  // other host spellings, and gwm knows the scheme from the origin.
  assert!(
    calls.contains("GITLAB_API_HOST:<unset>"),
    "an inherited API host outranks the pin and must go: {calls}"
  );
  assert!(calls.contains("GL_HOST:<unset>"), "{calls}");
  assert!(
    calls.contains("API_PROTOCOL:https"),
    "the scheme is pinned, not merely cleared: {calls}"
  );
}

#[test]
fn list_without_detect_pr_flag_has_no_pr_column() {
  // Default `gwm list` stays network-free: no PR column, no `#` markers.
  let (dir, repo) = init_repo();
  repo.remote("origin", "https://github.com/kbrdn1/gwm-cli.git").unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["list"])
    .assert()
    .success()
    .stdout(predicate::str::contains("STATUS"))
    .stdout(predicate::str::contains("PATH"))
    .stdout(predicate::str::contains('#').not());
}

#[test]
fn completions_zsh_emits_compdef_header() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["completions", "zsh"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("#compdef gwm"))
    .stdout(predicate::str::contains("_gwm"));
}

#[test]
fn completions_bash_emits_complete_directive() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["completions", "bash"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("_gwm"))
    .stdout(predicate::str::contains("complete "));
}

#[test]
fn completions_fish_emits_complete_directive() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["completions", "fish"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("complete -c gwm"));
}

#[test]
fn completions_powershell_emits_register_block() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["completions", "powershell"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("Register-ArgumentCompleter"))
    .stdout(predicate::str::contains("gwm"));
}

#[test]
fn completions_rejects_unknown_shell() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["completions", "tcsh"]);
  cmd.assert().failure();
}

#[test]
fn list_format_names_emits_one_name_per_line() {
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["list", "--format=names"])
    .assert()
    .success()
    // No table header, no leading "*" marker, no STATUS column.
    .stdout(predicate::str::contains("NAME").not())
    .stdout(predicate::str::contains("STATUS").not())
    // Main worktree is excluded so the output mirrors what `find_fuzzy`
    // accepts (path/remove/bootstrap skip the main workdir). A fresh repo
    // therefore prints nothing.
    .stdout(predicate::str::is_empty());
}

// --- JSON output flags (issue #38, phase 1) ----------------------------

#[test]
fn list_format_json_emits_a_parseable_worktree_array() {
  // Unlike `--format names`, the JSON array includes the main worktree:
  // an editor / statusbar consumer wants the full set, and resolves the
  // active worktree from it. A fresh repo has exactly the main worktree.
  let (dir, _repo) = init_repo();
  let out = Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["list", "--format=json"])
    .output()
    .unwrap();
  assert!(out.status.success(), "list --format=json must exit 0");
  let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("stdout must be valid JSON");
  let arr = v.as_array().expect("top level must be a JSON array");
  assert_eq!(arr.len(), 1, "a fresh repo has exactly the main worktree");
  let main = &arr[0];
  assert_eq!(main["is_main"], serde_json::json!(true));
  // Stable schema keys present.
  assert!(main.get("name").is_some());
  assert!(main.get("path").is_some());
  assert!(main.get("status").is_some());
  assert!(main["status"].get("is_dirty").is_some());
  // Optional link fields are present and null on a fresh repo.
  assert_eq!(main["pr"], serde_json::Value::Null);
}

#[test]
fn list_format_json_with_detect_pr_populates_the_pr_field() {
  // `--format=json --detect-pr` must agree with the table: the JSON `pr`
  // field carries the freshly detected number, not just the persisted
  // link (issue #38 review).
  let (dir, repo) = init_repo();
  repo.remote("origin", "https://github.com/kbrdn1/gwm-cli.git").unwrap();
  let fake_bin = tempfile::TempDir::new().unwrap();
  let fake_gh = write_dispatch_gh(fake_bin.path(), r#"[{"number":128}]"#, r#"{}"#);

  let out = Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_GH", &fake_gh)
    .env("PATH", prepend_path(fake_bin.path()))
    .args(["list", "--format=json", "--detect-pr"])
    .output()
    .unwrap();
  assert!(out.status.success());
  let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("valid JSON");
  let arr = v.as_array().unwrap();
  // The main worktree's branch gets the detected PR #128.
  assert!(
    arr.iter().any(|w| w["pr"] == serde_json::json!(128)),
    "detected PR number must surface in the JSON `pr` field, got: {v}"
  );
}

#[test]
fn list_format_json_detect_pr_keeps_explicit_link_when_detection_cannot_run() {
  // Regression (issue #38 review): with `--detect-pr` in a repo that has
  // no GitHub slug, live detection can't run, so it must NOT clobber an
  // explicit/persisted local PR link that the plain listing already shows.
  let (dir, repo) = init_repo();
  // No remote → repo_slug fails → detection yields None for every row.
  let head = repo.head().unwrap();
  let branch = head.shorthand().unwrap().to_string();
  // Explicit PR link in branch config (`branch.<name>.gwm-pr`).
  repo
    .config()
    .unwrap()
    .set_i64(&format!("branch.{branch}.gwm-pr"), 77)
    .unwrap();

  let out = Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["list", "--format=json", "--detect-pr"])
    .output()
    .unwrap();
  assert!(out.status.success());
  let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("valid JSON");
  let arr = v.as_array().unwrap();
  assert!(
    arr.iter().any(|w| w["pr"] == serde_json::json!(77)),
    "explicit PR link must be preserved when detection can't run, got: {v}"
  );
}

#[test]
fn list_format_json_detect_pr_clears_a_stale_persisted_pr() {
  // The flip side (issue #38 review): when detection DOES run (GitHub slug
  // present) and `gh pr list` returns no PR for a branch that had a
  // persisted detected PR, the JSON must clear it to null — matching the
  // table — not leave the stale number.
  let (dir, repo) = init_repo();
  repo.remote("origin", "https://github.com/kbrdn1/gwm-cli.git").unwrap();
  let head = repo.head().unwrap();
  let branch = head.shorthand().unwrap().to_string();
  // A persisted (now stale) detected PR in branch config.
  repo
    .config()
    .unwrap()
    .set_i64(&format!("branch.{branch}.gwm-pr-detected"), 99)
    .unwrap();

  let fake_bin = tempfile::TempDir::new().unwrap();
  // `gh pr list --head` returns no PR → detection clears the cache.
  let fake_gh = write_dispatch_gh(fake_bin.path(), "[]", "{}");

  let out = Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_GH", &fake_gh)
    .env("PATH", prepend_path(fake_bin.path()))
    .args(["list", "--format=json", "--detect-pr"])
    .output()
    .unwrap();
  assert!(out.status.success());
  let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("valid JSON");
  let arr = v.as_array().unwrap();
  assert!(
    arr.iter().all(|w| w["pr"] != serde_json::json!(99)),
    "a stale persisted PR must be cleared once detection runs, got: {v}"
  );
}

#[test]
fn doctor_format_json_emits_checks_severity_and_exit_code() {
  let (dir, _repo) = init_repo();
  let out = Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["doctor", "--format=json"])
    .output()
    .unwrap();
  let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("doctor json must parse");
  assert!(v["checks"].is_array(), "checks must be an array");
  assert!(
    !v["checks"].as_array().unwrap().is_empty(),
    "doctor runs at least one check"
  );
  let sev = v["severity"].as_str().expect("severity must be a string");
  assert!(
    matches!(sev, "ok" | "warning" | "failed"),
    "severity stable enum, got {sev}"
  );
  // The JSON exit_code mirrors the process exit code.
  let json_code = v["exit_code"].as_i64().expect("exit_code is an integer");
  let proc_code = out.status.code().unwrap_or(-1) as i64;
  assert_eq!(json_code, proc_code, "json exit_code must equal the process exit code");
  // Per-check shape.
  let first = &v["checks"][0];
  assert!(first.get("name").is_some());
  let cs = first["status"].as_str().unwrap();
  assert!(matches!(cs, "ok" | "warning" | "failed"));
}

#[test]
fn path_format_json_emits_name_path_branch() {
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "38", "json-path"])
    .assert()
    .success();

  let out = Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["path", "json-path", "--format=json"])
    .output()
    .unwrap();
  assert!(out.status.success(), "path --format=json must exit 0");
  let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("path json must parse");
  let obj = v.as_object().expect("path json must be an object");
  assert_eq!(obj.len(), 3, "exactly {{name, path, branch}}");
  assert_eq!(v["name"], serde_json::json!("feat-38-json-path"));
  assert_eq!(v["branch"], serde_json::json!("feat/#38-json-path"));
  assert!(
    v["path"].as_str().unwrap().ends_with("feat-38-json-path"),
    "path points at the worktree dir"
  );
}

#[test]
fn daemon_rejects_zero_poll_ms() {
  // `--poll-ms 0` would spin a subscribe loop with no wait; clap rejects
  // it at parse time (range 1..) so the daemon never starts (issue #38
  // review). No repo / socket needed — validation fails first.
  Command::cargo_bin("gwm")
    .unwrap()
    .args(["daemon", "--poll-ms", "0"])
    .assert()
    .failure()
    .stderr(
      predicate::str::contains("0").and(predicate::str::contains("not in").or(predicate::str::contains("invalid"))),
    );
}

#[test]
fn statusline_without_a_daemon_prints_blank_and_exits_zero() {
  // No daemon is listening at the given socket. A prompt substitution must
  // not break: the command exits 0 and emits no worktree summary, just a
  // blank line (issue #309 graceful-degradation contract).
  let sock_dir = tempfile::TempDir::new().unwrap();
  let missing = sock_dir.path().join("no-daemon.sock");
  Command::cargo_bin("gwm")
    .unwrap()
    .arg("statusline")
    .arg("--socket")
    .arg(&missing)
    .assert()
    .success()
    .stdout(predicate::str::contains(" wt").not());
}

#[test]
fn statusline_help_documents_watch_and_socket() {
  Command::cargo_bin("gwm")
    .unwrap()
    .args(["statusline", "--help"])
    .assert()
    .success()
    .stdout(predicate::str::contains("--watch"))
    .stdout(predicate::str::contains("--socket"));
}

#[test]
fn cd_unknown_pattern_fails_with_not_found() {
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["cd", "nope"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("not found"));
}

#[test]
fn cd_outside_git_repo_fails() {
  let dir = tempfile::TempDir::new().unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["cd", "anything"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("not inside a git repository"));
}

// Use `function gcd { ... }` (zsh-style, also valid in bash) rather than
// `gcd() { ... }`. The latter triggers `zsh: defining function based on
// alias 'gcd'` at parse time when an alias of the same name already
// exists — even if a preceding `unalias` would remove it, since zsh
// parses the whole eval'd block before running any of it.
#[test]
fn shell_init_bash_emits_gcd_function() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["shell-init", "bash"]);
  // Pin the invocation site: a regression that mentions `gwm cd` only in
  // a comment but doesn't actually call it from the function body would
  // pass a loose `contains("gwm cd")`. `gwm cd "$@"` (POSIX-style
  // argument forwarding) is what makes `gcd auth` translate into
  // `gwm cd auth`.
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("function gcd"))
    .stdout(predicate::str::contains("gwm cd \"$@\""));
}

#[test]
fn shell_init_zsh_emits_gcd_function() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["shell-init", "zsh"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("function gcd"))
    .stdout(predicate::str::contains("gwm cd \"$@\""));
}

// Regression: in zsh, an existing alias (e.g. `gcd='git checkout'` from
// oh-my-zsh's git plugin) wins over a same-named function and refuses to
// be shadowed at definition time ("defining function based on alias").
// The init script must `unalias gcd` first so the function takes effect
// regardless of the user's prior aliases.
#[test]
fn shell_init_posix_unaliases_gcd_first() {
  // regression: oh-my-zsh's git plugin defines `gcd='git checkout'` which
  // shadowed our gcd function ("defining function based on alias").
  for shell in ["bash", "zsh"] {
    let mut cmd = Command::cargo_bin("gwm").unwrap();
    cmd.args(["shell-init", shell]);
    cmd.assert().success().stdout(predicate::str::contains("unalias gcd"));
  }
}

#[test]
fn shell_init_powershell_unaliases_gcd_first() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["shell-init", "powershell"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("Remove-Alias"))
    .stdout(predicate::str::contains("gcd"));
}

#[test]
fn shell_init_fish_emits_function_block() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["shell-init", "fish"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("function gcd"))
    .stdout(predicate::str::contains("gwm cd $argv"))
    .stdout(predicate::str::contains("end"));
}

// Regression: fish performs wildcard expansion on unquoted variables, so
// `cd $target` would mangle paths containing `[`, `]`, or `*`. The
// emitted helper must use `cd -- "$target"` to disable both option
// parsing and glob expansion.
#[test]
fn shell_init_fish_quotes_target_with_double_dash() {
  // regression: fish wildcard expansion mangled paths containing `[`, `]`,
  // or `*` when the helper used `cd $target` without `cd -- "$target"`.
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["shell-init", "fish"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("cd -- \"$target\""));
}

#[test]
fn shell_init_powershell_emits_function_block() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["shell-init", "powershell"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("function gcd"))
    .stdout(predicate::str::contains("gwm cd $Pattern"))
    .stdout(predicate::str::contains("Set-Location"));
}

// Issue #22: with no argument, `gcd` should drop into `gwm switch` (the
// interactive picker) rather than print a usage error. The wrapper must
// still bail before cd'ing if the picker is cancelled (non-zero exit).
#[test]
fn shell_init_posix_no_arg_invokes_switch() {
  for shell in ["bash", "zsh"] {
    let mut cmd = Command::cargo_bin("gwm").unwrap();
    cmd.args(["shell-init", shell]);
    cmd
      .assert()
      .success()
      .stdout(predicate::str::contains("gwm switch"))
      .stdout(predicate::str::contains("\"$#\" -eq 0"));
  }
}

#[test]
fn shell_init_fish_no_arg_invokes_switch() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["shell-init", "fish"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("gwm switch"))
    .stdout(predicate::str::contains("count $argv) -eq 0"));
}

#[test]
fn shell_init_powershell_no_arg_invokes_switch() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["shell-init", "powershell"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("gwm switch"))
    .stdout(predicate::str::contains("IsNullOrEmpty"));
}

// Issue #58: users who eval the wrapper without reading the README must
// still discover the no-arg route. Pin a one-line cheat-sheet comment in
// the script header that names the bridge to `gwm switch`. The exact
// phrase `picker via `gwm switch`` is asserted because the README, the
// CLI --help, and the wrapper now share that wording — drift in one
// surface should break the test instead of going unnoticed.
#[test]
fn shell_init_posix_header_documents_no_arg_route() {
  for shell in ["bash", "zsh"] {
    let mut cmd = Command::cargo_bin("gwm").unwrap();
    cmd.args(["shell-init", shell]);
    cmd
      .assert()
      .success()
      .stdout(predicate::str::contains("picker via `gwm switch`"));
  }
}

#[test]
fn shell_init_fish_header_documents_no_arg_route() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["shell-init", "fish"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("picker via `gwm switch`"));
}

#[test]
fn shell_init_powershell_header_documents_no_arg_route() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["shell-init", "powershell"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("picker via `gwm switch`"));
}

// Issue #58: a user who lands on `gwm switch --help` first (e.g. via tab
// completion) should learn that the recommended invocation is the `gcd`
// wrapper from `gwm shell-init`, not the raw `cd "$(gwm switch)"` form.
#[test]
fn switch_help_mentions_gcd_wrapper() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["switch", "--help"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("gcd").and(predicate::str::contains("shell-init")));
}

#[test]
fn shell_init_rejects_unknown_shell() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["shell-init", "tcsh"]);
  cmd.assert().failure();
}

#[test]
fn list_format_table_is_default() {
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .arg("list")
    .assert()
    .success()
    .stdout(predicate::str::contains("NAME"))
    .stdout(predicate::str::contains("STATUS"));
}

// --------------------------------------------------------------------------
// Issue #23 — `gwm tmux <pattern>` / `gwm zellij <pattern>`
// --------------------------------------------------------------------------
//
// The actual spawn (`std::process::Command::new("tmux").args(...)`) is out
// of scope here — driving it would require a live tmux/zellij server on
// every CI runner. We instead pin the user-visible contract:
//
//   1. The subcommands exist and are listed in `gwm --help`.
//   2. Outside the corresponding multiplexer (no `$TMUX` / `$ZELLIJ`),
//      the command exits non-zero with a clear stderr that names the
//      missing multiplexer — no silent no-op.
//   3. Outside a git repo, the standard `NotInGitRepo` error wins.
//   4. The argv-builder unit tests in `tests/multiplexer_tests.rs`
//      cover what gets handed to the spawn.

#[test]
fn tmux_outside_tmux_session_fails_with_clear_error() {
  // CI runners and most local shells don't have `$TMUX` set. The command
  // must refuse loudly rather than spawn `tmux` against no server, which
  // would either start a brand-new tmux server or error opaquely.
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .env_remove("TMUX")
    .args(["tmux", "anything"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("tmux").and(predicate::str::contains("not")));
}

#[test]
fn zellij_outside_zellij_session_fails_with_clear_error() {
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .env_remove("ZELLIJ")
    .args(["zellij", "anything"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("zellij").and(predicate::str::contains("not")));
}

#[test]
fn tmux_outside_git_repo_fails() {
  // `NotInGitRepo` wins over the multiplexer-not-running gate when both
  // apply — the user is told to fix the more fundamental problem first.
  let dir = tempfile::TempDir::new().unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .env_remove("TMUX")
    .args(["tmux", "anything"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("not inside a git repository"));
}

#[test]
fn zellij_outside_git_repo_fails() {
  let dir = tempfile::TempDir::new().unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .env_remove("ZELLIJ")
    .args(["zellij", "anything"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("not inside a git repository"));
}

// regression: PR #65 Copilot review — the not-running error carried a
// literal backslash before the env var name (`\$TMUX` instead of
// `$TMUX`). The `\\` came from a shell-escape habit; this is stderr,
// not shell source, so the dollar must render bare.
#[test]
fn tmux_outside_tmux_error_does_not_escape_dollar() {
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .env_remove("TMUX")
    .args(["tmux", "anything"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("\\$").not())
    // And `$TMUX` itself must still appear so the hint is actionable.
    .stderr(predicate::str::contains("$TMUX"));
}

#[test]
fn zellij_outside_zellij_error_does_not_escape_dollar() {
  let (dir, _repo) = init_repo();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .env_remove("ZELLIJ")
    .args(["zellij", "anything"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("\\$").not())
    .stderr(predicate::str::contains("$ZELLIJ"));
}

#[test]
fn tmux_help_mentions_split_flag() {
  // The `-p` flag (split-pane instead of new-window) is the one knob users
  // care about; it must show up in `--help` so it's discoverable without
  // reading the README.
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["tmux", "--help"]);
  cmd.assert().success().stdout(predicate::str::contains("--split"));
}

#[test]
fn zellij_help_mentions_split_flag() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["zellij", "--help"]);
  cmd.assert().success().stdout(predicate::str::contains("--split"));
}

// --- Issue/PR linking (issue #67) ----------------------------------------

#[test]
fn link_help_documents_issue_and_pr_targets() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["link", "--help"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("issue"))
    .stdout(predicate::str::contains("pr"));
}

#[test]
fn unlink_help_documents_issue_and_pr_targets() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["unlink", "--help"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("issue"))
    .stdout(predicate::str::contains("pr"));
}

#[test]
fn open_help_documents_issue_and_pr_and_print_url() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["open", "--help"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("issue"))
    .stdout(predicate::str::contains("pr"))
    .stdout(predicate::str::contains("--print-url"));
}

#[test]
fn status_help_documents_json_flag() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["status", "--help"]);
  cmd.assert().success().stdout(predicate::str::contains("--json"));
}

#[test]
fn link_outside_git_repo_fails() {
  let dir = tempfile::TempDir::new().unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["link", "issue", "42"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("not inside a git repository"));
}

#[test]
fn link_issue_persists_and_status_reflects_it() {
  // E2E: link an issue then `gwm status --json` reads it back.
  // The repo has no remote configured so `status` runs in "local link only" mode
  // (no GitHub fetch). The JSON output should still carry the linked number.
  let (dir, repo) = init_repo();
  // Need a branch that's checked out for the CWD-resolved status to find it.
  let head = repo.head().unwrap().peel_to_commit().unwrap();
  repo.branch("feat/#42-tui-search", &head, false).unwrap();
  repo.set_head("refs/heads/feat/#42-tui-search").unwrap();

  // link
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["link", "issue", "99"])
    .assert()
    .success()
    .stdout(predicate::str::contains("issue #99"));

  // status --json
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["status", "--json"])
    .assert()
    .success()
    .stdout(predicate::str::contains("\"issue\""))
    .stdout(predicate::str::contains("99"));
}

#[test]
fn unlink_issue_falls_back_to_branch_name_auto_detect() {
  let (dir, repo) = init_repo();
  let head = repo.head().unwrap().peel_to_commit().unwrap();
  repo.branch("feat/#42-tui-search", &head, false).unwrap();
  repo.set_head("refs/heads/feat/#42-tui-search").unwrap();

  // Override then unlink.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["link", "issue", "99"])
    .assert()
    .success();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["unlink", "issue"])
    .assert()
    .success();

  // After unlink the branch-name auto-detect should resurface (issue #42).
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["status", "--json"])
    .assert()
    .success()
    .stdout(predicate::str::contains("42"));
}

#[test]
fn status_auto_detects_pr_when_none_explicitly_linked() {
  // E2E (issue #181): a branch with a GitHub remote and no explicit PR
  // link. `gwm status --json` should detect the branch's PR via `gh pr
  // list` and report it with source "detected".
  let (dir, repo) = init_repo();
  repo.remote("origin", "https://github.com/kbrdn1/gwm-cli.git").unwrap();
  let head = repo.head().unwrap().peel_to_commit().unwrap();
  // No issue number in the name → isolates the PR-detection path.
  repo.branch("detect-me", &head, false).unwrap();
  repo.set_head("refs/heads/detect-me").unwrap();

  let fake_bin = tempfile::TempDir::new().unwrap();
  let fake_gh = write_dispatch_gh(
    fake_bin.path(),
    r#"[{"number":128}]"#,
    r#"{"number":128,"title":"Auto-detect PR","state":"OPEN","isDraft":false,"url":"https://github.com/kbrdn1/gwm-cli/pull/128"}"#,
  );

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_GH", &fake_gh)
    .env("PATH", prepend_path(fake_bin.path()))
    .args(["status", "--json"])
    .assert()
    .success()
    .stdout(predicate::str::contains("\"number\":128"))
    .stdout(predicate::str::contains("\"source\":\"detected\""));
}

#[test]
fn status_persists_detected_pr_title_after_fetch() {
  let (dir, repo) = init_repo();
  repo.remote("origin", "https://github.com/kbrdn1/gwm-cli.git").unwrap();
  let head = repo.head().unwrap().peel_to_commit().unwrap();
  repo.branch("detect-me", &head, false).unwrap();
  repo.set_head("refs/heads/detect-me").unwrap();

  let fake_bin = tempfile::TempDir::new().unwrap();
  let fake_gh = write_dispatch_gh(
    fake_bin.path(),
    r#"[{"number":128}]"#,
    r#"{"number":128,"title":"Auto-detect PR","state":"OPEN","isDraft":false,"url":"https://github.com/kbrdn1/gwm-cli/pull/128"}"#,
  );

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_GH", &fake_gh)
    .env("PATH", prepend_path(fake_bin.path()))
    .args(["status", "--json"])
    .assert()
    .success();

  let link = gwm::github::read_link(&repo, "detect-me").unwrap();
  assert_eq!(link.pr, Some(128));
  assert_eq!(link.pr_source, gwm::github::LinkSource::Detected);
  assert_eq!(link.pr_title.as_deref(), Some("Auto-detect PR"));
}

#[test]
fn review_resolves_pr_metadata_and_names_branch_end_to_end() {
  // E2E (issue #308): drive `gwm review <PR#>` through the clap entry point.
  // A fake `gh` resolves the PR head metadata and `repo_slug` parses the
  // GitHub origin; `GIT_ALLOW_PROTOCOL=file` then makes the subsequent
  // `git fetch` over https fail instantly (no network) right after the
  // resolution block is printed — so the assertion stays hermetic and fast.
  //
  // This pins the clap surface + gh metadata resolution + review naming +
  // `[worktree].base` expansion that the unit / integration tests bypass. The
  // full fetch→worktree→link→base path is covered hermetically by
  // tests/review_integration.rs (which drives `review::materialize` directly
  // against a local origin and needs no GitHub URL — the slug/fetch coupling
  // makes that step un-mockable through the binary without a network call).
  let (dir, repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());
  repo.remote("origin", "https://github.com/kbrdn1/gwm-cli.git").unwrap();

  let fake_bin = tempfile::TempDir::new().unwrap();
  let fake_gh = write_dispatch_gh(
    fake_bin.path(),
    "[]",
    r#"{"number":1,"author":{"login":"alice"},"headRefName":"feat/spike-x","baseRefName":"main"}"#,
  );

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_GH", &fake_gh)
    .env("PATH", prepend_path(fake_bin.path()))
    .env("GIT_ALLOW_PROTOCOL", "file") // reject the https fetch instantly, no network
    .args(["review", "1"])
    .assert()
    .failure()
    .stdout(predicate::str::contains("PR     : #1 by alice (feat/spike-x → main)"))
    .stdout(predicate::str::contains("branch : review/pr-1-alice-spike-x"))
    .stdout(predicate::str::contains("review-pr-1-alice-spike-x"));
}

#[test]
fn status_explicit_pr_link_wins_over_detection() {
  // An explicit `gwm link --pr` must not be clobbered by detection: the
  // reported source stays "explicit" even though `gh pr list` would
  // return a different number.
  let (dir, repo) = init_repo();
  repo.remote("origin", "https://github.com/kbrdn1/gwm-cli.git").unwrap();
  let head = repo.head().unwrap().peel_to_commit().unwrap();
  repo.branch("detect-me", &head, false).unwrap();
  repo.set_head("refs/heads/detect-me").unwrap();

  let fake_bin = tempfile::TempDir::new().unwrap();
  let fake_gh = write_dispatch_gh(
    fake_bin.path(),
    r#"[{"number":999}]"#,
    r#"{"number":61,"title":"Explicit","state":"OPEN","isDraft":false,"url":"https://github.com/kbrdn1/gwm-cli/pull/61"}"#,
  );

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["link", "pr", "61"])
    .assert()
    .success();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_GH", &fake_gh)
    .env("PATH", prepend_path(fake_bin.path()))
    .args(["status", "--json"])
    .assert()
    .success()
    .stdout(predicate::str::contains("\"number\":61"))
    .stdout(predicate::str::contains("\"source\":\"explicit\""));
}

#[test]
fn open_print_url_emits_url_without_spawning_browser() {
  // `--print-url` is the test-friendly mode: we want to assert the URL
  // construction without actually shelling out to `open`/`xdg-open`.
  let (dir, repo) = init_repo();
  repo.remote("origin", "https://github.com/kbrdn1/gwm-cli.git").unwrap();
  let head = repo.head().unwrap().peel_to_commit().unwrap();
  repo.branch("feat/#42-tui-search", &head, false).unwrap();
  repo.set_head("refs/heads/feat/#42-tui-search").unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["open", "issue", "--print-url"])
    .assert()
    .success()
    .stdout(predicate::str::contains("https://github.com/kbrdn1/gwm-cli/issues/42"));
}

#[test]
fn open_pr_without_link_fails_clearly() {
  let (dir, repo) = init_repo();
  repo.remote("origin", "https://github.com/kbrdn1/gwm-cli.git").unwrap();
  let head = repo.head().unwrap().peel_to_commit().unwrap();
  // Branch without an issue number (no auto-detect) and no explicit PR link.
  repo.branch("random-branch", &head, false).unwrap();
  repo.set_head("refs/heads/random-branch").unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["open", "pr", "--print-url"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("no PR linked"));
}

#[test]
fn status_on_branch_with_no_link_reports_no_link() {
  let (dir, repo) = init_repo();
  let head = repo.head().unwrap().peel_to_commit().unwrap();
  repo.branch("random-branch", &head, false).unwrap();
  repo.set_head("refs/heads/random-branch").unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["status"])
    .assert()
    .success()
    .stdout(predicate::str::contains("no link"));
}

// --------------------------------------------------------------------------
// Issue #101 — E2E tests for the mutating subcommands (init / create / remove)
// --------------------------------------------------------------------------
//
// `cli_binary.rs` historically asserted only `--help` output and a handful
// of read-only error paths. The three subcommands that mutate state on
// disk (`init`, `create`, `remove`) had no end-to-end coverage, which let
// orchestration-layer regressions (e.g. issues #98 and #99) slip through
// unit-test review. The block below is the canonical CI signal for the
// CLI surface of those subcommands.
//
// Worktree-creating tests pin `[worktree].base` to a `tempfile::TempDir`
// so the test runner never writes under `~/cc-worktree/...`. The branch
// pattern is left at its default (`{type}/#{issue}-{desc}`) to exercise
// the production naming pipeline.

// --- init ---------------------------------------------------------------

#[test]
fn init_writes_gwm_toml_with_expected_sections() {
  // The default `.gwm.toml` shipped by `gwm init` is sourced from
  // `examples/gwm.toml.example`. Asserting on the exact contents would
  // couple the test to the example file character-for-character; we pin
  // the structural markers a user (and the rest of the codebase) relies
  // on: a `[worktree]` block with the documented placeholders, a
  // `[[bootstrap.copy]]` entry, and a `[[bootstrap.guard]]` entry. The
  // stdout line names the written path so users discover where it landed.
  let (dir, _repo) = init_repo();
  let cfg_path = dir.path().join(".gwm.toml");
  assert!(!cfg_path.exists(), "precondition: no .gwm.toml in fresh repo");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .arg("init")
    .assert()
    .success()
    .stdout(predicate::str::contains(".gwm.toml"));

  assert!(cfg_path.exists(), "gwm init must write .gwm.toml on disk");
  let body = std::fs::read_to_string(&cfg_path).unwrap();
  assert!(body.contains("[worktree]"), "missing [worktree] section");
  assert!(
    body.contains("base = ") && body.contains("{home}") && body.contains("{repo}"),
    "missing documented placeholders in [worktree].base"
  );
  assert!(
    body.contains("[[bootstrap.copy]]"),
    "missing [[bootstrap.copy]] template"
  );
  assert!(
    body.contains("[[bootstrap.guard]]"),
    "missing [[bootstrap.guard]] template"
  );
}

#[test]
fn init_refuses_to_overwrite_existing_gwm_toml() {
  // Idempotency contract: a second `gwm init` on a repo that already
  // carries a `.gwm.toml` must bail out instead of silently clobbering
  // user edits. The error must name the file *and* explain why so the
  // user knows what to remove if they truly want to start over. Pin
  // the exact "already exists" wording from `Config::write_default`
  // (src/config.rs) — a looser `.gwm.toml` contains-check would also
  // pass on a success run since the success path prints the same path.
  let (dir, _repo) = init_repo();
  let cfg_path = dir.path().join(".gwm.toml");
  std::fs::write(&cfg_path, "# user edits\n[worktree]\nbase = \"/custom\"\n").unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .arg("init")
    .assert()
    .failure()
    .stderr(predicate::str::contains(".gwm.toml"))
    .stderr(predicate::str::contains("already exists"));

  // Original contents must survive the failed init.
  let body = std::fs::read_to_string(&cfg_path).unwrap();
  assert!(
    body.contains("# user edits"),
    "failed gwm init must not modify the existing .gwm.toml"
  );
}

#[test]
fn init_outside_git_repo_fails() {
  // `cmd_init` calls `discover_repo` first — the standard `NotInGitRepo`
  // error wins so the user is steered to `git init` before configuring.
  let dir = tempfile::TempDir::new().unwrap();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .arg("init")
    .assert()
    .failure()
    .stderr(predicate::str::contains("not inside a git repository"));
}

// --- init --preset (issue #37) ------------------------------------------

#[test]
fn init_list_presets_enumerates_builtins() {
  // `--list-presets` is a pure stdout enumeration — it must work without a
  // git repo (it returns before `discover_repo`) and name every built-in.
  let dir = tempfile::TempDir::new().unwrap();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["init", "--list-presets"])
    .assert()
    .success()
    .stdout(predicate::str::contains("generic"))
    .stdout(predicate::str::contains("laravel"))
    .stdout(predicate::str::contains("node"))
    .stdout(predicate::str::contains("rust"))
    .stdout(predicate::str::contains("python-uv"));
}

#[test]
fn init_preset_show_prints_without_writing() {
  // `--show` prints the resolved preset to stdout and writes nothing — so a
  // user can diff a preset against an existing config.
  let (dir, _repo) = init_repo();
  let cfg_path = dir.path().join(".gwm.toml");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["init", "--preset", "rust", "--show"])
    .assert()
    .success()
    .stdout(predicate::str::contains("[[bootstrap.no_symlink]]"))
    .stdout(predicate::str::contains("target"));

  assert!(!cfg_path.exists(), "--show must not write .gwm.toml to disk");
}

#[test]
fn init_preset_writes_stack_config() {
  // `--preset laravel` seeds the opinionated stack config: the AWS-RDS guard
  // and the vendor/ no-symlink are the markers that distinguish it from the
  // generic template.
  let (dir, _repo) = init_repo();
  let cfg_path = dir.path().join(".gwm.toml");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["init", "--preset", "laravel"])
    .assert()
    .success()
    .stdout(predicate::str::contains(".gwm.toml"));

  let body = std::fs::read_to_string(&cfg_path).unwrap();
  assert!(body.contains("no-aws-rds"), "laravel preset missing the AWS-RDS guard");
  assert!(body.contains("vendor"), "laravel preset missing the vendor no-symlink");
}

#[test]
fn init_unknown_preset_fails() {
  // An unknown preset name must fail loudly and point the user at
  // `--list-presets` rather than silently writing the generic template.
  let (dir, _repo) = init_repo();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["init", "--preset", "cobol"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("cobol"))
    .stderr(predicate::str::contains("list-presets"));
}

#[test]
fn init_preset_nuxt_alias_writes_node_body() {
  // `nuxt` is an alias of `node`: it must seed the node_modules no-symlink.
  let (dir, _repo) = init_repo();
  let cfg_path = dir.path().join(".gwm.toml");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["init", "--preset", "nuxt"])
    .assert()
    .success();

  let body = std::fs::read_to_string(&cfg_path).unwrap();
  assert!(body.contains("node_modules"), "nuxt alias must seed the node preset");
}

// --- create -------------------------------------------------------------

/// Write a `.gwm.toml` that redirects `[worktree].base` into the test's
/// own `TempDir`. The caller already owns the `base` path (it's the
/// `TempDir` they passed in), so the test asserts on `base.join(...)`
/// directly — this helper has no return value. Bootstrap is left empty
/// by default so `gwm create` runs in its minimal shape; tests that
/// need bootstrap behaviour layer a second `.gwm.toml` write on top.
fn write_test_config(repo_root: &Path, base: &Path) {
  let body = format!(
    r#"
[worktree]
base = "{base}"
path_pattern = "{{type}}-{{issue}}-{{desc}}"
branch_pattern = "{{type}}/#{{issue}}-{{desc}}"
"#,
    base = toml_basic_string(base),
  );
  std::fs::write(repo_root.join(".gwm.toml"), body).unwrap();
}

fn toml_basic_string(path: &Path) -> String {
  path.display().to_string().replace('\\', "\\\\").replace('"', "\\\"")
}

fn prepend_path(dir: &Path) -> String {
  let old = std::env::var_os("PATH").unwrap_or_default();
  let mut paths = vec![dir.to_path_buf()];
  paths.extend(std::env::split_paths(&old));
  std::env::join_paths(paths).unwrap().to_string_lossy().into_owned()
}

/// Fake `gh` that dispatches on the first two args, used to exercise the
/// PR auto-detection path (issue #181): `gh pr list …` returns
/// `pr_list_json`, `gh pr view …` returns `pr_view_json`. Both arms emit
/// the JSON verbatim so the real `find_pr_for_branch` / `fetch_pr` parse
/// it. Unix + Windows variants so CI stays green on both.
fn write_dispatch_gh(root: &Path, pr_list_json: &str, pr_view_json: &str) -> PathBuf {
  #[cfg(unix)]
  {
    let script = root.join("gh");
    fs::write(
      &script,
      format!(
        r#"#!/bin/sh
if [ "$1" = "pr" ] && [ "$2" = "list" ]; then
  printf '%s' '{list}'
elif [ "$1" = "pr" ] && [ "$2" = "view" ]; then
  printf '%s' '{view}'
fi
"#,
        list = pr_list_json.replace('\'', "'\\''"),
        view = pr_view_json.replace('\'', "'\\''"),
      ),
    )
    .unwrap();
    let mut perms = fs::metadata(&script).unwrap().permissions();
    use std::os::unix::fs::PermissionsExt;
    perms.set_mode(0o755);
    fs::set_permissions(&script, perms).unwrap();
    script
  }
  #[cfg(windows)]
  {
    let script = root.join("gh.cmd");
    fs::write(
      &script,
      format!(
        "@echo off\r\nif \"%~1\"==\"pr\" if \"%~2\"==\"list\" echo {list}\r\nif \"%~1\"==\"pr\" if \"%~2\"==\"view\" echo {view}\r\n",
        list = pr_list_json,
        view = pr_view_json,
      ),
    )
    .unwrap();
    script
  }
}

/// A fake `glab` that records how it was invoked before answering.
///
/// The existing fakes only stub stdout, which is enough to test parsing
/// but blind to the contract nine review rounds kept breaking: *which*
/// binary gets picked, *where* it runs, and *what environment* it
/// inherits. This one appends `ARGV` / `CWD` / the targeting variables
/// to `$GWM_FAKE_LOG`, so a test can assert the spawn itself.
///
/// Unix-only on purpose: the contract under test (argv, cwd, child
/// environment) is platform-independent in gwm's own code, whereas a
/// `.cmd` shim would mostly exercise `cmd.exe` quoting rules.
#[cfg(unix)]
fn write_recording_glab(root: &Path, mr_list_json: &str, api_json: &str) -> PathBuf {
  let script = root.join("glab");
  fs::write(
    &script,
    format!(
      r#"#!/bin/sh
{{
  echo "ARGV:$*"
  echo "CWD:$(pwd)"
  echo "GITLAB_HOST:${{GITLAB_HOST-<unset>}}"
  echo "GITLAB_REPO:${{GITLAB_REPO-<unset>}}"
  echo "GITLAB_GROUP:${{GITLAB_GROUP-<unset>}}"
  echo "GITLAB_API_HOST:${{GITLAB_API_HOST-<unset>}}"
  echo "GL_HOST:${{GL_HOST-<unset>}}"
  echo "API_PROTOCOL:${{API_PROTOCOL-<unset>}}"
  echo "GITLAB_TOKEN:${{GITLAB_TOKEN-<unset>}}"
  echo "GLAB_DEBUG_HTTP:${{GLAB_DEBUG_HTTP-<unset>}}"
}} >> "$GWM_FAKE_LOG"
if [ "$1" = "mr" ] && [ "$2" = "list" ]; then
  printf '%s' '{list}'
elif [ "$1" = "api" ]; then
  # Drain the request body so a test can assert what travelled on the
  # pipe rather than on the command line (issue #459).
  cat > "$GWM_FAKE_STDIN"
  printf '%s' '{api}'
fi
"#,
      list = mr_list_json.replace('\'', "'\\''"),
      api = api_json.replace('\'', "'\\''"),
    ),
  )
  .unwrap();
  let mut perms = fs::metadata(&script).unwrap().permissions();
  use std::os::unix::fs::PermissionsExt;
  perms.set_mode(0o755);
  fs::set_permissions(&script, perms).unwrap();
  script
}

fn write_fake_gh(root: &Path, issue_url: &str) -> PathBuf {
  #[cfg(unix)]
  {
    write_unix_fake_gh(root, issue_url)
  }
  #[cfg(windows)]
  {
    write_windows_fake_gh(root, issue_url)
  }
}

#[cfg(unix)]
fn write_unix_fake_gh(root: &Path, issue_url: &str) -> PathBuf {
  let script = root.join("gh");
  fs::write(
    &script,
    format!(
      r#"#!/bin/sh
printf '%s\n' "$*" > '{args}'
body_file=""
prev=""
for arg in "$@"; do
  if [ "$prev" = "--body-file" ]; then
    body_file="$arg"
  fi
  prev="$arg"
done
if [ -n "$body_file" ]; then
  cp "$body_file" '{body}'
fi
printf '%s' '{url}'
"#,
      args = root.join("gh-args.txt").display(),
      body = root.join("gh-body.md").display(),
      url = issue_url.replace('\'', "'\\''"),
    ),
  )
  .unwrap();
  let mut perms = fs::metadata(&script).unwrap().permissions();
  use std::os::unix::fs::PermissionsExt;
  perms.set_mode(0o755);
  fs::set_permissions(&script, perms).unwrap();
  script
}

#[cfg(windows)]
fn write_windows_fake_gh(root: &Path, issue_url: &str) -> PathBuf {
  let script = root.join("gh.cmd");
  fs::write(
    &script,
    format!(
      r#"@echo off
echo %* > "{args}"
:scan
if "%~1"=="" goto done
if "%~1"=="--body-file" (
  copy "%~2" "{body}" > nul
)
shift
goto scan
:done
echo {url}
"#,
      args = root.join("gh-args.txt").display(),
      body = root.join("gh-body.md").display(),
      url = issue_url.trim(),
    ),
  )
  .unwrap();
  script
}

#[test]
fn test_config_base_path_is_escaped_for_toml_basic_strings() {
  assert_eq!(
    toml_basic_string(Path::new(r#"C:\Users\runner\AppData\Local\Temp"#)),
    r#"C:\\Users\\runner\\AppData\\Local\\Temp"#
  );
}

#[test]
fn create_adds_worktree_dir_and_branch_at_head() {
  // The full happy path through `cmd_create`:
  //   1. The dirname rendered from `[worktree].path_pattern` lands on disk
  //      under the configured `[worktree].base`.
  //   2. The branch rendered from `[worktree].branch_pattern` is created
  //      as a local ref pointing at the seed commit (`init_repo`'s HEAD).
  //   3. `branch.<name>.gwm-base` is recorded as the parent's short name
  //      (the launcher fallback chain depends on it — issue #75).
  let (dir, repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());
  let head_oid = repo.head().unwrap().target().unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    // Issue #95: this test writes a `.gwm.toml` and runs `gwm
    // create` non-interactively, so the TOFU prompt would block.
    // Setting GWM_ALLOW_BOOTSTRAP=1 is the documented CI bypass.
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "42", "tui-search"])
    .assert()
    .success()
    .stdout(predicate::str::contains("feat/#42-tui-search"))
    .stdout(predicate::str::contains("worktree created"));

  let wt_dir = base.path().join("feat-42-tui-search");
  assert!(wt_dir.exists(), "worktree dir must exist on disk");
  assert!(wt_dir.join(".git").exists(), "worktree must carry a .git pointer");

  let branch = repo
    .find_branch("feat/#42-tui-search", git2::BranchType::Local)
    .expect("branch must be created");
  let branch_oid = branch.into_reference().target().unwrap();
  assert_eq!(branch_oid, head_oid, "fresh branch must point at the main HEAD commit");

  let cfg = repo.config().unwrap();
  let recorded_base = cfg.get_string("branch.feat/#42-tui-search.gwm-base").unwrap();
  assert_eq!(
    recorded_base, "main",
    "gwm create must record the parent ref for the launcher fallback chain"
  );
}

#[test]
fn create_runs_bootstrap_by_default() {
  // A `[[bootstrap.copy]]` step lands its destination file inside the
  // freshly-created worktree iff bootstrap actually ran. The source file
  // lives in the main repo's workdir; we pin a unique marker string so a
  // false positive (e.g. a cargo lock file collision) can't pass the
  // assertion by accident.
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  let marker = "GWM_E2E_BOOTSTRAP_MARKER_v1";
  std::fs::write(dir.path().join("seed.env"), marker).unwrap();
  let body = format!(
    r#"
[worktree]
base = "{base}"
path_pattern = "{{type}}-{{issue}}-{{desc}}"
branch_pattern = "{{type}}/#{{issue}}-{{desc}}"

[[bootstrap.copy]]
from = "seed.env"
to = "seed.env"
required = true
"#,
    base = toml_basic_string(base.path()),
  );
  std::fs::write(dir.path().join(".gwm.toml"), body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    // Issue #95: bypass the TOFU prompt — the test's whole point
    // is to assert that bootstrap.copy actually runs, which is
    // gated behind the trust check.
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "7", "bootstrap-on"])
    .assert()
    .success();

  let copied = base.path().join("feat-7-bootstrap-on").join("seed.env");
  assert!(copied.exists(), "bootstrap copy step did not run");
  let body = std::fs::read_to_string(&copied).unwrap();
  assert!(
    body.contains(marker),
    "bootstrap copy must duplicate the source file content"
  );
}

#[test]
fn create_runs_lifecycle_hooks_and_legacy_bootstrap_command_alias() {
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  let body = format!(
    r#"
[worktree]
base = "{base}"
path_pattern = "{{type}}-{{issue}}-{{desc}}"
branch_pattern = "{{type}}/#{{issue}}-{{desc}}"

[[hooks.pre_create]]
name = "record pre-create"
run = "printf pre-{{branch}}-{{issue}}-{{desc}} > pre-create.txt"

[[hooks.post_create]]
name = "record post-create"
run = "printf post-{{branch}} > post-create.txt"

[[bootstrap.command]]
name = "legacy post-create"
run = "printf legacy > legacy-post-create.txt"
"#,
    base = toml_basic_string(base.path()),
  );
  std::fs::write(dir.path().join(".gwm.toml"), body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "88", "hooks"])
    .assert()
    .success()
    .stdout(predicate::str::contains("[pre_create] record pre-create"))
    .stdout(predicate::str::contains("[post_create] record post-create"))
    .stdout(predicate::str::contains("[post_create] legacy post-create"));

  let worktree = base.path().join("feat-88-hooks");
  assert_eq!(
    std::fs::read_to_string(dir.path().join("pre-create.txt")).unwrap(),
    "pre-feat/#88-hooks-88-hooks"
  );
  assert_eq!(
    std::fs::read_to_string(worktree.join("post-create.txt")).unwrap(),
    "post-feat/#88-hooks"
  );
  assert_eq!(
    std::fs::read_to_string(worktree.join("legacy-post-create.txt")).unwrap(),
    "legacy"
  );
}

#[test]
fn new_creates_issue_from_template_then_creates_worktree() {
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  let fake_bin = tempfile::TempDir::new().unwrap();
  let fake_gh = write_fake_gh(fake_bin.path(), "https://github.com/acme/widgets/issues/142\n");
  fs::create_dir_all(dir.path().join(".github/ISSUE_TEMPLATE")).unwrap();
  fs::write(
    dir.path().join(".github/ISSUE_TEMPLATE/feature_request.yml"),
    r#"
name: Feature
title: "[Feature]: "
labels: ["feature"]
body:
  - type: markdown
    attributes:
      value: |
        Feature request for {desc}
  - type: dropdown
    id: surface
    attributes:
      label: Surface
      options:
        - cli
        - tui
  - type: textarea
    id: proposal
    attributes:
      label: Proposed solution
      placeholder: "Implement {type}"
"#,
  )
  .unwrap();
  let body = format!(
    r#"
[worktree]
base = "{base}"
path_pattern = "{{type}}-{{issue}}-{{desc}}"
branch_pattern = "{{type}}/#{{issue}}-{{desc}}"

[issue_template]
default = "feature_request.yml"

[issue_template.by_type]
feat = {{ template = "feature_request.yml", surface = "cli", title_prefix = "[Feature]: ", labels = ["enhancement"] }}
"#,
    base = toml_basic_string(base.path()),
  );
  fs::write(dir.path().join(".gwm.toml"), body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .env("GWM_GH", &fake_gh)
    .env("PATH", prepend_path(fake_bin.path()))
    .args(["new", "feat", "add-config-types", "--no-bootstrap"])
    .assert()
    .success()
    .stdout(predicate::str::contains("created issue #142"))
    .stdout(predicate::str::contains("feat/#142-add-config-types"))
    .stdout(predicate::str::contains("worktree created"));

  assert!(base.path().join("feat-142-add-config-types").exists());
  let gh_args_raw = fs::read_to_string(fake_bin.path().join("gh-args.txt")).unwrap();
  // `cmd.exe`'s `echo %*` keeps the surrounding quotes on quoted args, so
  // normalise by stripping them before doing substring assertions.
  let gh_args = gh_args_raw.replace('"', "");
  assert!(gh_args.contains("issue create"), "{gh_args_raw}");
  assert!(gh_args.contains("--title [Feature]: add-config-types"), "{gh_args_raw}");
  assert!(gh_args.contains("--label feature"), "{gh_args_raw}");
  assert!(gh_args.contains("--label enhancement"), "{gh_args_raw}");
  let gh_body = fs::read_to_string(fake_bin.path().join("gh-body.md")).unwrap();
  assert!(gh_body.contains("Feature request for add-config-types"), "{gh_body}");
  assert!(gh_body.contains("**Surface:** cli"), "{gh_body}");
  assert!(gh_body.contains("Implement feat"), "{gh_body}");
}

#[test]
fn create_pre_create_abort_failure_leaves_no_worktree() {
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  let body = format!(
    r#"
[worktree]
base = "{base}"
path_pattern = "{{type}}-{{issue}}-{{desc}}"
branch_pattern = "{{type}}/#{{issue}}-{{desc}}"

[[hooks.pre_create]]
name = "block create"
run = "false"
on_fail = "abort"
"#,
    base = toml_basic_string(base.path()),
  );
  std::fs::write(dir.path().join(".gwm.toml"), body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "88", "blocked"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("hook pre_create 'block create' failed"));

  assert!(
    !base.path().join("feat-88-blocked").exists(),
    "pre_create abort must happen before worktree creation"
  );
}

#[test]
fn create_warn_and_ignore_hook_failures_do_not_abort() {
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  let body = format!(
    r#"
[worktree]
base = "{base}"
path_pattern = "{{type}}-{{issue}}-{{desc}}"
branch_pattern = "{{type}}/#{{issue}}-{{desc}}"

[[hooks.pre_create]]
name = "warn only"
run = "false"
on_fail = "warn"

[[hooks.pre_create]]
name = "ignore failure"
run = "false"
on_fail = "ignore"
"#,
    base = toml_basic_string(base.path()),
  );
  std::fs::write(dir.path().join(".gwm.toml"), body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "88", "nonfatal"])
    .assert()
    .success()
    .stdout(predicate::str::contains("! [pre_create] warn only"))
    .stdout(predicate::str::contains("· [pre_create] ignore failure"));

  assert!(base.path().join("feat-88-nonfatal").exists());
}

#[test]
fn create_skip_hooks_bypasses_named_phase() {
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  let body = format!(
    r#"
[worktree]
base = "{base}"
path_pattern = "{{type}}-{{issue}}-{{desc}}"
branch_pattern = "{{type}}/#{{issue}}-{{desc}}"

[[hooks.pre_create]]
name = "would block"
run = "false"
"#,
    base = toml_basic_string(base.path()),
  );
  std::fs::write(dir.path().join(".gwm.toml"), body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "88", "skip", "--skip-hooks", "pre_create"])
    .assert()
    .success();

  assert!(base.path().join("feat-88-skip").exists());
}

#[test]
fn bootstrap_runs_pre_and_post_bootstrap_hooks() {
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  let body = format!(
    r#"
[worktree]
base = "{base}"
path_pattern = "{{type}}-{{issue}}-{{desc}}"
branch_pattern = "{{type}}/#{{issue}}-{{desc}}"

[[hooks.pre_bootstrap]]
name = "before bootstrap"
run = "printf pre > pre-bootstrap.txt"

[[bootstrap.copy]]
from = "seed.txt"
to = "seed.txt"
required = true

[[hooks.post_bootstrap]]
name = "after bootstrap"
run = "printf post > post-bootstrap.txt"
"#,
    base = toml_basic_string(base.path()),
  );
  std::fs::write(dir.path().join(".gwm.toml"), body).unwrap();
  std::fs::write(dir.path().join("seed.txt"), "seed").unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["create", "feat", "88", "boot-hooks", "--no-bootstrap"])
    .assert()
    .success();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["bootstrap", "feat-88-boot-hooks"])
    .assert()
    .success()
    .stdout(predicate::str::contains("[pre_bootstrap] before bootstrap"))
    .stdout(predicate::str::contains("[post_bootstrap] after bootstrap"));

  let worktree = base.path().join("feat-88-boot-hooks");
  assert_eq!(
    std::fs::read_to_string(worktree.join("pre-bootstrap.txt")).unwrap(),
    "pre"
  );
  assert_eq!(std::fs::read_to_string(worktree.join("seed.txt")).unwrap(), "seed");
  assert_eq!(
    std::fs::read_to_string(worktree.join("post-bootstrap.txt")).unwrap(),
    "post"
  );
}

#[test]
fn remove_runs_pre_and_post_remove_hooks_and_force_skips_them() {
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["create", "feat", "88", "remove-hooks", "--no-bootstrap"])
    .assert()
    .success();

  let config = format!(
    r#"
[worktree]
base = "{base}"
path_pattern = "{{type}}-{{issue}}-{{desc}}"
branch_pattern = "{{type}}/#{{issue}}-{{desc}}"

[[hooks.pre_remove]]
name = "block remove"
run = "false"

[[hooks.post_remove]]
name = "cleanup"
run = "printf removed-{{branch}} > post-remove.txt"
"#,
    base = toml_basic_string(base.path()),
  );
  std::fs::write(dir.path().join(".gwm.toml"), config).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["remove", "remove-hooks"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("hook pre_remove 'block remove' failed"));
  assert!(base.path().join("feat-88-remove-hooks").exists());

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["remove", "remove-hooks", "--force"])
    .assert()
    .success();
  assert!(!base.path().join("feat-88-remove-hooks").exists());
  assert!(
    !dir.path().join("post-remove.txt").exists(),
    "--force must skip pre_remove and post_remove hooks"
  );
}

#[test]
fn create_skips_bootstrap_with_no_bootstrap_flag() {
  // Same scaffolding as the previous test, but `--no-bootstrap` must
  // short-circuit `bootstrap::run` BEFORE the copy step. The worktree
  // directory still appears (the branch + worktree are created first),
  // but `seed.env` is absent inside it. The stdout breadcrumb that
  // `cmd_create` prints when it skips makes the intent observable.
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  std::fs::write(dir.path().join("seed.env"), "marker").unwrap();
  let body = format!(
    r#"
[worktree]
base = "{base}"
path_pattern = "{{type}}-{{issue}}-{{desc}}"
branch_pattern = "{{type}}/#{{issue}}-{{desc}}"

[[bootstrap.copy]]
from = "seed.env"
to = "seed.env"
required = true
"#,
    base = toml_basic_string(base.path()),
  );
  std::fs::write(dir.path().join(".gwm.toml"), body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["create", "feat", "8", "bootstrap-off", "--no-bootstrap"])
    .assert()
    .success()
    .stdout(predicate::str::contains("skipped bootstrap"));

  let wt_dir = base.path().join("feat-8-bootstrap-off");
  assert!(wt_dir.exists(), "worktree dir must still be created");
  assert!(
    !wt_dir.join("seed.env").exists(),
    "--no-bootstrap must prevent the copy step from running"
  );
}

#[test]
fn create_rejects_unknown_branch_type() {
  // `BranchSpec::validate` rejects branch types outside the built-in /
  // configured allow-list before any filesystem operation. We must see
  // the failure surface on stderr with the offending value so the user
  // can grep their command history without re-running.
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["create", "blarg", "9", "nope"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("blarg"));

  assert!(
    !base.path().join("blarg-9-nope").exists(),
    "no worktree dir may be created when branch-type validation fails"
  );
}

#[test]
fn create_rejects_non_digit_issue() {
  // Issue must be digits-only — `abc` is rejected by `BranchSpec::new`
  // before any filesystem op. As with the unknown-branch-type test,
  // assert the no-side-effect invariant explicitly: the worktree dir
  // that *would* have been written (`<base>/feat-abc-thing`) must not
  // appear on disk. Otherwise a regression where validation runs
  // post-`worktree::add` could still satisfy a bare `.failure()` check
  // while leaving stray dirs behind.
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["create", "feat", "abc", "thing"])
    .assert()
    .failure();

  assert!(
    !base.path().join("feat-abc-thing").exists(),
    "no worktree dir may be created when issue-number validation fails"
  );
}

#[test]
fn create_refuses_stale_branch_without_reuse_flag() {
  // Issue #99 E2E. A pre-existing local branch of the same name must
  // surface `BranchExists` and refuse to create the worktree dir —
  // protecting the user from silently landing on whatever commit the
  // pre-existing ref points at. The error renders the stale tip's
  // OID and the `--reuse-branch` opt-in so the message is
  // self-explanatory.
  //
  // We pin the branch at the seed commit, THEN advance main by one
  // commit so the branch tip diverges from HEAD — the textbook
  // "stale" scenario from the issue. That divergence is what makes
  // the silent reuse a foot-gun in the first place, and asserting
  // the stale OID appears verbatim in stderr proves the error message
  // is grep-able for the value the user would otherwise be silently
  // attached to.
  let (dir, repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());

  let seed = repo.head().unwrap().peel_to_commit().unwrap();
  let stale_branch = repo.branch("feat/#99-stale", &seed, false).unwrap();
  let stale_oid = stale_branch.into_reference().target().unwrap().to_string();

  let sig = git2::Signature::now("gwm-test", "gwm@test").unwrap();
  let tree_id = repo.index().unwrap().write_tree().unwrap();
  let tree = repo.find_tree(tree_id).unwrap();
  repo
    .commit(Some("HEAD"), &sig, &sig, "advance main", &tree, &[&seed])
    .unwrap();
  let new_head = repo.head().unwrap().target().unwrap().to_string();
  assert_ne!(new_head, stale_oid, "precondition: HEAD must diverge from stale branch");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "99", "stale"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("feat/#99-stale"))
    .stderr(predicate::str::contains("--reuse-branch"))
    .stderr(predicate::str::contains(stale_oid.as_str()));

  assert!(
    !base.path().join("feat-99-stale").exists(),
    "no worktree dir may be created when the branch is refused"
  );
}

#[test]
fn create_reuses_stale_branch_with_flag() {
  // Companion to `create_refuses_stale_branch_without_reuse_flag`: the
  // `--reuse-branch` opt-in restores the legacy attach-to-existing
  // behaviour, and the worktree directory does get created.
  let (dir, repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());

  let head = repo.head().unwrap().peel_to_commit().unwrap();
  repo.branch("feat/#99-stale", &head, false).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "99", "stale", "--reuse-branch"])
    .assert()
    .success();

  assert!(
    base.path().join("feat-99-stale").exists(),
    "with --reuse-branch the worktree dir must be created against the stale branch"
  );
}

#[test]
fn create_subcommand_outside_git_repo_fails() {
  // The repo-bound contract: outside any git repo the standard
  // `NotInGitRepo` error wins, no worktree is touched. Named with the
  // `_subcommand_` infix to avoid colliding with the historical
  // `create_outside_git_repo_fails` test (line ~327) that — despite the
  // name — actually exercises `gwm list`.
  let dir = tempfile::TempDir::new().unwrap();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["create", "feat", "1", "x"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("not inside a git repository"));
}

// --- remove -------------------------------------------------------------

#[test]
fn remove_deletes_worktree_dir_and_keeps_branch_by_default() {
  // Without `--delete-branch`, `gwm remove` is the inverse of `gwm
  // create` for the on-disk directory only: the worktree dir disappears
  // (and so does its admin entry under `.git/worktrees/`), but the
  // local branch survives so the user can re-create the worktree from
  // it later. Stdout names the dir for visual confirmation.
  let (dir, repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1") // issue #95: TOFU bypass for the setup step
    .args(["create", "feat", "10", "remove-me"])
    .assert()
    .success();
  let wt_dir = base.path().join("feat-10-remove-me");
  assert!(wt_dir.exists());

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["remove", "remove-me"])
    .assert()
    .success()
    .stdout(predicate::str::contains("removed"));

  assert!(!wt_dir.exists(), "remove must delete the worktree directory");
  assert!(
    repo.find_branch("feat/#10-remove-me", git2::BranchType::Local).is_ok(),
    "remove without --delete-branch must keep the local branch"
  );
}

#[test]
fn remove_with_delete_branch_drops_branch() {
  // The `--delete-branch` flag drops the local branch in the same
  // command. The stdout breadcrumb names both the worktree dir and the
  // branch so two destructive operations are surfaced explicitly.
  let (dir, repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1") // issue #95: TOFU bypass for the setup step
    .args(["create", "feat", "11", "drop-branch"])
    .assert()
    .success();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["remove", "drop-branch", "--delete-branch"])
    .assert()
    .success()
    .stdout(predicate::str::contains("branch"))
    .stdout(predicate::str::contains("deleted"));

  assert!(
    repo
      .find_branch("feat/#11-drop-branch", git2::BranchType::Local)
      .is_err(),
    "--delete-branch must remove the local branch ref"
  );
}

#[test]
fn remove_unknown_pattern_fails() {
  // Fuzzy lookup must error loudly when nothing matches — silently
  // doing nothing would mask a user typo and leave them wondering why
  // their worktree is still around.
  let (dir, _repo) = init_repo();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["remove", "ghost"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("not found"));
}

#[test]
fn remove_outside_git_repo_fails() {
  let dir = tempfile::TempDir::new().unwrap();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["remove", "anything"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("not inside a git repository"));
}

// --- remove --dry-run / prune --dry-run (issue #31) ---------------------

#[test]
fn remove_dry_run_prints_plan_and_keeps_worktree_intact() {
  // Issue #31 contract for `gwm remove --dry-run`: resolve the pattern,
  // print the would-remove plan (name + path + branch), exit 0, do NOT
  // touch the worktree directory or the local branch. The user can pipe
  // the output into a confirmation script.
  let (dir, repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "31", "preview"])
    .assert()
    .success();
  let wt_dir = base.path().join("feat-31-preview");
  assert!(wt_dir.exists());

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["remove", "preview", "--dry-run"])
    .assert()
    .success()
    .stdout(predicate::str::contains("would remove"))
    .stdout(predicate::str::contains("feat-31-preview"))
    .stdout(predicate::str::contains("feat/#31-preview"));

  assert!(wt_dir.exists(), "--dry-run must not delete the worktree directory");
  assert!(
    repo.find_branch("feat/#31-preview", git2::BranchType::Local).is_ok(),
    "--dry-run must not delete the local branch"
  );
}

#[test]
fn remove_dry_run_with_delete_branch_flags_branch_deletion() {
  // When `--delete-branch` is combined with `--dry-run`, the plan must
  // surface that the branch would be deleted — without actually
  // dropping it. The user sees a single line that mirrors the live
  // command's would-do trail.
  let (dir, repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "32", "preview-drop"])
    .assert()
    .success();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["remove", "preview-drop", "--delete-branch", "--dry-run"])
    .assert()
    .success()
    .stdout(predicate::str::contains("would be deleted"));

  assert!(
    repo
      .find_branch("feat/#32-preview-drop", git2::BranchType::Local)
      .is_ok(),
    "--dry-run --delete-branch must not delete the local branch"
  );
}

#[test]
fn remove_dry_run_on_ambiguous_pattern_still_fails() {
  // Spec: an ambiguous pattern under `--dry-run` exits non-zero with the
  // candidate list — same error contract as the regular failure mode.
  // `--dry-run` only suppresses *destruction*, not resolution failures.
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "33", "ambiguous-one"])
    .assert()
    .success();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "34", "ambiguous-two"])
    .assert()
    .success();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["remove", "ambiguous", "--dry-run"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("ambiguous"));
}

#[test]
fn prune_dry_run_prints_plan_without_pruning() {
  // Issue #31 contract for `gwm prune --dry-run`: walk the worktree
  // list, detect prunable entries, print each (name + path + reason),
  // exit 0, and leave the admin entries in place. The follow-up
  // (non-dry-run) `gwm prune` is the destructive sibling.
  let (dir, repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "35", "stale"])
    .assert()
    .success();
  let wt_dir = base.path().join("feat-35-stale");
  assert!(wt_dir.exists());

  // Simulate a "working dir missing" prunable: delete the worktree
  // directory on disk WITHOUT going through `gwm remove`, so the admin
  // entry under `.git/worktrees/<name>` stays around and libgit2 flags
  // the worktree as prunable.
  std::fs::remove_dir_all(&wt_dir).unwrap();

  let admin_dir = dir.path().join(".git").join("worktrees").join("feat-35-stale");
  assert!(admin_dir.exists(), "precondition: admin entry must still exist");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["prune", "--dry-run"])
    .assert()
    .success()
    .stdout(predicate::str::contains("would prune"))
    .stdout(predicate::str::contains("feat-35-stale"));

  assert!(admin_dir.exists(), "--dry-run must not remove the prunable admin entry");
  assert!(
    repo.find_worktree("feat-35-stale").is_ok(),
    "--dry-run must leave libgit2's worktree list untouched"
  );
}

#[test]
fn prune_dry_run_reports_no_candidates_when_clean() {
  // Empty case: a clean repo has nothing to prune. The command exits 0
  // with a friendly "0 worktree(s) to prune" so scripts that pipe the
  // output get a stable signal instead of an empty stdout.
  let (dir, _repo) = init_repo();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["prune", "--dry-run"])
    .assert()
    .success()
    .stdout(predicate::str::contains("0 worktree"));
}

// --- trust ledger (issue #95) -------------------------------------------

#[test]
fn trust_help_lists_list_revoke_show() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["trust", "--help"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("list"))
    .stdout(predicate::str::contains("revoke"))
    .stdout(predicate::str::contains("show"));
}

#[test]
fn trust_list_empty_prints_zero_entries() {
  // Point GWM_TRUST_LEDGER at a freshly-created tempdir so we don't
  // clobber the user's real ~/.config/gwm/trust.toml and so the test
  // is hermetic on CI runners that have an empty $HOME.
  let dir = tempfile::TempDir::new().unwrap();
  let ledger = dir.path().join("trust.toml");
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_TRUST_LEDGER", &ledger)
    .args(["trust", "list"])
    .assert()
    .success()
    .stdout(predicate::str::contains("0 entries in trust ledger"));
}

#[test]
fn trust_show_when_absent_says_so() {
  let dir = tempfile::TempDir::new().unwrap();
  let ledger = dir.path().join("absent.toml");
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_TRUST_LEDGER", &ledger)
    .args(["trust", "show"])
    .assert()
    .success()
    .stdout(predicate::str::contains("file does not exist yet"));
}

#[test]
fn trust_revoke_no_matching_origin_is_a_no_op() {
  let dir = tempfile::TempDir::new().unwrap();
  let ledger = dir.path().join("trust.toml");
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_TRUST_LEDGER", &ledger)
    .args(["trust", "revoke", "git@github.com:foo/bar.git"])
    .assert()
    .success()
    .stdout(predicate::str::contains("0 entries matched"));
}

#[test]
fn trust_list_show_revoke_round_trip() {
  // Seed the ledger manually (we can't easily exercise the prompt
  // path from assert_cmd), then verify list → show → revoke all
  // reflect the same entry.
  use std::fs;
  let dir = tempfile::TempDir::new().unwrap();
  let ledger = dir.path().join("trust.toml");
  fs::write(
    &ledger,
    r#"[[entries]]
origin = "git@github.com:kbrdn1/gwm-cli.git"
config_sha = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
trusted_at = "2026-05-22T10:00:00Z"
trusted_by = "kylian@laptop"
"#,
  )
  .unwrap();

  // list ----------------------------------------------------------
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_TRUST_LEDGER", &ledger)
    .args(["trust", "list"])
    .assert()
    .success()
    .stdout(predicate::str::contains("git@github.com:kbrdn1/gwm-cli.git"))
    // Short sha (first 12) is what list renders.
    .stdout(predicate::str::contains("deadbeefdead"));

  // show prints the raw toml -------------------------------------
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_TRUST_LEDGER", &ledger)
    .args(["trust", "show"])
    .assert()
    .success()
    .stdout(predicate::str::contains("kylian@laptop"));

  // revoke removes it --------------------------------------------
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_TRUST_LEDGER", &ledger)
    .args(["trust", "revoke", "git@github.com:kbrdn1/gwm-cli.git"])
    .assert()
    .success()
    .stdout(predicate::str::contains("✓ revoked 1"));

  // and list is empty again --------------------------------------
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_TRUST_LEDGER", &ledger)
    .args(["trust", "list"])
    .assert()
    .success()
    .stdout(predicate::str::contains("0 entries"));
}

#[test]
fn allow_bootstrap_flag_is_global_and_documented() {
  // `--allow-bootstrap` is the CI bypass; if it ever stops being a
  // global flag (e.g. accidentally scoped to one subcommand), the
  // `gwm bootstrap --allow-bootstrap` invocation in user scripts
  // silently fails. Pin it down at the help level.
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["--help"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains("--allow-bootstrap"))
    .stdout(predicate::str::contains("--deny-bootstrap"));
}

#[test]
fn create_without_trust_in_non_interactive_aborts_cleanly() {
  // Black-box the TOFU gate at the CLI boundary: a fresh repo with
  // a `.gwm.toml` carrying any bootstrap surface, run from a
  // non-tty (assert_cmd's piped stdin), no `--allow-bootstrap`, no
  // ledger entry → must abort with a clear message rather than
  // silently running the bootstrap commands.
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    r#"[[bootstrap.command]]
name = "echo"
run  = "echo trapped"
"#,
  )
  .unwrap();

  let ledger_dir = tempfile::TempDir::new().unwrap();
  let ledger = ledger_dir.path().join("trust.toml");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_TRUST_LEDGER", &ledger)
    // No `GWM_ALLOW_BOOTSTRAP` env, no flag → must abort.
    .args(["create", "feat", "42", "trapped"])
    .assert()
    .failure()
    .stderr(
      predicate::str::contains("not in the trust ledger").or(predicate::str::contains("stdin is not interactive")),
    );
}

#[test]
fn create_with_allow_bootstrap_flag_bypasses_the_prompt() {
  // The `--allow-bootstrap` escape hatch is what makes scripted /
  // CI usage workable; this asserts the FLAG (not the env var)
  // actually short-circuits the trust gate. The env-var path is
  // covered by other tests that set GWM_ALLOW_BOOTSTRAP=1 — here
  // we exercise the clap-level wiring so a future refactor that
  // accidentally scopes the flag to one subcommand breaks loudly.
  //
  // `--no-bootstrap` is added so we don't actually shell out to
  // anything — the test is about the trust gate, not the bootstrap
  // step itself.
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    r#"[[bootstrap.command]]
name = "echo"
run  = "echo would-have-run"
"#,
  )
  .unwrap();

  let ledger_dir = tempfile::TempDir::new().unwrap();
  let ledger = ledger_dir.path().join("trust.toml");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_TRUST_LEDGER", &ledger)
    // No env-var bypass — the flag must do the work on its own.
    // `--allow-bootstrap` is a clap `global = true` flag declared on
    // `Cli`, so it MUST appear before the subcommand on the argv.
    .args(["--allow-bootstrap", "create", "feat", "42", "trapped", "--no-bootstrap"])
    .assert()
    .success();

  // The ledger MUST still be empty — Allow mode bypasses without
  // recording, so the next interactive run on the same machine
  // re-prompts. That's the "don't pollute the user's ledger from CI"
  // contract.
  assert!(
    !ledger.exists()
      || std::fs::read_to_string(&ledger).unwrap().contains("entries = []")
      || std::fs::read_to_string(&ledger).unwrap().is_empty()
  );
}

#[test]
fn create_with_gwm_allow_bootstrap_env_bypasses_the_prompt() {
  // Sibling of the previous test: same fixture, but exercise the
  // `GWM_ALLOW_BOOTSTRAP=1` env-var bypass with no flag. This is
  // the CI-runner code path — scripts can't always inject extra
  // args, so the env-var path has to keep working independently.
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    r#"[[bootstrap.command]]
name = "echo"
run  = "echo would-have-run"
"#,
  )
  .unwrap();

  let ledger_dir = tempfile::TempDir::new().unwrap();
  let ledger = ledger_dir.path().join("trust.toml");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_TRUST_LEDGER", &ledger)
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "42", "env-trapped", "--no-bootstrap"])
    .assert()
    .success();

  assert!(
    !ledger.exists()
      || std::fs::read_to_string(&ledger).unwrap().contains("entries = []")
      || std::fs::read_to_string(&ledger).unwrap().is_empty()
  );
}

#[test]
fn create_skips_trust_gate_when_bootstrap_surface_is_empty() {
  // A `.gwm.toml` that declares nothing executable (no copies, no
  // guards, no no_symlinks, no commands) carries no RCE risk —
  // prompting for trust in that case would just train the user to
  // mash `y`. Verify the gate is a silent no-op when the config has
  // only `[worktree]`.
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    format!(
      r#"[worktree]
base = "{base}"
path_pattern = "{{type}}-{{issue}}-{{desc}}"
branch_pattern = "{{type}}/#{{issue}}-{{desc}}"
"#,
      base = toml_basic_string(base.path()),
    ),
  )
  .unwrap();

  let ledger_dir = tempfile::TempDir::new().unwrap();
  let ledger = ledger_dir.path().join("trust.toml");

  // No --allow-bootstrap, no env bypass, no ledger entry, no tty —
  // the gate would normally abort. With an empty bootstrap surface
  // it must short-circuit and let the create proceed.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_TRUST_LEDGER", &ledger)
    .args(["create", "feat", "13", "empty-surface"])
    .assert()
    .success();

  // Ledger MUST stay untouched — the skip doesn't record anything.
  assert!(
    !ledger.exists(),
    "empty-surface short-circuit must not write to the ledger"
  );
}

#[test]
fn allow_bootstrap_succeeds_even_when_ledger_is_malformed() {
  // The whole point of `--allow-bootstrap` / `GWM_ALLOW_BOOTSTRAP=1`
  // is to be the unconditional CI escape hatch. A malformed
  // trust.toml on the CI host must NOT make the bypass fail — the
  // Allow check has to short-circuit before the ledger is touched.
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    "[[bootstrap.command]]\nname = \"x\"\nrun = \"true\"\n",
  )
  .unwrap();

  let ledger_dir = tempfile::TempDir::new().unwrap();
  let ledger = ledger_dir.path().join("trust.toml");
  std::fs::write(&ledger, b"this is not valid toml @@@@").unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_TRUST_LEDGER", &ledger)
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "99", "broken-ledger", "--no-bootstrap"])
    .assert()
    .success();
}

#[test]
fn deny_bootstrap_aborts_even_when_trusted() {
  // `--deny-bootstrap` is the forensic mode: even if the ledger
  // says the config is trusted, refuse to run bootstrap. Asserts
  // the precedence resolution in `resolve_trust_mode`.
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    "[[bootstrap.command]]\nname = \"x\"\nrun = \"true\"\n",
  )
  .unwrap();

  let ledger_dir = tempfile::TempDir::new().unwrap();
  let ledger = ledger_dir.path().join("trust.toml");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_TRUST_LEDGER", &ledger)
    .args(["--deny-bootstrap", "bootstrap"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("--deny-bootstrap"));
}

// --- aliases (issue #86) ------------------------------------------------

#[test]
fn aliases_help_lists_list() {
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd.args(["aliases", "--help"]);
  cmd.assert().success().stdout(predicate::str::contains("list"));
}

#[test]
fn aliases_list_prints_built_in_section_outside_repo() {
  // `aliases list` is read-only and must work outside a git repo —
  // built-in clap aliases are static and independent of any repo
  // config. The user fallback (`~/.config/gwm/aliases.toml`) is
  // silently empty when missing.
  let dir = tempfile::TempDir::new().unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    // Isolate the test from the developer's real `~/.config/gwm/aliases.toml`.
    .env("XDG_CONFIG_HOME", dir.path())
    .env("HOME", dir.path())
    .args(["aliases", "list"])
    .assert()
    .success()
    .stdout(predicate::str::contains("built-in:"))
    // Canonical built-in entries from `BUILT_IN_ALIASES`. Assert the full
    // formatted row (`  <name>  → <expansion>` with width-2 padding) rather
    // than a loose `contains("s")` — the latter matched incidental letters
    // in unrelated words (`aliases`, `built-ins`, …) and let the test pass
    // even when the `s → switch` row was missing or malformed.
    .stdout(predicate::str::contains("  s  → switch"))
    .stdout(predicate::str::contains("  cd → path"));
}

#[test]
fn aliases_list_prints_repo_aliases_with_source() {
  // `.gwm.toml` with `[aliases]` ⇒ `aliases list` surfaces them under
  // the `repo (.gwm.toml):` section.
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    r#"
[aliases]
wip = "create feat 0 wip"
ll = "list --format names"
"#,
  )
  .unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .env("XDG_CONFIG_HOME", dir.path())
    .env("HOME", dir.path())
    .args(["aliases", "list"])
    .assert()
    .success()
    .stdout(predicate::str::contains("repo (.gwm.toml)"))
    .stdout(predicate::str::contains("wip"))
    .stdout(predicate::str::contains("create feat 0 wip"))
    .stdout(predicate::str::contains("ll"))
    .stdout(predicate::str::contains("list --format names"));
}

#[test]
fn aliases_list_prints_user_aliases_with_source() {
  // `~/.config/gwm/aliases.toml` (XDG resolved via `$XDG_CONFIG_HOME`)
  // surfaces under the user section.
  let dir = tempfile::TempDir::new().unwrap();
  let user_cfg = dir.path().join("gwm");
  std::fs::create_dir_all(&user_cfg).unwrap();
  std::fs::write(
    user_cfg.join("aliases.toml"),
    r#"
[aliases]
copy = "path"
"#,
  )
  .unwrap();

  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .env("XDG_CONFIG_HOME", dir.path())
    .env("HOME", dir.path())
    .args(["aliases", "list"])
    .assert()
    .success()
    .stdout(predicate::str::contains("user"))
    .stdout(predicate::str::contains("aliases.toml"))
    .stdout(predicate::str::contains("copy"))
    .stdout(predicate::str::contains("path"));
}

#[test]
fn aliases_list_repo_overrides_user_for_same_name() {
  // When repo and user both declare the same alias, the repo entry
  // takes precedence at expansion time. `aliases list` still prints
  // BOTH sections so the user can see what's being shadowed.
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    r#"
[aliases]
copy = "path bar"
"#,
  )
  .unwrap();
  let user_cfg = dir.path().join("gwm");
  std::fs::create_dir_all(&user_cfg).unwrap();
  std::fs::write(
    user_cfg.join("aliases.toml"),
    r#"
[aliases]
copy = "path foo"
"#,
  )
  .unwrap();

  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .env("XDG_CONFIG_HOME", dir.path())
    .env("HOME", dir.path())
    .args(["aliases", "list"])
    .assert()
    .success()
    .stdout(predicate::str::contains("path bar"))
    .stdout(predicate::str::contains("path foo"));
}

#[test]
fn aliases_list_surfaces_shadow_error_with_alias_name() {
  // An invalid alias in `.gwm.toml` must fail `aliases list` with a
  // message naming the offending entry.
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    r#"
[aliases]
list = "create feat 0 wip"
"#,
  )
  .unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .env("XDG_CONFIG_HOME", dir.path())
    .env("HOME", dir.path())
    .args(["aliases", "list"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("list").and(predicate::str::contains("built-in")));
}

#[test]
fn alias_expansion_runs_built_in_subcommand() {
  // End-to-end expansion: declare `lst = "list --format names"`,
  // invoke `gwm lst` — must behave as `gwm list --format names`.
  // The repo has no worktrees yet so the names output is just empty.
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    r#"
[aliases]
lst = "list --format names"
"#,
  )
  .unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .env("XDG_CONFIG_HOME", dir.path())
    .env("HOME", dir.path())
    .arg("lst")
    .assert()
    .success();
}

#[test]
fn alias_expansion_preserves_trailing_user_args() {
  // `gwm typ` with `typ = "types"` plus a trailing `--help` must
  // surface clap's `types` help (or success), proving the trailing
  // arg made it through the expansion.
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    r#"
[aliases]
typ = "types"
"#,
  )
  .unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .env("XDG_CONFIG_HOME", dir.path())
    .env("HOME", dir.path())
    .args(["typ", "--help"])
    .assert()
    .success()
    .stdout(predicate::str::contains("branch types"));
}

#[test]
fn alias_does_not_shadow_built_in_subcommand_at_runtime() {
  // Even if a hostile `.gwm.toml` somehow tries to alias `types`,
  // the load gate refuses — `gwm types` always reaches the
  // built-in. This is the "defence in depth" pillar of the design.
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    r#"
[aliases]
types = "list"
"#,
  )
  .unwrap();
  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .env("XDG_CONFIG_HOME", dir.path())
    .env("HOME", dir.path())
    .args(["types"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("types"));
}

// --- argv robustness (issue #86 — Copilot follow-up) --------------------

#[cfg(unix)]
#[test]
fn binary_tolerates_non_utf8_argv() {
  // `std::env::args()` panics if any argv entry is non-UTF-8, which is
  // a regression vs. clap's default `args_os` handling. The binary
  // must NOT abort the process on a perfectly valid OS argv just
  // because someone passed bytes that don't decode as UTF-8.
  //
  // We don't care about the exit code per se — the contract is "no
  // panic, no SIGABRT". clap may legitimately reject the unknown
  // subcommand and exit non-zero (UsageError = 2), which is fine.
  // What we forbid is the process aborting before clap even sees
  // the args.
  use std::ffi::OsString;
  use std::os::unix::ffi::OsStringExt;

  let dir = tempfile::TempDir::new().unwrap();
  let invalid_utf8: OsString = OsString::from_vec(vec![0xff, 0xfe, 0x80]);

  let output = Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("XDG_CONFIG_HOME", dir.path())
    .env("HOME", dir.path())
    .arg(&invalid_utf8)
    .output()
    .expect("binary must launch");

  // Reject SIGABRT / SIGSEGV / SIGILL — anything that indicates the
  // process died on a signal rather than exited normally. On Unix,
  // signal deaths surface as `status.code() == None` from `assert_cmd`.
  assert!(
    output.status.code().is_some(),
    "binary died on a signal (likely a panic abort) when given non-UTF-8 argv; stderr={:?}",
    String::from_utf8_lossy(&output.stderr)
  );

  // Belt-and-suspenders: the stderr should not contain the libstd panic
  // banner for invalid UTF-8 in argv.
  let stderr = String::from_utf8_lossy(&output.stderr);
  assert!(
    !stderr.contains("invalid utf-8") && !stderr.contains("panicked at"),
    "binary panicked instead of gracefully handling non-UTF-8 argv: {}",
    stderr
  );
}

// --- Issue #29: gwm history + gwm undo --------------------------------------

/// Seed a journal file at `path` with a single recorded `remove` op
/// rooted at `repo_root` (canonical form). The OID is a synthetic 40-
/// char hex string the journal accepts verbatim — `gwm history` is a
/// read-only listing so it never resolves the OID against the object
/// DB, which means we don't need to seed a matching commit.
///
/// `repo_root` is escaped via `toml_basic_string` because Windows
/// paths (`\\?\C:\...`) contain backslashes that TOML treats as
/// escape sequences; without the escape the parser fails with
/// "missing escaped value, expected b, e, f, n, r, \\, …".
fn write_seed_history(path: &Path, repo_root: &Path, worktree: &str, branch: &str) {
  let body = format!(
    r#"[[op]]
ts = "2026-05-19T08:42:11Z"
kind = "remove"
worktree = "{worktree}"
branch = "{branch}"
branch_oid = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678"
path = "/tmp/cc-worktree/{worktree}"
deleted_branch = false
repo_root = "{repo_root}"
"#,
    repo_root = toml_basic_string(repo_root),
  );
  if let Some(parent) = path.parent() {
    std::fs::create_dir_all(parent).unwrap();
  }
  std::fs::write(path, body).unwrap();
}

#[test]
fn history_empty_journal_reports_no_ops() {
  // Empty case: a fresh repo with no recorded operations must print
  // a clear "no operations recorded" line and exit 0. Scripted callers
  // (e.g. `gwm history | head -n1`) need a stable signal — silent
  // stdout would force them to also check `$?` to disambiguate.
  let (dir, _) = init_repo();
  let tmp = tempfile::TempDir::new().unwrap();
  let history_file = tmp.path().join("history.toml");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_HISTORY_FILE", &history_file)
    .arg("history")
    .assert()
    .success()
    .stdout(predicate::str::contains("no operations recorded"));
}

#[test]
fn history_lists_recorded_remove_op() {
  // Happy path: a seeded journal with one `remove` op produces a
  // single-row listing carrying the worktree name. The exact
  // column shape is intentionally flexible — we pin only the
  // load-bearing tokens (kind = `remove`, worktree name) so the
  // formatter can evolve without test churn.
  let (dir, _) = init_repo();
  let repo_root = dir.path().canonicalize().unwrap();
  let tmp = tempfile::TempDir::new().unwrap();
  let history_file = tmp.path().join("history.toml");
  write_seed_history(&history_file, &repo_root, "feat-29-foo", "feat/#29-foo");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_HISTORY_FILE", &history_file)
    .arg("history")
    .assert()
    .success()
    .stdout(predicate::str::contains("remove"))
    .stdout(predicate::str::contains("feat-29-foo"));
}

#[test]
fn history_filters_to_current_repo_by_default() {
  // Two ops recorded against two different repos. From inside
  // repo A, `gwm history` must surface ONLY the entry whose
  // `repo_root` matches the current repo — the per-repo
  // separation contract.
  let (dir, _) = init_repo();
  let repo_root = dir.path().canonicalize().unwrap();
  let tmp = tempfile::TempDir::new().unwrap();
  let history_file = tmp.path().join("history.toml");

  // Seed two ops: one for the current repo, one for a fake "other-repo"
  // path. Only the first should surface in the default listing.
  // `toml_basic_string` escapes the repo path for TOML — Windows
  // canonical paths (`\\?\C:\…`) would otherwise break the parser.
  let body = format!(
    r#"[[op]]
ts = "2026-05-19T08:42:11Z"
kind = "remove"
worktree = "feat-here-foo"
branch = "feat/#1-here"
branch_oid = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678"
path = "/tmp/cc-worktree/feat-here-foo"
deleted_branch = false
repo_root = "{repo_root}"

[[op]]
ts = "2026-05-19T09:00:00Z"
kind = "remove"
worktree = "feat-elsewhere-bar"
branch = "feat/#2-elsewhere"
branch_oid = "b2c3d4e5f60718293a4b5c6d7e8f9012345678a1"
path = "/tmp/cc-worktree/feat-elsewhere-bar"
deleted_branch = false
repo_root = "/nonexistent/other-repo"
"#,
    repo_root = toml_basic_string(&repo_root),
  );
  if let Some(parent) = history_file.parent() {
    std::fs::create_dir_all(parent).unwrap();
  }
  std::fs::write(&history_file, body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_HISTORY_FILE", &history_file)
    .arg("history")
    .assert()
    .success()
    .stdout(predicate::str::contains("feat-here-foo"))
    .stdout(predicate::str::contains("feat-elsewhere-bar").not());
}

#[test]
fn remove_records_journal_entry_before_destruction() {
  // Issue #29: `gwm remove <name>` must write a journal entry naming
  // the doomed worktree + branch + OID BEFORE the destructive call
  // runs. Without this hook `gwm undo` has nothing to replay. The
  // assertion is intentionally loose on the exact TOML shape — we
  // pin only that the journal file exists, is non-empty, and
  // contains the worktree name we asked to remove.
  let (dir, _) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  let history_dir = tempfile::TempDir::new().unwrap();
  let history_file = history_dir.path().join("history.toml");

  // Seed a worktree the test will then remove.
  let body = format!(
    r#"
[worktree]
base = "{base}"
path_pattern = "{{type}}-{{issue}}-{{desc}}"
branch_pattern = "{{type}}/#{{issue}}-{{desc}}"
"#,
    base = toml_basic_string(base.path()),
  );
  std::fs::write(dir.path().join(".gwm.toml"), body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .env("GWM_HISTORY_FILE", &history_file)
    .args(["create", "feat", "29", "doomed", "--no-bootstrap"])
    .assert()
    .success();

  // No journal entry should exist yet — `gwm create` does NOT hook
  // the journal (only destructive ops do).
  assert!(
    !history_file.exists() || std::fs::read_to_string(&history_file).unwrap().trim().is_empty(),
    "create must not record a journal entry"
  );

  // Now remove it — the journal must capture the op.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_HISTORY_FILE", &history_file)
    .args(["remove", "feat-29-doomed"])
    .assert()
    .success();

  assert!(
    history_file.exists(),
    "remove must create the journal file at {}",
    history_file.display()
  );
  let body = std::fs::read_to_string(&history_file).unwrap();
  assert!(
    body.contains("feat-29-doomed"),
    "journal must record the removed worktree name; got:\n{}",
    body
  );
  assert!(
    body.contains("kind = \"remove\""),
    "journal must record kind = remove; got:\n{}",
    body
  );
  assert!(
    body.contains("feat/#29-doomed"),
    "journal must record the branch name; got:\n{}",
    body
  );
}

#[test]
fn remove_dry_run_does_not_record_journal_entry() {
  // The dry-run flag (issue #31) gives the user a preview without
  // touching state. The journal hook MUST gate on the destructive
  // path only — a `--dry-run` invocation that wrote to the journal
  // would let the user "undo" something that never happened.
  let (dir, _) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  let history_dir = tempfile::TempDir::new().unwrap();
  let history_file = history_dir.path().join("history.toml");

  let body = format!(
    r#"
[worktree]
base = "{base}"
path_pattern = "{{type}}-{{issue}}-{{desc}}"
branch_pattern = "{{type}}/#{{issue}}-{{desc}}"
"#,
    base = toml_basic_string(base.path()),
  );
  std::fs::write(dir.path().join(".gwm.toml"), body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .env("GWM_HISTORY_FILE", &history_file)
    .args(["create", "feat", "31", "preview", "--no-bootstrap"])
    .assert()
    .success();

  // dry-run must not write to the journal.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_HISTORY_FILE", &history_file)
    .args(["remove", "feat-31-preview", "--dry-run"])
    .assert()
    .success();

  assert!(
    !history_file.exists() || std::fs::read_to_string(&history_file).unwrap().trim().is_empty(),
    "remove --dry-run must NOT write to the journal; got: {:?}",
    std::fs::read_to_string(&history_file).ok()
  );
}

#[test]
fn undo_recreates_branch_and_worktree_after_remove() {
  // The full round-trip contract: create → remove → undo. After
  // `gwm undo`, the worktree dir must exist again AND the local
  // branch must resolve. The journal entry must be consumed.
  let (dir, _) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  let history_dir = tempfile::TempDir::new().unwrap();
  let history_file = history_dir.path().join("history.toml");

  let body = format!(
    r#"
[worktree]
base = "{base}"
path_pattern = "{{type}}-{{issue}}-{{desc}}"
branch_pattern = "{{type}}/#{{issue}}-{{desc}}"
"#,
    base = toml_basic_string(base.path()),
  );
  std::fs::write(dir.path().join(".gwm.toml"), body).unwrap();

  // 1. Create.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .env("GWM_HISTORY_FILE", &history_file)
    .args(["create", "feat", "29", "undo-rt", "--no-bootstrap"])
    .assert()
    .success();
  let wt_path = base.path().join("feat-29-undo-rt");
  assert!(wt_path.exists(), "create must produce the worktree dir");

  // 2. Remove (with --delete-branch so we exercise the harder
  //    resurrection path).
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_HISTORY_FILE", &history_file)
    .args(["remove", "feat-29-undo-rt", "--delete-branch"])
    .assert()
    .success();
  assert!(!wt_path.exists(), "remove must drop the worktree dir");

  let repo = git2::Repository::open(dir.path()).unwrap();
  assert!(
    repo.find_branch("feat/#29-undo-rt", git2::BranchType::Local).is_err(),
    "remove --delete-branch must drop the local branch"
  );

  // 3. Undo. The branch must come back at the same OID, and the
  //    worktree dir must reappear.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_HISTORY_FILE", &history_file)
    .arg("undo")
    .assert()
    .success()
    .stdout(predicate::str::contains("recreated branch"))
    .stdout(predicate::str::contains("re-added worktree"));

  assert!(wt_path.exists(), "undo must restore the worktree dir");
  let repo = git2::Repository::open(dir.path()).unwrap();
  assert!(
    repo.find_branch("feat/#29-undo-rt", git2::BranchType::Local).is_ok(),
    "undo must recreate the local branch"
  );

  // 4. The journal entry is consumed — a second undo errors with
  //    "nothing to undo".
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_HISTORY_FILE", &history_file)
    .arg("undo")
    .assert()
    .failure()
    .stderr(predicate::str::contains("nothing to undo"));
}

#[test]
fn undo_bootstrap_without_trust_aborts() {
  // Issue #338: `gwm undo --bootstrap` must mediate the repo's
  // `[[bootstrap.command]]` shell through the SAME TOFU trust gate as
  // create / review / bootstrap. Before the fix, `cmd_undo` had no
  // `trust_mode` parameter and called `bootstrap::run` directly, so the
  // bootstrap commands ran unprompted on undo. Pin the gate at the CLI
  // boundary: create → remove → `undo --bootstrap` from a non-tty with
  // an empty ledger and no `GWM_ALLOW_BOOTSTRAP` must abort with the
  // trust message rather than silently running the bootstrap surface.
  let (dir, _) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  let history_dir = tempfile::TempDir::new().unwrap();
  let history_file = history_dir.path().join("history.toml");
  let ledger_dir = tempfile::TempDir::new().unwrap();
  let ledger = ledger_dir.path().join("trust.toml");

  let body = format!(
    r#"
[worktree]
base = "{base}"
path_pattern = "{{type}}-{{issue}}-{{desc}}"
branch_pattern = "{{type}}/#{{issue}}-{{desc}}"

[[bootstrap.command]]
name = "trap"
run  = "echo trapped"
"#,
    base = toml_basic_string(base.path()),
  );
  std::fs::write(dir.path().join(".gwm.toml"), body).unwrap();

  // 1. Create — bypass the gate via the env var, skip the shell step.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .env("GWM_TRUST_LEDGER", &ledger)
    .env("GWM_HISTORY_FILE", &history_file)
    .args(["create", "feat", "338", "undo-trust", "--no-bootstrap"])
    .assert()
    .success();

  // 2. Remove — records the journal entry `undo` will replay.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_TRUST_LEDGER", &ledger)
    .env("GWM_HISTORY_FILE", &history_file)
    .args(["remove", "feat-338-undo-trust"])
    .assert()
    .success();

  // 3. `undo --bootstrap` with an empty ledger and no allow-bypass,
  //    from a non-tty → the trust gate must abort rather than running
  //    the `[[bootstrap.command]]` shell unprompted.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_TRUST_LEDGER", &ledger)
    .env("GWM_HISTORY_FILE", &history_file)
    .args(["undo", "--bootstrap"])
    .assert()
    .failure()
    .stderr(
      predicate::str::contains("not in the trust ledger").or(predicate::str::contains("stdin is not interactive")),
    );

  // 4. The gate runs BEFORE any resurrection (fail-fast), so a denied
  //    undo must leave the journal entry and worktree untouched — not
  //    half-apply then exit non-zero. The worktree must still be gone…
  let wt_path = base.path().join("feat-338-undo-trust");
  assert!(
    !wt_path.exists(),
    "a denied trust gate must NOT restore the worktree — undo must stay retryable"
  );

  // …and a follow-up `undo` (no --bootstrap → no gate) must still find
  //    the journal entry and restore the worktree, proving the denied
  //    run consumed nothing.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_TRUST_LEDGER", &ledger)
    .env("GWM_HISTORY_FILE", &history_file)
    .arg("undo")
    .assert()
    .success();
  assert!(
    wt_path.exists(),
    "retry undo must restore the worktree — the entry was preserved"
  );
}

#[test]
fn undo_refuses_detached_head_entry_with_clear_error() {
  // PR #155 Copilot review: a journal entry with `branch = ""` (the
  // serialised form of `branch: None`) flags a worktree that was
  // removed while on a detached HEAD. The pre-fix code fell back to
  // `branch_name = "HEAD"` and called `worktree::add`, which either
  // failed at the libgit2 level (invalid refname) or created a real
  // branch named "HEAD" — a foot-gun. The fix surfaces a clear
  // error message so the user knows the limitation and can file a
  // follow-up if it matters.
  //
  // We seed the journal directly with a `branch = ""` entry rather
  // than going through `gwm create / gwm remove` because the create
  // path always attaches a branch — there's no shortcut to a
  // detached-HEAD worktree from the CLI. The fixture matches what
  // serde produces for `Option<String>::None` once round-tripped
  // through TOML.
  let (dir, _) = init_repo();
  let repo_root = dir.path().canonicalize().unwrap();
  let tmp = tempfile::TempDir::new().unwrap();
  let history_file = tmp.path().join("history.toml");

  // Direct TOML seed without a `branch` key — serde will deserialise
  // it as `Option::None`, which is the detached-HEAD discriminator.
  let body = format!(
    r#"[[op]]
ts = "2026-05-19T08:42:11Z"
kind = "remove"
worktree = "feat-detached-foo"
branch_oid = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678"
path = "/tmp/cc-worktree/feat-detached-foo"
deleted_branch = false
repo_root = "{repo_root}"
"#,
    repo_root = toml_basic_string(&repo_root),
  );
  std::fs::write(&history_file, body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_HISTORY_FILE", &history_file)
    .arg("undo")
    .assert()
    .failure()
    .stderr(predicate::str::contains("detached-HEAD"));
}

#[test]
fn history_with_zero_limit_prints_nothing_but_does_not_lie() {
  // PR #155 Copilot review: `--limit 0` used to truncate the row list
  // to empty, which then triggered the "no operations recorded"
  // branch — factually wrong when ops exist, and breaks the scripted
  // signal callers rely on. The fix prints nothing and exits 0,
  // leaving the "no operations recorded" sentinel reserved for the
  // truly-empty case.
  let (dir, _) = init_repo();
  let repo_root = dir.path().canonicalize().unwrap();
  let tmp = tempfile::TempDir::new().unwrap();
  let history_file = tmp.path().join("history.toml");
  write_seed_history(&history_file, &repo_root, "feat-zero-foo", "feat/#1-zero");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_HISTORY_FILE", &history_file)
    .args(["history", "--limit", "0"])
    .assert()
    .success()
    .stdout(predicate::eq(""));
}

#[test]
fn undo_with_empty_journal_errors_clearly() {
  // A clean install with no recorded operations: `gwm undo` must
  // exit non-zero with a clear "nothing to undo" message — silent
  // success would mislead users into thinking the previous op was
  // already undone.
  let (dir, _) = init_repo();
  let history_dir = tempfile::TempDir::new().unwrap();
  let history_file = history_dir.path().join("history.toml");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_HISTORY_FILE", &history_file)
    .arg("undo")
    .assert()
    .failure()
    .stderr(predicate::str::contains("nothing to undo"));
}

#[test]
fn history_all_flag_surfaces_every_repo() {
  // `--all` opt-out from the per-repo filter: useful for power users
  // grepping the journal for forensic purposes. Both entries must
  // appear in the listing.
  let (dir, _) = init_repo();
  let repo_root = dir.path().canonicalize().unwrap();
  let tmp = tempfile::TempDir::new().unwrap();
  let history_file = tmp.path().join("history.toml");

  // `toml_basic_string` escapes the repo path for TOML so this seed
  // parses on Windows (canonical paths there start with `\\?\C:\…`).
  let body = format!(
    r#"[[op]]
ts = "2026-05-19T08:42:11Z"
kind = "remove"
worktree = "feat-here-foo"
branch = "feat/#1-here"
branch_oid = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678"
path = "/tmp/cc-worktree/feat-here-foo"
deleted_branch = false
repo_root = "{repo_root}"

[[op]]
ts = "2026-05-19T09:00:00Z"
kind = "remove"
worktree = "feat-elsewhere-bar"
branch = "feat/#2-elsewhere"
branch_oid = "b2c3d4e5f60718293a4b5c6d7e8f9012345678a1"
path = "/tmp/cc-worktree/feat-elsewhere-bar"
deleted_branch = false
repo_root = "/nonexistent/other-repo"
"#,
    repo_root = toml_basic_string(&repo_root),
  );
  std::fs::create_dir_all(history_file.parent().unwrap()).unwrap();
  std::fs::write(&history_file, body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_HISTORY_FILE", &history_file)
    .args(["history", "--all"])
    .assert()
    .success()
    .stdout(predicate::str::contains("feat-here-foo"))
    .stdout(predicate::str::contains("feat-elsewhere-bar"));
}

// --- gwm pr (issue #84) -------------------------------------------------

/// Build a `feat/#<issue>-<desc>` branch on top of `main` carrying one
/// extra commit so `git log main..HEAD` and `git diff --stat main..HEAD`
/// produce non-empty output for the `{commits}` and `{files_changed}`
/// placeholders. Switches the working tree to that branch.
fn make_feature_branch_with_commit(
  repo: &git2::Repository,
  workdir: &std::path::Path,
  branch: &str,
  filename: &str,
  contents: &str,
  message: &str,
) {
  let head = repo.head().unwrap().peel_to_commit().unwrap();
  let branch_ref = repo.branch(branch, &head, false).unwrap();
  let ref_name = branch_ref.into_reference().name().unwrap().to_string();
  repo.set_head(&ref_name).unwrap();
  repo
    .checkout_head(Some(git2::build::CheckoutBuilder::new().force()))
    .unwrap();

  let dest = workdir.join(filename);
  if let Some(parent) = dest.parent() {
    std::fs::create_dir_all(parent).unwrap();
  }
  std::fs::write(&dest, contents).unwrap();
  let mut index = repo.index().unwrap();
  index.add_path(std::path::Path::new(filename)).unwrap();
  index.write().unwrap();
  let tree_id = index.write_tree().unwrap();
  let tree = repo.find_tree(tree_id).unwrap();
  let sig = git2::Signature::now("gwm-test", "gwm@test").unwrap();
  repo.commit(Some("HEAD"), &sig, &sig, message, &tree, &[&head]).unwrap();
}

#[test]
fn pr_render_prints_body_with_placeholders_substituted() {
  // `gwm pr --render` resolves the template configured for the current
  // branch type, substitutes the placeholders against the current
  // branch's context (type / issue / desc / base / head / commits /
  // files_changed), and prints the rendered Markdown to stdout. It
  // never shells out to `gh` — the canonical pipe-friendly form is
  // `gwm pr --render | gh pr create --body-file -`.
  let (dir, repo) = init_repo();
  make_feature_branch_with_commit(
    &repo,
    dir.path(),
    "feat/#84-pr-templates",
    "docs/note.md",
    "hello pr\n",
    "✨ feat: pr templates",
  );

  let body = r###"
[pr_template.by_type.feat]
body = """
## Summary

{desc} (#{issue})

## Commits

{commits}

## Files changed

{files_changed}
"""
"###;
  std::fs::write(dir.path().join(".gwm.toml"), body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["pr", "--render"])
    .assert()
    .success()
    .stdout(predicate::str::contains("pr-templates (#84)"))
    .stdout(predicate::str::contains("- ✨ feat: pr templates"))
    .stdout(predicate::str::contains("docs/note.md"));
}

#[test]
fn pr_creates_pull_request_via_gh() {
  // `gwm pr` (no `--render`) renders the body, writes it to a temp
  // file, and shells out to `gh pr create --title … --body-file …
  // --head <branch>`. The fake gh prints a PR URL so the CLI can
  // surface the new number in stdout.
  let (dir, repo) = init_repo();
  make_feature_branch_with_commit(
    &repo,
    dir.path(),
    "feat/#84-pr-templates",
    "src/x.rs",
    "fn x() {}\n",
    "✨ feat: x",
  );

  let fake_bin = tempfile::TempDir::new().unwrap();
  let fake_gh = write_fake_gh(fake_bin.path(), "https://github.com/acme/widgets/pull/321\n");

  let body = r###"
[pr_template.by_type.feat]
body = "## Summary\n{desc} (#{issue})\n"
"###;
  std::fs::write(dir.path().join(".gwm.toml"), body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_GH", &fake_gh)
    .env("PATH", prepend_path(fake_bin.path()))
    .args(["pr"])
    .assert()
    .success()
    .stdout(predicate::str::contains("created PR #321"))
    .stdout(predicate::str::contains("https://github.com/acme/widgets/pull/321"));

  let gh_args_raw = std::fs::read_to_string(fake_bin.path().join("gh-args.txt")).unwrap();
  let gh_args = gh_args_raw.replace('"', "");
  assert!(gh_args.contains("pr create"), "{gh_args_raw}");
  assert!(gh_args.contains("--head feat/#84-pr-templates"), "{gh_args_raw}");
  let gh_body = std::fs::read_to_string(fake_bin.path().join("gh-body.md")).unwrap();
  assert!(gh_body.contains("pr-templates (#84)"), "{gh_body}");
}

#[cfg(unix)]
#[test]
fn pr_body_travels_on_stdin_and_never_reaches_the_glab_argv() {
  // Issue #459: `glab` has no `--body-file`, so the previous
  // `glab mr create --description "<body>"` published the whole rendered
  // document on the command line, readable by any local process through
  // `ps`. The creation path now goes through `glab api --input -`.
  //
  // The assertion is deliberately on the *recorded argv*, not on the
  // argv builder: a unit test on the builder cannot see a body that some
  // other layer appends later.
  let (dir, repo) = init_repo();
  repo.remote("origin", "https://gitlab.com/group/proj.git").unwrap();
  make_feature_branch_with_commit(
    &repo,
    dir.path(),
    "feat/#84-pr-templates",
    "src/x.rs",
    "fn x() {}\n",
    "✨ feat: x",
  );

  let fake_bin = tempfile::TempDir::new().unwrap();
  let log = fake_bin.path().join("calls.log");
  let stdin_dump = fake_bin.path().join("stdin.json");
  let fake_glab = write_recording_glab(
    fake_bin.path(),
    "[]",
    r#"{"iid":321,"web_url":"https://gitlab.com/group/proj/-/merge_requests/321"}"#,
  );

  std::fs::write(
    dir.path().join(".gwm.toml"),
    "[pr_template.by_type.feat]\nbody = \"## Summary\\nSUPER-SECRET-BODY (#{issue})\\n\"\n",
  )
  .unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_GLAB", &fake_glab)
    .env("GWM_FAKE_LOG", &log)
    .env("GWM_FAKE_STDIN", &stdin_dump)
    // Set by a user debugging something else entirely. It makes glab
    // dump full requests and responses — bodies included — to stderr,
    // which the transcript keeps and the error path quotes verbatim.
    .env("GLAB_DEBUG_HTTP", "1")
    .env("PATH", prepend_path(fake_bin.path()))
    .args(["pr"])
    .assert()
    .success()
    .stdout(predicate::str::contains("created MR #321"))
    .stdout(predicate::str::contains(
      "https://gitlab.com/group/proj/-/merge_requests/321",
    ));

  let calls = fs::read_to_string(&log).unwrap();
  assert!(
    !calls.contains("SUPER-SECRET-BODY"),
    "the body must not be visible in the argv: {calls}"
  );
  assert!(calls.contains("--input -"), "{calls}");
  assert!(
    calls.contains("GLAB_DEBUG_HTTP:<unset>"),
    "the HTTP debug dump would print the body straight back out: {calls}"
  );

  // ...and it must still actually arrive, or the test above would pass
  // just as well with the body silently dropped.
  let sent: serde_json::Value = serde_json::from_str(&fs::read_to_string(&stdin_dump).unwrap()).unwrap();
  assert!(
    sent["description"].as_str().unwrap().contains("SUPER-SECRET-BODY"),
    "{sent}"
  );
  assert_eq!(sent["source_branch"], "feat/#84-pr-templates");
}

#[test]
fn pr_draft_flag_is_forwarded_to_gh() {
  // `gwm pr --draft` passes `--draft` through to `gh pr create` so the
  // resulting PR opens as a draft instead of a normal review-ready PR.
  let (dir, repo) = init_repo();
  make_feature_branch_with_commit(
    &repo,
    dir.path(),
    "feat/#84-pr-templates",
    "src/y.rs",
    "fn y() {}\n",
    "✨ feat: y",
  );

  let fake_bin = tempfile::TempDir::new().unwrap();
  let fake_gh = write_fake_gh(fake_bin.path(), "https://github.com/acme/widgets/pull/777\n");

  let body = r###"
[pr_template.by_type.feat]
body = "draft body for {desc}"
"###;
  std::fs::write(dir.path().join(".gwm.toml"), body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_GH", &fake_gh)
    .env("PATH", prepend_path(fake_bin.path()))
    .args(["pr", "--draft"])
    .assert()
    .success()
    .stdout(predicate::str::contains("created PR #777"));

  let gh_args_raw = std::fs::read_to_string(fake_bin.path().join("gh-args.txt")).unwrap();
  let gh_args = gh_args_raw.replace('"', "");
  assert!(gh_args.contains("--draft"), "{gh_args_raw}");
}

#[test]
fn pr_falls_back_to_common_trunk_when_configured_trunks_do_not_resolve() {
  // If `[doctor].trunks` only lists refs that don't exist locally
  // (e.g. a repo customised the list but the trunk hasn't been
  // created yet, or the repo uses `master`), `gwm pr` must still
  // find a sensible base ref by walking the common trunk names
  // (`main` / `master` / `dev` / `develop` / `trunk`) before giving
  // up — otherwise `{commits}` / `{files_changed}` come out empty
  // and the user has no signal as to why (Copilot review on PR #164).
  let (dir, repo) = init_repo();
  make_feature_branch_with_commit(
    &repo,
    dir.path(),
    "feat/#84-fallback",
    "src/fallback.rs",
    "fn fb() {}\n",
    "✨ feat: fallback",
  );

  let body = r###"
[doctor]
trunks = ["nonexistent-trunk"]

[pr_template.by_type.feat]
body = "summary: {desc} (#{issue})\ncommits:\n{commits}\n"
"###;
  std::fs::write(dir.path().join(".gwm.toml"), body).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["pr", "--render"])
    .assert()
    .success()
    .stdout(predicate::str::contains("fallback (#84)"))
    .stdout(predicate::str::contains("- ✨ feat: fallback"));
}

#[test]
fn pr_errors_when_no_template_configured() {
  // Without any `[pr_template]` block in `.gwm.toml`, `gwm pr` exits
  // non-zero with a hint about the missing config — same shape as the
  // `gwm new` failure for an unconfigured branch type.
  let (dir, repo) = init_repo();
  make_feature_branch_with_commit(
    &repo,
    dir.path(),
    "feat/#84-pr-templates",
    "src/z.rs",
    "fn z() {}\n",
    "✨ feat: z",
  );
  std::fs::write(dir.path().join(".gwm.toml"), "").unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["pr", "--render"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("pr_template"))
    .stderr(predicate::str::contains("feat"));
}

// --- gwm tui keys (issue #87) -------------------------------------------

#[test]
fn tui_keys_lists_default_bindings() {
  // The bare invocation prints the full resolved keymap as a
  // human-readable table. Default surface ships with `down → j, Down`,
  // `top → g g`, `quit → q`, … — assert the canary rows so a regression
  // in the table layout or the defaults map fails loudly.
  let (dir, _) = init_repo();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["tui", "keys"])
    .assert()
    .success()
    .stdout(predicate::str::contains("down"))
    .stdout(predicate::str::contains("j"))
    .stdout(predicate::str::contains("top"))
    .stdout(predicate::str::contains("g g"))
    .stdout(predicate::str::contains("quit"))
    .stdout(predicate::str::contains("default"));
}

#[test]
fn tui_keys_marks_user_overrides_in_source_column() {
  // When the user overrides a binding via `[tui.keys]`, the source
  // column for that row flips from `default` to a non-default marker
  // (we use `.gwm.toml`). The other rows keep `default`.
  let (dir, _) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    r#"
[tui.keys]
down = ["Ctrl+n"]
"#,
  )
  .unwrap();

  let output = Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["tui", "keys"])
    .assert()
    .success()
    .get_output()
    .clone();

  let stdout = String::from_utf8(output.stdout).unwrap();
  // Find the `down` row and assert it carries the user-config marker.
  let down_line = stdout
    .lines()
    .find(|l| l.starts_with("down"))
    .unwrap_or_else(|| panic!("expected a `down` row in:\n{stdout}"));
  assert!(
    down_line.contains("Ctrl+n"),
    "expected `down` row to show the override, got: {down_line}"
  );
  assert!(
    down_line.contains(".gwm.toml"),
    "expected `down` row source to be `.gwm.toml`, got: {down_line}"
  );
  // `up` was not overridden — must still read as default.
  let up_line = stdout
    .lines()
    .find(|l| l.starts_with("up"))
    .unwrap_or_else(|| panic!("expected an `up` row in:\n{stdout}"));
  assert!(
    up_line.contains("default"),
    "expected `up` row source to stay `default`, got: {up_line}"
  );
}

// --- gwm theme list / show (issue #33) ----------------------------------

#[test]
fn theme_list_includes_builtin_presets() {
  // `gwm theme list` prints the names of every built-in preset
  // shipped by the binary. Catppuccin is the named example in the
  // issue; the exact catalogue can grow over time.
  let (dir, _) = init_repo();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["theme", "list"])
    .assert()
    .success()
    .stdout(predicate::str::contains("catppuccin"))
    .stdout(predicate::str::contains("claude-dark"));
}

#[test]
fn theme_show_claude_dark_emits_the_orange_accent_as_hex() {
  // The Claude dark port (#185) is RGB-based, so `theme show` must
  // render its accent as a copy-pasteable `#RRGGBB` string that
  // round-trips through the `[theme]` parser.
  let (dir, _) = init_repo();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["theme", "show", "claude-dark"])
    .assert()
    .success()
    .stdout(predicate::str::contains("[theme]"))
    .stdout(predicate::str::contains("#d4825d"));
}

#[test]
fn theme_show_emits_toml_block_users_can_copy() {
  // `gwm theme show catppuccin` dumps a `[theme]` block that, when
  // pasted into a `.gwm.toml`, reproduces the preset.
  let (dir, _) = init_repo();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["theme", "show", "catppuccin"])
    .assert()
    .success()
    .stdout(predicate::str::contains("[theme]"))
    .stdout(predicate::str::contains("focus"));
}

#[test]
fn theme_show_includes_name_and_path_chrome_roles() {
  // #210: the `name` / `path` chrome roles must be part of the dumpable
  // block so users can discover and override them like any other role.
  let (dir, _) = init_repo();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["theme", "show", "catppuccin"])
    .assert()
    .success()
    .stdout(predicate::str::contains("name         ="))
    .stdout(predicate::str::contains("path         ="));
}

#[test]
fn theme_show_includes_git_status_family_roles() {
  // #211: the staged / modified / untracked roles must be dumpable so
  // users can discover and override the working-tree colours.
  let (dir, _) = init_repo();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["theme", "show", "catppuccin"])
    .assert()
    .success()
    .stdout(predicate::str::contains("staged       ="))
    .stdout(predicate::str::contains("modified     ="))
    .stdout(predicate::str::contains("untracked    ="));
}

#[test]
fn theme_show_rejects_unknown_preset() {
  let (dir, _) = init_repo();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["theme", "show", "does-not-exist"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("does-not-exist"));
}

#[test]
fn theme_show_output_round_trips_through_gwm_toml() {
  // Copilot review on PR #168 caught that `Color::Indexed(n)` was
  // emitted as a bare integer, breaking the round-trip because
  // `ThemeConfig.overrides` is a `BTreeMap<String, String>` and
  // TOML integers won't deserialise as `String`. Pin the
  // round-trip contract end-to-end: capture stdout, drop the
  // first `preset = "…"` line (preset is a dedicated field, not
  // an override), write the rest as `.gwm.toml`, reload, assert
  // no error.
  let (dir, _) = init_repo();
  let output = Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["theme", "show", "catppuccin"])
    .assert()
    .success()
    .get_output()
    .clone();
  let toml_block = String::from_utf8(output.stdout).unwrap();
  // Pasting verbatim into a fresh `.gwm.toml` and reloading must
  // succeed — every value in the block has to be a TOML string.
  let target = dir.path().join(".gwm.toml");
  std::fs::write(&target, &toml_block).unwrap();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["doctor"])
    .assert()
    // doctor's exit code may be 0 or 1 depending on local env
    // (it's advisory). What matters is that the config parses —
    // a TOML parse error would produce a `failed` config check
    // and exit code 2 / a hard error before doctor runs. We
    // assert the absence of "invalid TOML" / "config error" in
    // stderr to pin the round-trip.
    .stderr(predicate::str::contains("invalid TOML").not())
    .stderr(predicate::str::contains("config error").not());
}

#[test]
fn tui_keys_lists_modal_contexts() {
  // Issue #219: the listing prints the contextual modal bindings under
  // their `[tui.keys.modal.<context>]` headings, including nested link stages.
  let (dir, _) = init_repo();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["tui", "keys"])
    .assert()
    .success()
    .stdout(predicate::str::contains("[tui.keys.modal.confirm]"))
    .stdout(predicate::str::contains("focus_confirm"))
    .stdout(predicate::str::contains("[tui.keys.modal.link.choose_target]"));
}

// --- exec / clean (issue #313) ------------------------------------------

/// Spin up a repo plus one non-main worktree via the real binary, so the
/// `exec` / `clean` tests exercise the actual worktree-discovery and
/// target-selection path (not just the pure helpers). Returns the main repo
/// tempdir, the worktree-base tempdir (kept alive), and the worktree path.
fn repo_with_one_worktree() -> (tempfile::TempDir, tempfile::TempDir, PathBuf) {
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  // Reuse the shared writer so the tempdir path is TOML-escaped (backslashes
  // on Windows CI would otherwise make `.gwm.toml` invalid).
  write_test_config(dir.path(), base.path());
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "1", "wt"])
    .assert()
    .success();
  let wt = base.path().join("feat-1-wt");
  assert!(wt.exists(), "worktree must exist for the exec/clean tests");
  (dir, base, wt)
}

#[test]
fn exec_runs_the_command_inside_each_worktree() {
  let (dir, _base, wt) = repo_with_one_worktree();
  // The command's CWD is the worktree, so the marker lands there — proving
  // discovery + per-worktree execution, not just a parse.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--", "sh", "-c", "echo hi > exec_marker.txt"])
    .assert()
    .success()
    .stdout(predicate::str::contains(""))
    .stdout(predicate::str::contains("feat-1-wt"));
  assert!(
    wt.join("exec_marker.txt").exists(),
    "the command must run with the worktree as its working directory"
  );
}

#[test]
fn exec_exits_nonzero_when_a_worktree_command_fails() {
  let (dir, _base, _wt) = repo_with_one_worktree();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--", "sh", "-c", "exit 5"])
    .assert()
    .failure()
    .stdout(predicate::str::contains(""))
    .stdout(predicate::str::contains("exit 5"));
}

/// Append a TOML snippet to the repo's `.gwm.toml` (the writer created by
/// `repo_with_one_worktree`), so a test can add `[exec.profiles.*]` /
/// `[clean.profiles.*]` entries on top of the base config.
fn append_config(repo_root: &Path, snippet: &str) {
  use std::io::Write;
  let mut f = std::fs::OpenOptions::new()
    .append(true)
    .open(repo_root.join(".gwm.toml"))
    .unwrap();
  writeln!(f, "{snippet}").unwrap();
}

// --- exec/clean named profiles (issue #324) ---------------------------------

#[test]
fn exec_runs_a_named_profile_command() {
  let (dir, _base, wt) = repo_with_one_worktree();
  append_config(
    dir.path(),
    "[exec.profiles.greet]\ncommand = [\"sh\", \"-c\", \"echo hi > prof_marker.txt\"]\n",
  );
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--profile", "greet"])
    .assert()
    .success()
    .stdout(predicate::str::contains(""));
  assert!(
    wt.join("prof_marker.txt").exists(),
    "the profile's command must run in the worktree"
  );
}

#[test]
fn exec_jobs_runs_the_parallel_capture_path() {
  // `--jobs > 1` runs the bounded-parallel path: each worktree's output is
  // captured and printed as a block (after its header), and the command still
  // runs and rolls up ✓.
  let (dir, _base, wt) = repo_with_one_worktree();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args([
      "exec",
      "--jobs",
      "2",
      "--",
      "sh",
      "-c",
      "echo blockline; echo hi > exec_jobs_marker.txt",
    ])
    .assert()
    .success()
    .stdout(predicate::str::contains("blockline")) // captured stdout printed as a block
    .stdout(predicate::str::contains("feat-1-wt"))
    .stdout(predicate::str::contains(""));
  assert!(
    wt.join("exec_jobs_marker.txt").exists(),
    "the command must still run under --jobs"
  );
}

#[test]
fn exec_jobs_preserves_raw_binary_output() {
  // The parallel path captures bytes, but must re-emit them RAW — a
  // `String::from_utf8_lossy` would mangle a non-UTF-8 byte (0xFF) into the
  // U+FFFD replacement char. `printf '\377'` emits a literal 0xFF.
  let (dir, _base, _wt) = repo_with_one_worktree();
  let out = Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--jobs", "2", "--", "printf", "\\377"])
    .output()
    .unwrap();
  assert!(out.status.success(), "exec should succeed: {out:?}");
  assert!(
    out.stdout.contains(&0xFFu8),
    "the raw 0xFF byte must survive the capture, not be UTF-8-mangled"
  );
}

#[test]
fn exec_inline_inside_bare_repo_does_not_require_a_workdir() {
  // A bare repo has no `workdir()`, so there's no `.gwm.toml` to read — but
  // inline `gwm exec` must still run (it enumerates worktrees, not config).
  // Regression: reading the `[exec] jobs` default must fall back gracefully
  // here instead of failing with `NotInGitRepo` (#324 review).
  let dir = tempfile::TempDir::new().unwrap();
  git2::Repository::init_bare(dir.path()).expect("init bare repo");
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--", "true"])
    .assert()
    .success()
    .stdout(predicate::str::contains("no worktrees to run in"));
}

#[test]
fn exec_jobs_flag_skips_config_when_inline() {
  // Inline + `--jobs`: the flag is authoritative and the command is on the
  // CLI, so `[exec]` is never read — a malformed sibling profile can't block
  // `gwm exec --jobs N -- <cmd>` (#324 review).
  let (dir, _base, _wt) = repo_with_one_worktree();
  append_config(dir.path(), "[exec.profiles.bad]\ncommand = []\n");
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--jobs", "2", "--", "true"])
    .assert()
    .success();
}

#[test]
fn exec_inline_jobs_default_tolerates_a_semantic_sibling_profile() {
  // Inline + no `--jobs`: the `[exec] jobs` default IS read, but sibling
  // profiles are NOT semantically validated (inline uses none of them), so a
  // `command = []` sibling doesn't block the inline run.
  let (dir, _base, _wt) = repo_with_one_worktree();
  append_config(dir.path(), "[exec]\njobs = 1\n[exec.profiles.bad]\ncommand = []\n");
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--", "true"])
    .assert()
    .success();
}

#[test]
fn exec_jobs_flag_parses_and_propagates_failure() {
  // The parallel path propagates a non-zero rollup just like sequential.
  let (dir, _base, _wt) = repo_with_one_worktree();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--jobs", "3", "--", "sh", "-c", "exit 4"])
    .assert()
    .failure()
    .stdout(predicate::str::contains(""))
    .stdout(predicate::str::contains("exit 4"));
}

#[test]
fn exec_inline_command_ignores_a_broken_gwm_toml() {
  // The inline `gwm exec -- <cmd>` surface is promised config-free: an
  // unrelated `.gwm.toml` error must NOT break it (it only reads config for
  // a `--profile` lookup). Here a stray top-level key would fail a config
  // load, yet the inline command still runs.
  let (dir, _base, _wt) = repo_with_one_worktree();
  append_config(dir.path(), "nonsense_key = true\n");
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--", "sh", "-c", "true"])
    .assert()
    .success();
}

#[test]
fn exec_profile_tolerates_an_unrelated_config_error() {
  // The `--profile` path reads only the `[exec]` section, so an UNRELATED
  // top-level typo is tolerated — the failure is the unknown profile, not the
  // typo (exit 1 either way, but for the right reason).
  let (dir, _base, _wt) = repo_with_one_worktree();
  append_config(dir.path(), "nonsense_key = true\n");
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--profile", "whatever"])
    .assert()
    .failure()
    .code(1)
    .stderr(predicate::str::contains("no profile named `whatever`"));
}

#[test]
fn exec_profile_surfaces_a_malformed_exec_section() {
  // A shape error in the `[exec]` section ITSELF still surfaces (exit 1):
  // an unknown field in a profile is rejected by `deny_unknown_fields`.
  let (dir, _base, _wt) = repo_with_one_worktree();
  append_config(dir.path(), "[exec.profiles.bad]\ncommand = [\"true\"]\nbogus = 1\n");
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--profile", "bad"])
    .assert()
    .failure()
    .code(1);
}

#[test]
fn exec_profile_and_inline_command_are_mutually_exclusive() {
  let (dir, _base, _wt) = repo_with_one_worktree();
  append_config(dir.path(), "[exec.profiles.t]\ncommand = [\"true\"]\n");
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--profile", "t", "--", "echo", "hi"])
    .assert()
    .failure()
    .code(1)
    .stderr(predicate::str::contains("mutually exclusive"));
}

#[test]
fn exec_unknown_profile_exits_one() {
  let (dir, _base, _wt) = repo_with_one_worktree();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--profile", "ghost"])
    .assert()
    .failure()
    .code(1)
    .stderr(predicate::str::contains("no profile named `ghost`"));
}

#[test]
fn clean_unknown_profile_exits_one() {
  let (dir, _base, _wt) = repo_with_one_worktree();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean", "--profile", "ghost"])
    .assert()
    .failure()
    .code(1)
    .stderr(predicate::str::contains("no profile named `ghost`"));
}

#[test]
fn clean_builtin_ignores_a_broken_gwm_toml() {
  // The built-in `gwm clean` (no `--profile`) is opt-in/config-tolerant: an
  // unrelated `.gwm.toml` error (a stray top-level key) must NOT block it —
  // only the `[clean]` section is read, so it falls back to the built-in dirs.
  let (dir, _base, _wt) = repo_with_one_worktree();
  append_config(dir.path(), "nonsense_key = true\n");
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean"])
    .assert()
    .success();
}

#[test]
fn clean_honors_default_profile_despite_an_unrelated_config_error() {
  // A configured `[clean.profiles.default]` must NOT be silently dropped
  // (reverting to the built-in set) just because an unrelated key is wrong —
  // that would make a destructive `--yes` delete the wrong set. The default
  // profile's `coverage` (only reclaimable under that profile) is reported.
  let (dir, _base, wt) = repo_with_one_worktree();
  std::fs::create_dir_all(wt.join("coverage")).unwrap();
  std::fs::write(wt.join("coverage/lcov.info"), vec![0u8; 2048]).unwrap();
  std::fs::write(wt.join(".gitignore"), "coverage/\n").unwrap();
  append_config(
    dir.path(),
    "nonsense_key = true\n[clean.profiles.default]\ndirs = [\"coverage\"]\n",
  );
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean"])
    .assert()
    .success()
    .stdout(predicate::str::contains("coverage"));
}

#[test]
fn clean_surfaces_a_malformed_clean_section() {
  // A shape error in the `[clean]` section ITSELF still surfaces (exit 1),
  // even without `--profile` — a profile missing its required `dirs` must not
  // be silently ignored before a destructive clean.
  let (dir, _base, _wt) = repo_with_one_worktree();
  append_config(dir.path(), "[clean.profiles.broken]\n");
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean"])
    .assert()
    .failure()
    .code(1);
}

#[test]
fn clean_rejects_a_sibling_invalid_profile() {
  // The `[clean]` loader validates EVERY profile, not just the selected one:
  // a sibling `bad` that escapes the worktree fails `--profile good` too, so
  // the command path matches `gwm config validate` / doctor (#324 review).
  let (dir, _base, _wt) = repo_with_one_worktree();
  append_config(
    dir.path(),
    "[clean.profiles.good]\ndirs = [\"target\"]\n[clean.profiles.bad]\ndirs = [\"..\"]\n",
  );
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean", "--profile", "good"])
    .assert()
    .failure()
    .code(1)
    .stderr(predicate::str::contains(".."));
}

#[test]
fn exec_rejects_a_sibling_invalid_profile() {
  // Same for `[exec]`: a sibling `bad` with an empty command fails
  // `--profile good`.
  let (dir, _base, _wt) = repo_with_one_worktree();
  append_config(
    dir.path(),
    "[exec.profiles.good]\ncommand = [\"true\"]\n[exec.profiles.bad]\ncommand = []\n",
  );
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--profile", "good"])
    .assert()
    .failure()
    .code(1)
    .stderr(predicate::str::contains("empty `command`"));
}

#[test]
fn clean_profile_with_an_unsafe_dir_exits_one() {
  // A `dirs` entry that could escape the worktree (here `..`) is refused at
  // resolution, before any filesystem scan — exit 1, nothing walked.
  let (dir, _base, _wt) = repo_with_one_worktree();
  append_config(dir.path(), "[clean.profiles.evil]\ndirs = [\"..\"]\n");
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean", "--profile", "evil"])
    .assert()
    .failure()
    .code(1)
    .stderr(predicate::str::contains("escape the worktree"));
}

#[test]
fn clean_named_profile_scopes_the_reclaim_to_its_dirs() {
  let (dir, _base, wt) = repo_with_one_worktree();
  // `coverage/` is only reclaimable under a profile that lists it; the
  // built-in set (target/node_modules/dist/build) would ignore it.
  std::fs::create_dir_all(wt.join("coverage")).unwrap();
  std::fs::write(wt.join("coverage/lcov.info"), vec![0u8; 2048]).unwrap();
  std::fs::write(wt.join(".gitignore"), "coverage/\n").unwrap();
  append_config(dir.path(), "[clean.profiles.cov]\ndirs = [\"coverage\"]\n");
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean", "--profile", "cov"])
    .assert()
    .success()
    .stdout(predicate::str::contains("coverage"));
}

#[test]
fn clean_reclaims_a_leading_dash_profile_dir() {
  // A profile dir whose name starts with `-` (e.g. `-cache`) must flow through
  // the git-ignored safety check correctly — the check passes `--` so git
  // doesn't parse the name as an option and wrongly skip it (#324 review P3).
  let (dir, _base, wt) = repo_with_one_worktree();
  std::fs::create_dir_all(wt.join("-cache")).unwrap();
  std::fs::write(wt.join("-cache/blob.bin"), vec![0u8; 2048]).unwrap();
  std::fs::write(wt.join(".gitignore"), "/-cache/\n").unwrap();
  append_config(dir.path(), "[clean.profiles.dash]\ndirs = [\"-cache\"]\n");
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean", "--profile", "dash", "--yes"])
    .assert()
    .success();
  assert!(
    !wt.join("-cache").exists(),
    "a git-ignored `-cache` profile dir must be reclaimed, not skipped"
  );
}

#[test]
fn clean_reports_artifacts_without_deleting_by_default() {
  let (dir, _base, wt) = repo_with_one_worktree();
  // target/ is git-ignored ⇒ deletable, so the dry-run preview counts it and
  // prompts to re-run — but report-only must not actually delete it.
  fs::write(wt.join(".gitignore"), "/target\n").unwrap();
  fs::create_dir_all(wt.join("target")).unwrap();
  fs::write(wt.join("target").join("blob.bin"), vec![0u8; 4096]).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean"])
    .assert()
    .success()
    .stdout(predicate::str::contains("target"))
    .stdout(predicate::str::contains("re-run with --yes"));

  assert!(wt.join("target").exists(), "report-only mode must not delete anything");
}

#[test]
fn clean_preview_excludes_non_deletable_dirs_from_total() {
  // A non-ignored dist/ must not be counted as reclaimable nor trigger the
  // "re-run with --yes" promise — the preview must match what --yes would do.
  let (dir, _base, wt) = repo_with_one_worktree();
  fs::create_dir_all(wt.join("dist")).unwrap();
  fs::write(wt.join("dist").join("keep.txt"), b"hand-authored").unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean"])
    .assert()
    .success()
    .stdout(predicate::str::contains("skipped"))
    .stdout(predicate::str::contains("dist"))
    .stdout(predicate::str::contains("nothing to reclaim"))
    .stdout(predicate::str::contains("re-run with --yes").not());
}

#[test]
fn clean_yes_deletes_gitignored_artifacts() {
  let (dir, _base, wt) = repo_with_one_worktree();
  // target/ is ignored ⇒ safe to reclaim.
  fs::write(wt.join(".gitignore"), "/target\n").unwrap();
  fs::create_dir_all(wt.join("target")).unwrap();
  fs::write(wt.join("target").join("blob.bin"), vec![0u8; 4096]).unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean", "--yes"])
    .assert()
    .success()
    .stdout(predicate::str::contains("reclaimed"));

  assert!(
    !wt.join("target").exists(),
    "a git-ignored target/ should be deleted with --yes"
  );
}

#[test]
fn clean_yes_refuses_to_delete_non_ignored_artifacts() {
  let (dir, _base, wt) = repo_with_one_worktree();
  // dist/ is NOT ignored (no matching rule) and holds hand-authored content;
  // the safety gate must skip it rather than destroy it.
  fs::create_dir_all(wt.join("dist")).unwrap();
  fs::write(wt.join("dist").join("keep.txt"), b"non-regenerable work").unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean", "--yes"])
    .assert()
    .success()
    .stdout(predicate::str::contains("skipped"))
    .stdout(predicate::str::contains("dist"));

  assert!(wt.join("dist").exists(), "a non-ignored dist/ must be preserved");
  assert!(
    wt.join("dist").join("keep.txt").exists(),
    "hand-authored content under a non-ignored dir must survive --yes"
  );
}

#[test]
fn clean_yes_refuses_ignored_dir_holding_tracked_files() {
  // git tracks files, not directories: a `dist/` ignore rule can coexist with
  // a force-added, committed `dist/index.html`. `check-ignore dist` succeeds,
  // but the dir holds tracked work — the gate must still skip it.
  let (dir, _base, wt) = repo_with_one_worktree();
  fs::write(wt.join(".gitignore"), "/dist\n").unwrap();
  fs::create_dir_all(wt.join("dist")).unwrap();
  fs::write(wt.join("dist").join("index.html"), b"tracked output").unwrap();
  // Force-track the file despite the ignore rule.
  std::process::Command::new("git")
    .current_dir(&wt)
    .args(["add", "-f", "dist/index.html"])
    .status()
    .expect("git add -f");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean", "--yes"])
    .assert()
    .success()
    .stdout(predicate::str::contains("skipped"))
    .stdout(predicate::str::contains("dist"));

  assert!(
    wt.join("dist").join("index.html").exists(),
    "a tracked file under an ignored dir must survive --yes"
  );
}

/// Run `git <args>` in `dir`, asserting success — fixture setup helper.
fn git_at(dir: &Path, args: &[&str]) {
  // Pin signing off so a developer with `commit.gpgsign=true` (or a missing
  // signing key) in their ambient git config doesn't make these fixtures fail
  // before `gwm` is even exercised (#326 review).
  let ok = std::process::Command::new("git")
    .current_dir(dir)
    .args(["-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false"])
    .args(args)
    .status()
    .unwrap()
    .success();
  assert!(ok, "git {args:?} in {} failed", dir.display());
}

/// A workspace root with two child repos (`alpha`, `beta`), each carrying one
/// non-main linked worktree at `<root>/alpha-wt` / `<root>/beta-wt`. `discover`
/// collapses each worktree onto its owning repo, so the workspace has exactly
/// the two repos and `exec`/`clean` fan out over their worktrees.
fn workspace_with_worktrees() -> tempfile::TempDir {
  let root = tempfile::TempDir::new().unwrap();
  for (repo, wt) in [("alpha", "alpha-wt"), ("beta", "beta-wt")] {
    let repo_dir = root.path().join(repo);
    std::fs::create_dir_all(&repo_dir).unwrap();
    git_at(&repo_dir, &["init", "-b", "main"]);
    git_at(&repo_dir, &["config", "user.email", "t@t.t"]);
    git_at(&repo_dir, &["config", "user.name", "t"]);
    std::fs::write(repo_dir.join("README.md"), "x").unwrap();
    git_at(&repo_dir, &["add", "."]);
    git_at(&repo_dir, &["commit", "-m", "init"]);
    let wt_path = root.path().join(wt);
    git_at(
      &repo_dir,
      &["worktree", "add", "-b", "feat/x", wt_path.to_str().unwrap()],
    );
  }
  root
}

/// A workspace root with two child repos that have ONLY their main checkout
/// (no linked worktrees) — so exec/clean fan-out finds no targets anywhere.
fn workspace_main_only() -> tempfile::TempDir {
  let root = tempfile::TempDir::new().unwrap();
  for repo in ["alpha", "beta"] {
    let repo_dir = root.path().join(repo);
    std::fs::create_dir_all(&repo_dir).unwrap();
    git_at(&repo_dir, &["init", "-b", "main"]);
    git_at(&repo_dir, &["config", "user.email", "t@t.t"]);
    git_at(&repo_dir, &["config", "user.name", "t"]);
    std::fs::write(repo_dir.join("README.md"), "x").unwrap();
    git_at(&repo_dir, &["add", "."]);
    git_at(&repo_dir, &["commit", "-m", "init"]);
  }
  root
}

// `gwm exec` / `gwm clean` now FAN OUT across a workspace's child repos under
// `--workspace <root>` (issue #326), reversing the #319 deferral. This is an
// additive transition — a previous refusal turning into a success is not a
// breaking change. These tests pin the fan-out: a repo-tagged rollup/report
// across every child repo, with an aggregated exit code. The `--workspace`
// refusal now only applies to commands that still don't implement it (covered
// by `workspace_refuses_unsupported_subcommand` below).

#[test]
fn exec_fans_out_across_workspace_child_repos() {
  let root = workspace_with_worktrees();
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--workspace"])
    .arg(root.path())
    .args(["--", "sh", "-c", "echo ran > ws_exec_marker.txt"])
    .assert()
    .success()
    // A `══ <repo>` header per child repo, and a repo-tagged rollup.
    .stdout(predicate::str::contains("══ alpha"))
    .stdout(predicate::str::contains("══ beta"))
    .stdout(predicate::str::contains("✓ alpha/"))
    .stdout(predicate::str::contains("✓ beta/"));
  // The command actually ran in each child repo's worktree.
  assert!(root.path().join("alpha-wt/ws_exec_marker.txt").exists());
  assert!(root.path().join("beta-wt/ws_exec_marker.txt").exists());
}

#[test]
fn exec_workspace_scopes_to_a_matching_slug() {
  // A slug matching a worktree in only one child repo scopes the fan-out to
  // that repo (the others contribute nothing — not an error).
  let root = workspace_with_worktrees();
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--workspace"])
    .arg(root.path())
    .args(["alpha-wt", "--", "sh", "-c", "echo hi > scoped.txt"])
    .assert()
    .success();
  assert!(root.path().join("alpha-wt/scoped.txt").exists(), "alpha matched");
  assert!(
    !root.path().join("beta-wt/scoped.txt").exists(),
    "beta did not match the slug"
  );
}

#[test]
fn exec_workspace_scoped_slug_ignores_an_unrelated_repos_missing_profile() {
  // Only `alpha` defines `[exec.profiles.fmt]`; `beta` has none. Scoping to
  // `alpha-wt` must not resolve `beta`'s config (it contributes no target), so
  // the run succeeds despite `beta` lacking the profile (#326 review).
  let root = workspace_with_worktrees();
  std::fs::write(
    root.path().join("alpha/.gwm.toml"),
    "[exec.profiles.fmt]\ncommand = [\"sh\", \"-c\", \"echo hi > prof.txt\"]\n",
  )
  .unwrap();
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--workspace"])
    .arg(root.path())
    .args(["alpha-wt", "--profile", "fmt"])
    .assert()
    .success();
  assert!(root.path().join("alpha-wt/prof.txt").exists(), "alpha's profile ran");
}

#[test]
fn exec_workspace_errors_on_a_slug_matching_no_child_repo() {
  // A typo that matches nothing in ANY child repo is an error, not a silent
  // exit-0 having run nothing (#326 review).
  let root = workspace_with_worktrees();
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--workspace"])
    .arg(root.path())
    .args(["ghost-typo", "--", "true"])
    .assert()
    .failure()
    .code(1)
    .stderr(predicate::str::contains("ghost-typo"));
}

#[test]
fn exec_workspace_aggregates_a_nonzero_exit() {
  let root = workspace_with_worktrees();
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--workspace"])
    .arg(root.path())
    .args(["--", "sh", "-c", "exit 3"])
    .assert()
    .failure()
    .stdout(predicate::str::contains("✗ alpha/"))
    .stdout(predicate::str::contains("✗ beta/"));
}

#[test]
fn clean_fans_out_across_workspace_child_repos() {
  let root = workspace_with_worktrees();
  // A git-ignored `target/` in each child repo's worktree is reclaimable.
  for (repo, wt) in [("alpha", "alpha-wt"), ("beta", "beta-wt")] {
    let _ = repo;
    let wtdir = root.path().join(wt);
    std::fs::create_dir_all(wtdir.join("target")).unwrap();
    std::fs::write(wtdir.join("target/blob.bin"), vec![0u8; 4096]).unwrap();
    std::fs::write(wtdir.join(".gitignore"), "/target\n").unwrap();
  }
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean", "--workspace"])
    .arg(root.path())
    .assert()
    .success()
    // Report is repo-tagged; report-only must not delete.
    .stdout(predicate::str::contains("alpha/"))
    .stdout(predicate::str::contains("beta/"))
    .stdout(predicate::str::contains("re-run with --yes"));
  assert!(
    root.path().join("alpha-wt/target").exists(),
    "report-only keeps target/"
  );
}

#[test]
fn clean_workspace_yes_deletes_in_every_child_repo() {
  let root = workspace_with_worktrees();
  for wt in ["alpha-wt", "beta-wt"] {
    let wtdir = root.path().join(wt);
    std::fs::create_dir_all(wtdir.join("target")).unwrap();
    std::fs::write(wtdir.join("target/blob.bin"), vec![0u8; 4096]).unwrap();
    std::fs::write(wtdir.join(".gitignore"), "/target\n").unwrap();
  }
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean", "--workspace"])
    .arg(root.path())
    .arg("--yes")
    .assert()
    .success()
    .stdout(predicate::str::contains("reclaimed"));
  assert!(!root.path().join("alpha-wt/target").exists());
  assert!(!root.path().join("beta-wt/target").exists());
}

#[test]
fn clean_workspace_errors_before_deleting_on_a_corrupt_child_repo() {
  // A child that looks like a repo (.git present) but won't open must fail the
  // whole fan-out BEFORE any deletion — not be silently skipped while the valid
  // repos get cleaned (#326 review).
  let root = workspace_with_worktrees();
  let wtdir = root.path().join("alpha-wt");
  std::fs::create_dir_all(wtdir.join("target")).unwrap();
  std::fs::write(wtdir.join("target/blob.bin"), vec![0u8; 4096]).unwrap();
  std::fs::write(wtdir.join(".gitignore"), "/target\n").unwrap();
  let corrupt = root.path().join("corrupt");
  std::fs::create_dir_all(&corrupt).unwrap();
  std::fs::write(corrupt.join(".git"), "gitdir: /nonexistent-gitdir\n").unwrap();

  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean", "--workspace"])
    .arg(root.path())
    .arg("--yes")
    .assert()
    .failure()
    .code(1)
    .stderr(predicate::str::contains("corrupt"));
  // The valid repo's reclaimable target/ survives — nothing was deleted.
  assert!(wtdir.join("target").exists(), "fan-out must fail before any deletion");
}

#[test]
fn exec_workspace_all_empty_errors_on_a_missing_command() {
  // Every repo is main-only (no targets), but a usage error (neither inline
  // command nor --profile) must still surface, not a silent exit 0 (#326 rev).
  let root = workspace_main_only();
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--workspace"])
    .arg(root.path())
    .assert()
    .failure()
    .code(1)
    .stderr(predicate::str::contains("provide a command"));
}

#[test]
fn exec_workspace_all_empty_errors_on_an_unknown_profile() {
  let root = workspace_main_only();
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--workspace"])
    .arg(root.path())
    .args(["--profile", "ghost"])
    .assert()
    .failure()
    .code(1)
    .stderr(predicate::str::contains("no profile named `ghost`"));
}

#[test]
fn exec_workspace_all_empty_inline_command_exits_zero() {
  // A valid inline command with no targets anywhere is "nothing to do", exit 0.
  let root = workspace_main_only();
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["exec", "--workspace"])
    .arg(root.path())
    .args(["--", "true"])
    .assert()
    .success()
    .stdout(predicate::str::contains("no worktrees to run in"));
}

#[test]
fn clean_workspace_all_empty_errors_on_an_unknown_profile() {
  // A typo'd `--profile` with no targets anywhere must surface, not silently
  // report "nothing to reclaim" (#326 review).
  let root = workspace_main_only();
  Command::cargo_bin("gwm")
    .unwrap()
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["clean", "--workspace"])
    .arg(root.path())
    .args(["--profile", "ghost", "--yes"])
    .assert()
    .failure()
    .code(1)
    .stderr(predicate::str::contains("no profile named `ghost`"));
}

#[test]
fn workspace_refuses_a_still_unsupported_subcommand() {
  // `--workspace` is still refused on commands that don't implement it (only
  // list/create/exec/clean and the bare TUI do).
  let (dir, _base, _wt) = repo_with_one_worktree();
  let ws = tempfile::TempDir::new().unwrap();
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["sync", "--workspace", ws.path().to_str().unwrap()])
    .assert()
    .failure()
    .code(1)
    .stderr(predicate::str::contains("--workspace is only supported"));
}

// -- gwm agents (issue #408, US4) ------------------------------------------
//
// Detection is hermetic here: GWM_AGENTS_HOME points every scan at a seeded
// TempDir, so no test depends on the runner's real home or installed agents.

mod agents_cmd {
  use super::*;
  use common::init_repo;
  use std::path::Path;

  /// Seed a codex session recorded at `cwd` under `home`.
  fn seed_codex(home: &Path, cwd: &Path, sid: &str) {
    let dir = home
      .join(".codex/sessions")
      .join(gwm::agent_sessions::codex_day_dir(std::time::SystemTime::now()));
    std::fs::create_dir_all(&dir).unwrap();
    // Windows paths carry backslashes — escape them or the JSON line is
    // invalid and the session is silently dropped.
    let cwd = cwd.display().to_string().replace('\\', "\\\\");
    let line = format!(
      r#"{{"timestamp":"2026-07-22T10:00:00.000Z","type":"session_meta","payload":{{"session_id":"{sid}","cwd":"{cwd}"}}}}"#,
    );
    std::fs::write(dir.join(format!("rollout-{sid}.jsonl")), format!("{line}\n")).unwrap();
  }

  fn gwm_in(dir: &Path, home: &Path) -> Command {
    let mut cmd = Command::cargo_bin("gwm").unwrap();
    cmd.current_dir(dir).env("GWM_AGENTS_HOME", home);
    cmd
  }

  #[test]
  fn opencode_db_sessions_are_read_without_a_sqlite3_cli() {
    // Codex review round I (P1): Windows rarely ships a `sqlite3` CLI, so
    // shelling out silently degraded every opencode ≥ 1.x install to the
    // dead legacy JSON. The db must be read in-process — strip PATH so any
    // external sqlite3 is unreachable and the session must still surface.
    let (repo_dir, _repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();
    let dir = home.path().join(".local/share/opencode");
    std::fs::create_dir_all(dir.join("storage/project")).unwrap();
    let now_ms = std::time::SystemTime::now()
      .duration_since(std::time::SystemTime::UNIX_EPOCH)
      .unwrap()
      .as_millis() as i64;
    let conn = rusqlite::Connection::open(dir.join("opencode.db")).unwrap();
    conn
      .execute_batch(
        "CREATE TABLE session (id text, parent_id text, directory text, title text, time_updated integer, time_archived integer);",
      )
      .unwrap();
    conn
      .execute(
        "INSERT INTO session VALUES (?1, NULL, ?2, ?3, ?4, NULL)",
        rusqlite::params![
          "oc-nocli",
          repo_dir.path().display().to_string(),
          "db without cli",
          now_ms
        ],
      )
      .unwrap();
    drop(conn);

    gwm_in(repo_dir.path(), home.path())
      .env("PATH", "")
      .arg("agents")
      .assert()
      .success()
      .stdout(predicate::str::contains("opencode"))
      .stdout(predicate::str::contains("db without cli"));
  }

  #[test]
  fn attach_resolves_exact_names_before_substrings() {
    // Codex review round K (P2): the agents worktree matcher did a bare
    // case-sensitive substring match, so with worktrees `foo` and
    // `foo-extra`, `gwm agents attach foo <id>` errored as ambiguous
    // instead of selecting the exact name — `find_fuzzy`'s tiering (exact
    // name, exact id, then case-insensitive substring) applies here too.
    let (repo_dir, _repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();
    let side = tempfile::TempDir::new().unwrap();
    let foo = side.path().join("foo");
    let foo_extra = side.path().join("foo-extra");
    git_at(
      repo_dir.path(),
      &["worktree", "add", "-b", "b-foo", foo.to_str().unwrap()],
    );
    git_at(
      repo_dir.path(),
      &["worktree", "add", "-b", "b-foo-extra", foo_extra.to_str().unwrap()],
    );
    seed_codex(home.path(), &foo, "ffff-exact");

    gwm_in(repo_dir.path(), home.path())
      .args(["agents", "attach", "foo", "ffff-exact"])
      .assert()
      .success();
  }

  #[test]
  fn opencode_detection_honors_xdg_data_home() {
    // Codex review round O (P2): with `XDG_DATA_HOME` set, opencode keeps
    // `opencode.db` under `$XDG_DATA_HOME/opencode` — the hardcoded
    // `~/.local/share` base made every session invisible there. No
    // GWM_AGENTS_HOME here: the seam deliberately IGNORES XDG (round T),
    // so the XDG resolution is exercised against the real-home path — the
    // assertions only require the seeded session to be present, ambient
    // sessions from the machine's own stores may appear alongside.
    let (repo_dir, _repo) = init_repo();
    let xdg = tempfile::TempDir::new().unwrap();
    let dir = xdg.path().join("opencode");
    std::fs::create_dir_all(dir.join("storage/project")).unwrap();
    let now_ms = std::time::SystemTime::now()
      .duration_since(std::time::SystemTime::UNIX_EPOCH)
      .unwrap()
      .as_millis() as i64;
    let conn = rusqlite::Connection::open(dir.join("opencode.db")).unwrap();
    conn
      .execute_batch(
        "CREATE TABLE session (id text, parent_id text, directory text, title text, time_updated integer, time_archived integer);",
      )
      .unwrap();
    conn
      .execute(
        "INSERT INTO session VALUES (?1, NULL, ?2, ?3, ?4, NULL)",
        rusqlite::params!["oc-xdg", repo_dir.path().display().to_string(), "xdg session", now_ms],
      )
      .unwrap();
    drop(conn);

    let mut cmd = Command::cargo_bin("gwm").unwrap();
    cmd
      .current_dir(repo_dir.path())
      .env_remove("GWM_AGENTS_HOME")
      .env("XDG_DATA_HOME", xdg.path())
      .arg("agents")
      .assert()
      .success()
      .stdout(predicate::str::contains("opencode"))
      .stdout(predicate::str::contains("xdg session"));
  }

  #[test]
  fn gwm_agents_home_beats_an_inherited_xdg_data_home() {
    // Codex review round T (P2): with GWM_AGENTS_HOME isolating a run but
    // an absolute XDG_DATA_HOME inherited from the environment, the
    // opencode scan followed XDG into the REAL machine store — the seam
    // must win for every backend or tests and the documented override
    // become machine-dependent.
    let (repo_dir, _repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();
    let xdg = tempfile::TempDir::new().unwrap(); // absolute, and NOT the seam
    let dir = home.path().join(".local/share/opencode");
    std::fs::create_dir_all(dir.join("storage/project")).unwrap();
    let now_ms = std::time::SystemTime::now()
      .duration_since(std::time::SystemTime::UNIX_EPOCH)
      .unwrap()
      .as_millis() as i64;
    let conn = rusqlite::Connection::open(dir.join("opencode.db")).unwrap();
    conn
      .execute_batch(
        "CREATE TABLE session (id text, parent_id text, directory text, title text, time_updated integer, time_archived integer);",
      )
      .unwrap();
    conn
      .execute(
        "INSERT INTO session VALUES (?1, NULL, ?2, ?3, ?4, NULL)",
        rusqlite::params!["oc-seam", repo_dir.path().display().to_string(), "seam wins", now_ms],
      )
      .unwrap();
    drop(conn);

    gwm_in(repo_dir.path(), home.path())
      .env("XDG_DATA_HOME", xdg.path())
      .arg("agents")
      .assert()
      .success()
      .stdout(predicate::str::contains("seam wins"));
  }

  #[test]
  fn agents_lists_detected_sessions_per_worktree() {
    let (repo_dir, _repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();
    seed_codex(home.path(), repo_dir.path(), "0000-cafe");

    gwm_in(repo_dir.path(), home.path())
      .arg("agents")
      .assert()
      .success()
      .stdout(predicate::str::contains("codex"))
      .stdout(predicate::str::contains("0000-cafe"))
      .stdout(predicate::str::contains("active"))
      // Codex review round A: the human listing must also carry the last
      // activity (spec US4) — a relative form like "0m ago".
      .stdout(predicate::str::contains("ago"));
  }

  #[test]
  fn list_hides_the_agent_column_without_any_detected_session() {
    // Codex review round D: with no agent tooling / no session, the human
    // table must be byte-identical to the pre-#408 layout — no AGENT
    // header squeezing NAME/BRANCH/PATH.
    let (repo_dir, _repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();

    gwm_in(repo_dir.path(), home.path())
      .arg("list")
      .assert()
      .success()
      .stdout(predicate::str::contains("AGENT").not());
  }

  #[test]
  fn list_shows_the_agent_column_when_a_session_is_detected() {
    let (repo_dir, _repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();
    seed_codex(home.path(), repo_dir.path(), "1111-cafe");

    gwm_in(repo_dir.path(), home.path())
      .arg("list")
      .assert()
      .success()
      .stdout(predicate::str::contains("AGENT"))
      .stdout(predicate::str::contains("codex"));
  }

  #[test]
  fn agents_lists_unmatched_sessions_in_a_dedicated_section() {
    // Codex review round C: the attach error says "run `gwm agents` to see
    // the detected ids", so a session matched to NO worktree — precisely
    // the one worth attaching — must be listed too, under `unmatched`.
    let (repo_dir, _repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();
    seed_codex(home.path(), Path::new("/somewhere/else"), "9999-lost");

    gwm_in(repo_dir.path(), home.path())
      .arg("agents")
      .assert()
      .success()
      .stdout(predicate::str::contains("unmatched"))
      .stdout(predicate::str::contains("9999-lost"));
  }

  #[test]
  fn agents_omits_the_unmatched_section_when_every_session_is_matched() {
    let (repo_dir, _repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();
    seed_codex(home.path(), repo_dir.path(), "0000-cafe");

    gwm_in(repo_dir.path(), home.path())
      .arg("agents")
      .assert()
      .success()
      .stdout(predicate::str::contains("unmatched").not());
  }

  #[test]
  fn agents_listing_prefers_the_session_name_when_present() {
    let (repo_dir, _repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();
    let dir = home
      .path()
      .join(".codex/sessions")
      .join(gwm::agent_sessions::codex_day_dir(std::time::SystemTime::now()));
    std::fs::create_dir_all(&dir).unwrap();
    let cwd = repo_dir.path().display().to_string().replace('\\', "\\\\");
    let meta = format!(r#"{{"type":"session_meta","payload":{{"session_id":"named-1","cwd":"{cwd}"}}}}"#);
    let user = r#"{"type":"event_msg","payload":{"type":"user_message","message":"refactor the login flow"}}"#;
    std::fs::write(
      dir.join("rollout-named.jsonl"),
      format!(
        "{meta}
{user}
"
      ),
    )
    .unwrap();

    gwm_in(repo_dir.path(), home.path())
      .arg("agents")
      .assert()
      .success()
      // Name shown alongside the (full) id — both visible, the id is what
      // attach takes.
      .stdout(predicate::str::contains("refactor the login flow"))
      .stdout(predicate::str::contains("named-1"));
  }

  #[test]
  fn pinned_marker_is_scoped_to_the_pinned_worktree_only() {
    // Codex review round A: a session detected on worktree A but pinned on
    // B must be flagged "pinned" only under B.
    let (repo_dir, repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();
    // Session recorded on the MAIN checkout path (detected on A).
    seed_codex(home.path(), repo_dir.path(), "4444-cafe");
    // A second worktree B to pin onto.
    let wt_b = repo_dir.path().join("wt-b");
    {
      let head = repo.head().unwrap().peel_to_commit().unwrap();
      repo.branch("feat/b", &head, false).unwrap();
      let mut opts = git2::WorktreeAddOptions::new();
      let branch = repo.find_branch("feat/b", git2::BranchType::Local).unwrap();
      opts.reference(Some(branch.get()));
      repo.worktree("wt-b", &wt_b, Some(&opts)).unwrap();
    }
    gwm_in(repo_dir.path(), home.path())
      .args(["agents", "attach", "wt-b", "4444-cafe"])
      .assert()
      .success();

    let out = gwm_in(repo_dir.path(), home.path())
      .arg("agents")
      .assert()
      .success()
      .get_output()
      .stdout
      .clone();
    let text = String::from_utf8_lossy(&out);
    // Split per worktree block: the main checkout's block must NOT carry
    // "pinned"; wt-b's block must.
    let blocks: Vec<&str> = text.split("\n\n").collect();
    let _ = blocks; // block layout is free; assert line-wise instead:
    let pinned_lines: Vec<&str> = text.lines().filter(|l| l.contains("pinned")).collect();
    assert_eq!(pinned_lines.len(), 1, "exactly one pinned line, got: {text}");
  }

  #[test]
  fn attach_accumulates_pins_and_detach_removes_one_or_all() {
    // User feedback 2026-07-22: several agents can work one worktree —
    // attach ADDS a pin, `detach <wt> <id>` removes that one, bare
    // `detach <wt>` clears them all.
    let (repo_dir, _repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();
    seed_codex(home.path(), repo_dir.path(), "aaaa-multi");
    seed_codex(home.path(), repo_dir.path(), "bbbb-multi");

    for sid in ["aaaa-multi", "bbbb-multi"] {
      gwm_in(repo_dir.path(), home.path())
        .args(["agents", "attach", ".", sid])
        .assert()
        .success();
    }
    let out = gwm_in(repo_dir.path(), home.path())
      .arg("agents")
      .assert()
      .success()
      .get_output()
      .stdout
      .clone();
    let text = String::from_utf8_lossy(&out);
    let pinned = text.lines().filter(|l| l.contains("pinned")).count();
    assert_eq!(pinned, 2, "both pins marked, got: {text}");

    // Targeted detach removes exactly one pin.
    gwm_in(repo_dir.path(), home.path())
      .args(["agents", "detach", ".", "aaaa-multi"])
      .assert()
      .success();
    let out = gwm_in(repo_dir.path(), home.path())
      .arg("agents")
      .assert()
      .success()
      .get_output()
      .stdout
      .clone();
    let text = String::from_utf8_lossy(&out);
    assert_eq!(text.lines().filter(|l| l.contains("pinned")).count(), 1, "got: {text}");
    assert!(
      text.lines().any(|l| l.contains("bbbb-multi") && l.contains("pinned")),
      "the other pin survives: {text}"
    );

    // Bare detach clears the rest.
    gwm_in(repo_dir.path(), home.path())
      .args(["agents", "detach", "."])
      .assert()
      .success();
    let out = gwm_in(repo_dir.path(), home.path())
      .arg("agents")
      .assert()
      .success()
      .get_output()
      .stdout
      .clone();
    assert!(!String::from_utf8_lossy(&out).contains("pinned"));
  }

  #[test]
  fn workspace_list_table_carries_the_agent_column() {
    // Codex review round A: `gwm list --workspace` (human table) must show
    // AGENT like the single-repo table — and like it, only when a session
    // was actually detected (round D conditional).
    let root = workspace_with_worktrees();
    let home = tempfile::TempDir::new().unwrap();
    seed_codex(home.path(), &root.path().join("alpha-wt"), "aaaa-ws");
    let mut cmd = Command::cargo_bin("gwm").unwrap();
    cmd
      .current_dir(root.path())
      .env("GWM_AGENTS_HOME", home.path())
      .args(["list", "--workspace", "."])
      .assert()
      .success()
      .stdout(predicate::str::contains("AGENT"))
      .stdout(predicate::str::contains("codex"));
  }

  #[test]
  fn workspace_list_table_hides_the_agent_column_without_sessions() {
    let root = workspace_with_worktrees();
    let home = tempfile::TempDir::new().unwrap();
    let mut cmd = Command::cargo_bin("gwm").unwrap();
    cmd
      .current_dir(root.path())
      .env("GWM_AGENTS_HOME", home.path())
      .args(["list", "--workspace", "."])
      .assert()
      .success()
      .stdout(predicate::str::contains("AGENT").not())
      // Codex review round E: the DATA rows must drop the 8-wide `-`
      // placeholder cell too, not just the header — otherwise the table
      // grows a headerless column that shifts PATH.
      .stdout(predicate::str::is_match(r"clean\s+-\s+/").unwrap().not());
  }

  #[test]
  fn workspace_listings_honor_per_repo_pins() {
    // Codex review round I (P2): a session pinned in a child repo vanished
    // from every workspace surface — the workspace pass handed detection an
    // empty pin list instead of opening each row's owning repo.
    let root = workspace_with_worktrees();
    let home = tempfile::TempDir::new().unwrap();
    // Recorded OUTSIDE any workspace path: only the pin can surface it.
    seed_codex(home.path(), &home.path().join("elsewhere"), "cccc-wspin");
    let alpha_wt = root.path().join("alpha-wt");
    Command::cargo_bin("gwm")
      .unwrap()
      .current_dir(&alpha_wt)
      .env("GWM_AGENTS_HOME", home.path())
      .args(["agents", "attach", ".", "cccc-wspin"])
      .assert()
      .success();

    let mut cmd = Command::cargo_bin("gwm").unwrap();
    cmd
      .current_dir(root.path())
      .env("GWM_AGENTS_HOME", home.path())
      .args(["list", "--workspace", ".", "--format=json"])
      .assert()
      .success()
      .stdout(predicate::str::contains("cccc-wspin"));
    // Human table too: the pinned session drives the AGENT column.
    let mut cmd = Command::cargo_bin("gwm").unwrap();
    cmd
      .current_dir(root.path())
      .env("GWM_AGENTS_HOME", home.path())
      .args(["list", "--workspace", "."])
      .assert()
      .success()
      .stdout(predicate::str::contains("codex"));
  }

  #[test]
  fn agents_json_returns_the_wire_shape() {
    let (repo_dir, _repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();
    seed_codex(home.path(), repo_dir.path(), "1111-cafe");

    let out = gwm_in(repo_dir.path(), home.path())
      .args(["agents", "--format=json"])
      .assert()
      .success()
      .get_output()
      .stdout
      .clone();
    let v: serde_json::Value = serde_json::from_slice(&out).expect("valid JSON");
    let rows = v.as_array().expect("array of worktrees");
    let with = rows
      .iter()
      .find(|r| r["agents"].is_object())
      .expect("one row carries agents");
    assert_eq!(with["agents"]["top"]["kind"], "codex");
    assert_eq!(with["agents"]["top"]["id"], "1111-cafe");
  }

  #[test]
  fn agents_with_nothing_detected_says_so_and_exits_zero() {
    let (repo_dir, _repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();
    gwm_in(repo_dir.path(), home.path())
      .arg("agents")
      .assert()
      .success()
      .stdout(predicate::str::contains("no agent session"));
  }

  #[test]
  fn attach_pins_an_unmatched_session_and_detach_restores_detection() {
    let (repo_dir, _repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();
    // Session recorded elsewhere: pure detection matches nothing.
    seed_codex(home.path(), Path::new("/somewhere/else"), "2222-cafe");

    gwm_in(repo_dir.path(), home.path())
      .args(["agents", "attach", ".", "2222-cafe"])
      .assert()
      .success()
      .stdout(predicate::str::contains("2222-cafe"));

    // The pin is honoured by `agents` AND by the list JSON surface.
    gwm_in(repo_dir.path(), home.path())
      .arg("agents")
      .assert()
      .success()
      .stdout(predicate::str::contains("codex"))
      .stdout(predicate::str::contains("pinned"));
    let out = gwm_in(repo_dir.path(), home.path())
      .args(["list", "--format=json"])
      .assert()
      .success()
      .get_output()
      .stdout
      .clone();
    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    assert!(
      v.as_array()
        .unwrap()
        .iter()
        .any(|r| r["agents"]["top"]["id"] == "2222-cafe"),
      "pinned session must ride the list JSON"
    );

    gwm_in(repo_dir.path(), home.path())
      .args(["agents", "detach", "."])
      .assert()
      .success();
    // Codex review round C: with the pin gone the session is no longer
    // attributed to any worktree, but it stays discoverable — listed under
    // `unmatched` (unpinned) instead of vanishing from the output.
    gwm_in(repo_dir.path(), home.path())
      .arg("agents")
      .assert()
      .success()
      .stdout(predicate::str::contains("unmatched"))
      .stdout(predicate::str::contains("2222-cafe"))
      .stdout(predicate::str::contains("pinned").not());
  }

  #[test]
  fn attach_unknown_session_id_fails_with_a_hint() {
    let (repo_dir, _repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();
    gwm_in(repo_dir.path(), home.path())
      .args(["agents", "attach", ".", "nope-nope"])
      .assert()
      .failure()
      .stderr(predicate::str::contains("gwm agents"));
  }

  #[test]
  fn plain_list_table_carries_the_agent_column() {
    let (repo_dir, _repo) = init_repo();
    let home = tempfile::TempDir::new().unwrap();
    seed_codex(home.path(), repo_dir.path(), "3333-cafe");
    gwm_in(repo_dir.path(), home.path())
      .arg("list")
      .assert()
      .success()
      .stdout(predicate::str::contains("AGENT"))
      .stdout(predicate::str::contains("codex"));
  }
}

#[test]
fn a_link_written_after_a_backend_flip_survives_the_next_command() {
  // The reconcile lives in `forge::resolve`, and `gwm link` did not
  // resolve. So after flipping `forge` the write succeeded against the
  // previous backend's marker, and the next command that *did* resolve
  // saw the mismatch and deleted what the user had just linked (Codex
  // review #458).
  //
  // `gwm open --print-url` brackets this rather than `gwm list`: the
  // network-free list never resolves a forge, so it neither records the
  // marker nor triggers the purge, and a test built on it would pass
  // against the bug.
  let (dir, repo) = init_repo();
  repo
    .remote("origin", "https://git.acme.internal/team/proj.git")
    .unwrap();
  let branch = repo.head().unwrap().shorthand().unwrap().to_string();

  let ledger = dir.path().join("trust.toml");
  let gwm = |args: &[&str]| {
    Command::cargo_bin("gwm")
      .unwrap()
      .current_dir(dir.path())
      .env("GWM_TRUST_LEDGER", &ledger)
      .env("GWM_NO_GLOBAL_CONFIG", "1")
      .args(args)
      .assert()
      .success();
  };

  // `git.acme.internal` says nothing about which forge it runs, so the
  // backend is named explicitly on both sides of the flip — that is the
  // gate from `forge::resolve`, not part of what this test pins.
  fs::write(dir.path().join(".gwm.toml"), "forge = \"github\"\n").unwrap();
  gwm(&["trust", "add"]);
  // Record the GitHub backend against the repo.
  gwm(&["link", "issue", "7"]);
  gwm(&["open", "issue", "--print-url"]);

  fs::write(dir.path().join(".gwm.toml"), "forge = \"gitlab\"\n").unwrap();
  // `git.acme.internal` states no forge, so the repo's own `.gwm.toml`
  // is what names it — and that file ships with the repo, so it only
  // counts once the repo is approved. Editing it above changed its
  // hash, which is why this runs again here.
  gwm(&["trust", "add"]);
  gwm(&["link", "pr", "42"]);

  // Resolves as GitLab. Before the fix this purged the line above and
  // the command failed with "no PR linked".
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_TRUST_LEDGER", &ledger)
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .args(["open", "pr", "--print-url"])
    .assert()
    .success()
    .stdout(predicate::str::contains("/-/merge_requests/42"));

  let reopened = git2::Repository::open(dir.path()).unwrap();
  assert_eq!(
    gwm::github::read_link(&reopened, &branch).unwrap().pr,
    Some(42),
    "the user linked this under the new backend; nothing may drop it"
  );
}

#[test]
fn a_repo_cannot_authorise_its_own_host_until_it_is_trusted() {
  // The hole three review rounds kept naming: `.gwm.toml` ships with the
  // repo, so letting its `forge` key point gwm at an unrecognised host
  // meant a hostile clone could aim `gh` / `glab` at its own server —
  // and whatever token the environment carries — from a plain
  // `gwm status` or a TUI selection (Codex review #458).
  //
  // Same ledger as `[[bootstrap.command]]`, because it is the same
  // decision about the same file. It is checked non-interactively, since
  // `forge::resolve` runs on the TUI's selection path; `gwm trust add`
  // is how the user answers.
  let (dir, repo) = init_repo();
  repo
    .remote("origin", "https://code.acme.internal/team/proj.git")
    .unwrap();
  fs::write(dir.path().join(".gwm.toml"), "forge = \"gitlab\"\n").unwrap();
  let ledger = dir.path().join("trust.toml");

  let run = |args: &[&str]| {
    let mut c = Command::cargo_bin("gwm").unwrap();
    c.current_dir(dir.path())
      .env("GWM_TRUST_LEDGER", &ledger)
      .env("GWM_NO_GLOBAL_CONFIG", "1")
      .args(args);
    c.assert()
  };

  run(&["link", "issue", "7"]).success();
  run(&["open", "issue", "--print-url"])
    .failure()
    .stderr(predicate::str::contains("gwm trust add"));

  run(&["trust", "add"]).success();
  run(&["open", "issue", "--print-url"])
    .success()
    .stdout(predicate::str::contains("code.acme.internal"));

  // Approving covers the file as it was: editing it revokes that.
  fs::write(dir.path().join(".gwm.toml"), "forge = \"gitlab\"\n# changed\n").unwrap();
  run(&["open", "issue", "--print-url"]).failure();

  // And the escape hatch the rest of the trust surface already has,
  // for CI runners with no one to answer.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_TRUST_LEDGER", &ledger)
    .env("GWM_NO_GLOBAL_CONFIG", "1")
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["open", "issue", "--print-url"])
    .assert()
    .success();
}

#[test]
fn a_global_forge_kind_does_not_authorise_an_arbitrary_host() {
  // `forge = "gitlab"` in the user's own config says which *backend* they
  // use. It does not say which *hosts* may receive an authenticated call,
  // and reading it as though it did left the gate wide open for the most
  // ordinary setup there is: anyone working at a GitLab shop sets that key
  // once, and from then on every clone — including one whose `origin` an
  // attacker chose — got `glab` pointed at it.
  //
  // That is not theoretical. Verified against glab 1.109.0: with
  // `GITLAB_HOST` naming an arbitrary host, glab sends the ambient
  // `GITLAB_TOKEN` there as a `Private-Token` header, with no host
  // scoping of any kind. The repo does not even need a `.gwm.toml` —
  // the global value merges in on its own.
  let (dir, repo) = init_repo();
  repo
    .remote("origin", "https://code.acme.internal/team/proj.git")
    .unwrap();

  let xdg = tempfile::TempDir::new().unwrap();
  fs::create_dir_all(xdg.path().join("gwm")).unwrap();
  fs::write(xdg.path().join("gwm").join("config.toml"), "forge = \"gitlab\"\n").unwrap();
  let ledger = dir.path().join("trust.toml");

  let run = |args: &[&str]| {
    let mut c = Command::cargo_bin("gwm").unwrap();
    c.current_dir(dir.path())
      .env("GWM_TRUST_LEDGER", &ledger)
      .env("XDG_CONFIG_HOME", xdg.path())
      .env_remove("GWM_NO_GLOBAL_CONFIG")
      .args(args);
    c.assert()
  };

  // Link first, so the refusal below can only come from the gate. Without
  // it the command stops at "no issue linked" and the test passes while
  // the host is still being authorised.
  run(&["link", "issue", "7"]).success();
  run(&["open", "issue", "--print-url"])
    .failure()
    .stderr(predicate::str::contains("forge_hosts"));
}

#[test]
fn a_global_config_authorises_the_hosts_it_names_with_their_kind() {
  // The remedy, and the reason the kind lives *per host*: a shop with both
  // a self-hosted GitLab and a GitHub Enterprise cannot be described by a
  // single `forge` key. Naming each host with its own backend covers the
  // mixed fleet, and covers it declaratively — one entry per host, in a
  // file that never ships with a repo, so nothing a clone carries can add
  // to it.
  let xdg = tempfile::TempDir::new().unwrap();
  fs::create_dir_all(xdg.path().join("gwm")).unwrap();
  fs::write(
    xdg.path().join("gwm").join("config.toml"),
    // `Code.ACME.internal` deliberately mis-cased: hosts are compared
    // case-insensitively, like DNS and like `known_kind`, so a config that
    // spells the host the way a human would must still cover the origin.
    "[forge_hosts]\n\"Code.ACME.internal\" = \"gitlab\"\n\"ghe.acme.internal\" = \"github\"\n",
  )
  .unwrap();

  let case = |url: &str, want: &str| {
    let (dir, repo) = init_repo();
    repo.remote("origin", url).unwrap();
    let ledger = dir.path().join("trust.toml");
    Command::cargo_bin("gwm")
      .unwrap()
      .current_dir(dir.path())
      .env("GWM_TRUST_LEDGER", &ledger)
      .env("XDG_CONFIG_HOME", xdg.path())
      .env_remove("GWM_NO_GLOBAL_CONFIG")
      .args(["link", "issue", "7"])
      .assert()
      .success();
    Command::cargo_bin("gwm")
      .unwrap()
      .current_dir(dir.path())
      .env("GWM_TRUST_LEDGER", &ledger)
      .env("XDG_CONFIG_HOME", xdg.path())
      .env_remove("GWM_NO_GLOBAL_CONFIG")
      .args(["open", "issue", "--print-url"])
      .assert()
      .success()
      .stdout(predicate::str::contains(want));
  };

  // GitLab nests the issue under `/-/issues`, GitHub does not: the URL
  // shape is what proves the *kind* came from the host's own entry and
  // not from a shared default.
  case(
    "https://code.acme.internal/team/proj.git",
    "code.acme.internal/team/proj/-/issues/7",
  );
  case(
    "https://ghe.acme.internal/team/proj.git",
    "ghe.acme.internal/team/proj/issues/7",
  );
}

#[test]
fn approving_one_repo_does_not_approve_its_neighbour_on_the_same_host() {
  // The ledger is keyed on `(origin, sha256(.gwm.toml))`, and the `origin`
  // half has to identify the *repo*. Building it from `RemoteRef::web_origin`
  // degraded it to the *host*, so the pair collapsed to
  // `(https://code.acme.internal, <hash>)` — shared by every repo on that
  // host whose config hashes the same.
  //
  // That is not a corner case: `.gwm.toml` is normally a template copied
  // across a team's repos, so byte-identical files are the common shape. A
  // hostile repo could ship a sibling's config verbatim and inherit its
  // approval, which is exactly the capability the #419 gate exists to
  // withhold.
  let ledger = tempfile::TempDir::new().unwrap();
  let ledger = ledger.path().join("trust.toml");
  let config = "forge = \"gitlab\"\n";

  let make = |slug: &str| {
    let (dir, repo) = init_repo();
    repo
      .remote("origin", &format!("https://code.acme.internal/{slug}.git"))
      .unwrap();
    fs::write(dir.path().join(".gwm.toml"), config).unwrap();
    dir
  };
  let mine = make("team/mine");
  let theirs = make("team/theirs");

  let run = |dir: &tempfile::TempDir, args: &[&str]| {
    let mut c = Command::cargo_bin("gwm").unwrap();
    c.current_dir(dir.path())
      .env("GWM_TRUST_LEDGER", &ledger)
      .env("GWM_NO_GLOBAL_CONFIG", "1")
      .args(args);
    c.assert()
  };

  run(&mine, &["link", "issue", "7"]).success();
  run(&theirs, &["link", "issue", "7"]).success();
  run(&mine, &["trust", "add"]).success();

  run(&mine, &["open", "issue", "--print-url"]).success();
  run(&theirs, &["open", "issue", "--print-url"])
    .failure()
    .stderr(predicate::str::contains("trust ledger"));
}

#[test]
fn trust_add_satisfies_the_gate_that_bootstrap_checks() {
  // `gwm trust add` printed `✓ trusted …` and `gwm create` in the same repo
  // still refused, because the two wrote and read different keys. One helper
  // now builds both, so approving a repo means the same thing everywhere.
  let (dir, repo) = init_repo();
  repo
    .remote("origin", "https://code.acme.internal/team/proj.git")
    .unwrap();
  fs::write(
    dir.path().join(".gwm.toml"),
    "forge = \"gitlab\"\n\n[[bootstrap.command]]\nname = \"noop\"\nrun = \"true\"\n",
  )
  .unwrap();
  let ledger = dir.path().join("trust.toml");

  let run = |args: &[&str]| {
    let mut c = Command::cargo_bin("gwm").unwrap();
    c.current_dir(dir.path())
      .env("GWM_TRUST_LEDGER", &ledger)
      .env("GWM_NO_GLOBAL_CONFIG", "1")
      .args(args);
    c.assert()
  };

  run(&["trust", "add"]).success();
  // Both gates, one approval: the forge host gate and the bootstrap gate.
  run(&["link", "issue", "7"]).success();
  run(&["open", "issue", "--print-url"]).success();
  run(&["bootstrap"]).success();
}

// --- create --name (issue #416) -----------------------------------------

#[test]
fn create_name_flag_appears_in_help() {
  Command::cargo_bin("gwm")
    .unwrap()
    .args(["create", "--help"])
    .assert()
    .success()
    .stdout(predicate::str::contains("--name"));
}

/// The mode is chosen by an explicit flag, never inferred from how many
/// positionals were supplied — two of the three is a typo, not a request
/// for free-form naming.
#[test]
fn create_rejects_a_partial_triple() {
  Command::cargo_bin("gwm")
    .unwrap()
    .args(["create", "feat", "42"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("<DESC>").or(predicate::str::contains("required")));
}

#[test]
fn create_name_conflicts_with_the_structured_triple() {
  Command::cargo_bin("gwm")
    .unwrap()
    .args(["create", "--name", "spike-redis", "feat", "42", "x"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("cannot be used with").or(predicate::str::contains("conflict")));
}

#[test]
fn create_name_makes_a_worktree_whose_branch_is_the_name() {
  let (dir, repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "--name", "spike-redis"])
    .assert()
    .success()
    .stdout(predicate::str::contains("spike-redis"))
    .stdout(predicate::str::contains("worktree created"));

  // `path_pattern` is `{type}-{issue}-{desc}` in the test config and must
  // NOT have been applied — a free-form name has none of those tokens.
  let wt_dir = base.path().join("spike-redis");
  assert!(wt_dir.exists(), "worktree dir must be the name verbatim");
  assert!(
    repo.find_branch("spike-redis", git2::BranchType::Local).is_ok(),
    "the branch must be the name verbatim"
  );
}

#[test]
fn create_name_rejects_a_name_git_would_refuse() {
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  write_test_config(dir.path(), base.path());

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "--name", "has space"])
    .assert()
    .failure()
    .stderr(predicate::str::contains("has space"));
}

#[test]
fn commit_prefix_reads_a_branch_written_with_a_custom_pattern() {
  // Issue #417. `worktree.branch_pattern` drives `BranchSpec::branch_name`,
  // so a repo configured with `{type}-{issue}-{desc}` creates
  // `feat-41-foo` and every gwm surface that re-reads the branch has to
  // recognise it. The parser matched a hardcoded `<type>/#<issue>-<desc>`
  // instead, so the branch this very repo told gwm to create came back
  // unreadable: no gitmoji, no issue in the prefix.
  //
  // Slash-less is the point, not an edge case — `-` sits in neither the
  // type charset (`[a-z]+`) nor the issue charset (`\d+`), so the split is
  // unambiguous and there is no reason for it to fail.
  let (dir, _repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    "[worktree]\nbranch_pattern = \"{type}-{issue}-{desc}\"\n",
  )
  .expect("seed .gwm.toml");

  let mut cmd = Command::cargo_bin("gwm").unwrap();
  cmd
    .current_dir(dir.path())
    .args(["commit-prefix", "--branch", "feat-41-foo"]);
  cmd
    .assert()
    .success()
    .stdout(predicate::str::contains(":sparkles: feat(#41):"));
}

#[test]
fn commit_prefix_never_echoes_control_bytes_from_the_branch_pattern() {
  // Codex review on PR #476. `branch_pattern` comes from a repo's `.gwm.toml`
  // and `gwm commit-prefix` does not go through the TOFU trust gate, so
  // running it inside a repo you have not vetted must stay safe. Both errors
  // #417 added quote the pattern, and quoting it raw hands an unvetted config
  // the same terminal escape channel (OSC 52 clipboard write, screen clear)
  // that `branch_pattern_warning` already neutralises.
  let (dir, _repo) = init_repo();
  // OSC 52 clipboard-write shape: ESC ] 52 ; c ; <payload> BEL
  std::fs::write(
    dir.path().join(".gwm.toml"),
    // TOML basic-string escapes: `\u001B` is ESC, `\u0007` is BEL. Written this
    // way rather than as raw bytes because TOML forbids control characters
    // inside a string, and a config that fails to parse would fall back to the
    // default pattern and quietly make this test vacuous.
    "[worktree]\nbranch_pattern = \"{type}/{desc}\\u001B]52;c;cHduZWQ=\\u0007\"\n",
  )
  .expect("seed .gwm.toml");

  // A branch that does not match, so the "does not match this pattern" error
  // fires and quotes the pattern.
  let assert = Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["commit-prefix", "--branch", "nothing-like-it"])
    .assert()
    .failure();
  let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
  assert!(
    !stderr.chars().any(|c| c.is_control() && c != '\n'),
    "no control character may reach the terminal: {:?}",
    stderr
  );

  // …and the "carries no {issue}" error, which quotes it too.
  let assert = Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["commit-prefix", "--branch", "feat/x"])
    .assert()
    .failure();
  let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
  assert!(
    !stderr.chars().any(|c| c.is_control() && c != '\n'),
    "the second error quotes the pattern too: {:?}",
    stderr
  );
}

#[test]
fn pr_falls_back_to_chore_when_the_pattern_carries_no_type() {
  // Codex review on PR #476, second pass. Before #417 the parser either
  // matched or returned `None`, so `unwrap_or_else(|| "chore")` covered every
  // branch with no readable type. #417 let a partial pattern parse and report
  // the segments it *does* carry, which hands `gwm pr` a `Some` holding an
  // empty type — and an empty type selects no `[pr_template.by_type]` entry
  // and renders `{type}` blank. The fallback has to survive the loosening.
  let (dir, repo) = init_repo();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    "[worktree]\nbranch_pattern = \"{issue}-{desc}\"\n\n\
     [pr_template.by_type.chore]\nbody = \"chore body for {desc} (#{issue})\\n\"\n",
  )
  .expect("seed .gwm.toml");
  make_feature_branch_with_commit(&repo, dir.path(), "42-tidy-up", "note.md", "x\n", "🔧 chore: tidy");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .args(["pr", "--render"])
    .assert()
    .success()
    .stdout(predicate::str::contains("chore body for tidy-up (#42)"));
}

// ---------------------------------------------------------------------
// Issue #477 — `worktree::discover_repo` walks back to the main working
// directory when it lands inside a linked worktree, which is right for
// every command operating on the whole worktree *set* (`list`, `remove`,
// `switch`, `prune`). Commands that instead ask "which branch am I on"
// were reading that handle's HEAD, so from inside a worktree they
// answered with the main checkout's branch.
//
// `gwm commit-prefix` is the one that hurts: the bundled `commit-msg`
// hook calls it, and git invokes that hook with the working directory
// inside the worktree, so committing from a worktree derived the prefix
// from whatever the main checkout happened to be sitting on.
//
// Pre-existing, measured against the published 1.5.0 binary in the issue
// and re-measured against this branch's build before the fix.
// ---------------------------------------------------------------------

/// The reproduction from the issue, as a test. `repo_with_one_worktree`
/// leaves the main checkout on its default branch and the worktree on
/// `feat/#1-wt`; before the fix this errored out saying the *main*
/// branch carried no type to read.
#[test]
fn commit_prefix_reads_the_branch_of_the_worktree_it_runs_in() {
  let (_dir, _base, wt) = repo_with_one_worktree();

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(&wt)
    .args(["commit-prefix", "--unicode"])
    .assert()
    .success()
    .stdout(predicate::str::contains("feat(#1):"));
}

/// Same handle, same defect, different symptom: `cmd_pr` falls back to
/// the `chore` template when the branch does not parse, so reading the
/// main checkout's branch surfaced as "no pr_template configured for
/// branch type 'chore'" rather than as a wrong branch name.
#[test]
fn pr_reads_the_branch_of_the_worktree_it_runs_in() {
  let (dir, _base, wt) = repo_with_one_worktree();
  let cfg = dir.path().join(".gwm.toml");
  let mut body = std::fs::read_to_string(&cfg).expect("seeded config");
  body.push_str("\n[pr_template.by_type.feat]\nbody = \"GWM_PROBE head={head} type={type} issue={issue}\\n\"\n");
  std::fs::write(&cfg, body).expect("append a template");

  // Selecting the `feat` entry at all is half the assertion: before the fix
  // the main checkout's branch did not parse, the type fell back to `chore`,
  // and this errored with "no pr_template configured for branch type
  // 'chore'". `{head}` then pins the branch itself, not just its type.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(&wt)
    .args(["pr", "--render"])
    .assert()
    .success()
    .stdout(predicate::str::contains("GWM_PROBE head=feat/#1-wt type=feat issue=1"));
}

/// 🔴 The over-correction guard. Only the *branch* comes from the
/// invoking checkout. `.gwm.toml`, the workdir and `worktree::repo_name`
/// all legitimately want the main repo, and `{repo}` is a legal token in
/// `branch_pattern`, so a fix that discovered from the current directory
/// everywhere would compile the parser with the *worktree directory's*
/// name and stop reading a branch gwm itself wrote.
///
/// Under `{type}/#{issue}-{desc}-{repo}` the worktree directory is named
/// `feat-1-wt` while the repo is not, so the two names cannot be
/// confused: this passes only if the parser was handed the main repo's.
///
/// `{repo}` sits at the end rather than leading the branch because
/// `init_repo` builds on `TempDir`, whose basename starts with `.` on
/// macOS, and git refuses a ref component that does. Inside a component
/// the same character is fine.
#[test]
fn only_the_branch_comes_from_the_worktree_the_repo_name_still_comes_from_the_main_checkout() {
  let (dir, _repo) = init_repo();
  let base = tempfile::TempDir::new().unwrap();
  let repo_name = dir.path().file_name().unwrap().to_string_lossy().to_string();
  std::fs::write(
    dir.path().join(".gwm.toml"),
    format!(
      "[worktree]\nbase = \"{base}\"\n\
       path_pattern = \"{{type}}-{{issue}}-{{desc}}\"\n\
       branch_pattern = \"{{type}}/#{{issue}}-{{desc}}-{{repo}}\"\n",
      base = toml_basic_string(base.path()),
    ),
  )
  .expect("seed .gwm.toml");

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["create", "feat", "1", "wt"])
    .assert()
    .success();
  let wt = base.path().join("feat-1-wt");
  assert!(
    wt.join(".git").exists(),
    "precondition: the worktree exists and is named after `path_pattern`, not the repo"
  );
  assert_ne!(
    repo_name, "feat-1-wt",
    "precondition: the two names differ, or the assertion below proves nothing"
  );

  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(&wt)
    .args(["commit-prefix", "--unicode"])
    .assert()
    .success()
    .stdout(predicate::str::contains("feat(#1):"));
}

/// The sweep the issue asked for ("worth checking whether the same
/// handle is used for anything else that is position-dependent") found a
/// third site with a *different* symptom: `cmd_bootstrap` never resolved
/// a branch at all unless the target came from a fuzzy pattern, so hooks
/// received an empty `{branch}` / `{type}` / `{issue}` rather than the
/// wrong one. Two of its three target paths were affected, measured
/// against this branch's build: no argument (the worktree is the CWD),
/// and an argument that is already a directory. Only the fuzzy path,
/// which reads the branch off the worktree record, was correct.
#[test]
fn bootstrap_gives_hooks_the_branch_of_the_worktree_it_targets() {
  let (dir, _base, wt) = repo_with_one_worktree();
  let cfg = dir.path().join(".gwm.toml");
  let mut body = std::fs::read_to_string(&cfg).expect("seeded config");
  body.push_str(
    "\n[[hooks.post_bootstrap]]\nname = \"probe\"\n\
     run = \"echo GWM_PROBE branch=[{branch}] type=[{type}] issue=[{issue}]\"\n",
  );
  std::fs::write(&cfg, body).expect("append a hook");

  let expected = "GWM_PROBE branch=[feat/#1-wt] type=[feat] issue=[1]";

  // No argument: the worktree is the current directory.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(&wt)
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .arg("bootstrap")
    .assert()
    .success()
    .stdout(predicate::str::contains(expected));

  // An argument that is already a directory, from the main checkout.
  // This one is not about where the command runs: the path was given
  // outright and its branch was simply never looked up.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .arg("bootstrap")
    .arg(&wt)
    .assert()
    .success()
    .stdout(predicate::str::contains(expected));

  // The fuzzy path already worked; it is here so a future change cannot
  // fix the two above by breaking the one that was right.
  Command::cargo_bin("gwm")
    .unwrap()
    .current_dir(dir.path())
    .env("GWM_ALLOW_BOOTSTRAP", "1")
    .args(["bootstrap", "feat-1"])
    .assert()
    .success()
    .stdout(predicate::str::contains(expected));
}