gwm-cli 1.6.1

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
use crate::bootstrap::{self, BootstrapCtx};
use crate::clean;
use crate::config::Config;
use crate::config_cli;
use crate::doctor::{self, CheckStatus, DoctorCtx};
use crate::error::{GwmError, LinkKind, Result};
use crate::exec;
use crate::forge;
use crate::github::{self, BranchLink, IssueState, IssueStatus, LinkSource, PrState, PrStatus};
use crate::gitmoji;
use crate::history::{self, OpEntry};
use crate::hooks;
use crate::issue_templates;
use crate::json_api;
use crate::labels::{self, LabelDiff};
use crate::lifecycle::{self, HookContext, HookPhase, HookSkips};
use crate::milestones::{self, MilestoneDiff};
use crate::multiplexer::{
  build_tmux_command, build_zellij_command, detect_tmux, detect_zellij, Multiplexer, SpawnMode,
};
use crate::naming::{BranchSpec, WorktreeName};
use crate::pr_templates::{self, PrTemplateContext};
use crate::presets;
use crate::review;
use crate::sync::{self, SyncAction, SyncReport, SyncStrategy};
use crate::trust::{self, TrustLedger, TrustMode, TrustOutcome};
use crate::workspace;
use crate::worktree;
use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use clap_complete::{generate, Shell};
use git2::Repository;
use std::io;
use std::path::{Path, PathBuf};

#[derive(Debug, Parser)]
#[command(name = "gwm", version, about = "git worktree manager (TUI + CLI)")]
pub struct Cli {
  /// Skip the TOFU trust prompt on `.gwm.toml` (issue #95).
  ///
  /// Equivalent to `GWM_ALLOW_BOOTSTRAP=1`. Use in non-interactive
  /// environments (CI runners, scripted workflows) where there is no
  /// human to answer the prompt. Off by default — the threat model is
  /// arbitrary RCE via `[[bootstrap.command]]` lines from an untrusted
  /// remote, so the safe default is "prompt".
  #[arg(long, global = true)]
  pub allow_bootstrap: bool,

  /// Refuse to run `.gwm.toml` bootstrap regardless of trust state
  /// (issue #95). Useful for forensic inspection of an unfamiliar
  /// repo: `gwm bootstrap --deny-bootstrap` short-circuits the
  /// execution path even if the ledger says trusted.
  #[arg(long, global = true, conflicts_with = "allow_bootstrap")]
  pub deny_bootstrap: bool,

  /// Operate across every git repo one level below <DIR> (issue #36).
  ///
  /// Workspace mode is an orthogonal dimension on top of single-repo
  /// mode: `gwm --workspace ~/Projects` opens the TUI over every
  /// direct-child repo, and `gwm list --workspace ~/Projects` prints
  /// the merged worktree table with a leading `REPO` column.
  /// `.gwm.toml` stays per-repo — there is no workspace-level config.
  /// `global = true` so the flag is accepted before or after the
  /// subcommand.
  #[arg(long, global = true, value_name = "DIR")]
  pub workspace: Option<PathBuf>,

  #[command(subcommand)]
  pub command: Option<Command>,
}

/// Sub-actions of `gwm agents` (issue #408 US4). Bare `gwm agents` lists.
#[derive(Debug, Clone, clap::Subcommand)]
pub enum AgentsAction {
  /// Pin session SESSION_ID to the worktree matching PATTERN. The pin
  /// overlays auto-detection and ACCUMULATES — several sessions can be
  /// pinned to one worktree.
  Attach {
    /// Worktree name (substring match), or `.` for the enclosing worktree.
    pattern: String,
    /// Session id as shown by `gwm agents`.
    session_id: String,
  },
  /// Remove pin(s) from the worktree matching PATTERN: the one named by
  /// SESSION_ID, or every pin when omitted.
  Detach {
    /// Worktree name (substring match), or `.` for the enclosing worktree.
    pattern: String,
    /// Specific pinned session id to remove (all pins when omitted).
    session_id: Option<String>,
  },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum AgentsFormat {
  /// Human-readable listing (default).
  Table,
  /// Machine-readable JSON — the same worktree rows as
  /// `gwm list --format=json` (experimental `agents` field included).
  Json,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum ListFormat {
  /// Human-readable table (default).
  Table,
  /// One worktree name per line — suitable for shell completion.
  Names,
  /// Machine-readable JSON array of worktrees (issue #38). Stable schema
  /// documented under `docs/schema/worktree-list.schema.json`.
  Json,
}

/// Output format for commands that have only a human-readable text form
/// and a machine-readable JSON form (`gwm path`, `gwm doctor` — issue #38).
/// Distinct from [`ListFormat`], which also carries the `names` variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum OutputFormat {
  /// Human-readable text (default).
  Text,
  /// Machine-readable JSON. Stable schema documented under `docs/schema/`.
  Json,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum InitShell {
  Bash,
  Zsh,
  Fish,
  Powershell,
}

/// Target of `gwm link / unlink / open` — issue or pull request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum LinkTarget {
  /// GitHub issue.
  Issue,
  /// GitHub pull request.
  Pr,
}

#[derive(Debug, Subcommand)]
pub enum Command {
  /// Write a .gwm.toml to the current repo, optionally from a stack preset.
  Init {
    /// Seed an opinionated .gwm.toml for a known stack (e.g. `laravel`,
    /// `node`/`nuxt`, `rust`, `go`, `python-uv`). Omit for the generic
    /// documented template. Run `gwm init --list-presets` to see them all.
    #[arg(long, value_name = "NAME")]
    preset: Option<String>,
    /// List the built-in presets with one-line descriptions and exit
    /// (writes nothing, needs no git repo).
    #[arg(long)]
    list_presets: bool,
    /// Print the resolved preset to stdout instead of writing .gwm.toml —
    /// handy for diffing a preset against an existing config.
    #[arg(long)]
    show: bool,
  },
  /// List worktrees in the current repo.
  List {
    /// Output format. `names` prints one worktree name per line (for shell completion).
    #[arg(long, value_enum, default_value_t = ListFormat::Table)]
    format: ListFormat,
    /// Add a PR column, auto-detecting each worktree's pull request via
    /// `gh pr list --head <branch>` (issue #181). Off by default: it
    /// makes one `gh` call per worktree, so the plain listing stays
    /// network-free. Ignored with `--format names`.
    #[arg(long)]
    detect_pr: bool,
  },
  /// Agent sessions per worktree (issue #408): list what detection found,
  /// or pin/unpin a session manually. Detection reads each agent's on-disk
  /// session artefacts (Claude Code, Codex, opencode, Mistral Vibe) — a pin
  /// overlays it for the cases the recorded directory cannot cover.
  Agents {
    #[command(subcommand)]
    action: Option<AgentsAction>,
    /// Output format for the listing (ignored by attach/detach).
    #[arg(long, value_enum, default_value_t = AgentsFormat::Table)]
    format: AgentsFormat,
  },
  /// Create a new worktree (and matching branch).
  Create {
    /// Branch type (feat, fix, hotfix, docs, test, refactor, chore, perf, ci, build).
    #[arg(required_unless_present = "name", conflicts_with = "name")]
    branch_type: Option<String>,
    /// Issue number (digits only).
    #[arg(required_unless_present = "name", conflicts_with = "name")]
    issue: Option<String>,
    /// Short description (kebab-case, will be normalized).
    #[arg(required_unless_present = "name", conflicts_with = "name")]
    desc: Option<String>,
    /// Name the worktree freely instead of using the <TYPE> <ISSUE> <DESC>
    /// triple (issue #416), e.g. `gwm create --name spike-redis`. The name
    /// becomes the branch verbatim; `branch_pattern` / `path_pattern` do not
    /// apply because it has no `{type}` / `{issue}` / `{desc}` to expand.
    /// Features that read the branch name back (issue auto-linking, gitmoji)
    /// stay inactive on it — `gwm link` remains available.
    ///
    /// Exclusive with the positional triple: the mode is chosen explicitly,
    /// never inferred from how many arguments were supplied.
    #[arg(long, value_name = "NAME", conflicts_with_all = ["branch_type", "issue", "desc"])]
    name: Option<String>,
    /// Skip bootstrap after creation.
    #[arg(long)]
    no_bootstrap: bool,
    /// Attach the new worktree to an already-existing local branch of the
    /// same name instead of refusing (issue #99). Off by default — a
    /// pre-existing branch ends `gwm create` with an error naming the
    /// stale tip so the user can audit it.
    #[arg(long)]
    reuse_branch: bool,
    /// Skip lifecycle hooks for comma-separated phases (e.g. pre_create,post_create).
    #[arg(long, value_name = "PHASES")]
    skip_hooks: Option<String>,
    /// In workspace mode (`--workspace <dir>`), which child repo gets the
    /// new worktree (issue #36). Required there to disambiguate; ignored
    /// in single-repo mode, where the worktree always lands in the
    /// discovered repo.
    #[arg(long, value_name = "NAME")]
    repo: Option<String>,
  },
  /// Render the PR body from `[pr_template]` (issue #84), then
  /// `gh pr create` unless `--render` is passed.
  ///
  /// Without `--render`, the rendered Markdown is written to a temp
  /// file and shelled out to `gh pr create --title <subject> --body-file
  /// <tmp> --head <branch>` (plus `--draft` and `--base` when
  /// specified). The body resolution honours
  /// `[pr_template.by_type.<type>]` (inline `body` wins over per-type
  /// `path`), then `[pr_template].default` as a fallback.
  ///
  /// Placeholders substituted by the template engine:
  ///   `{type}` `{issue}` `{desc}` `{base}` `{head}` `{repo}`
  ///   `{commits}`        — `git log --pretty='- %s' base..head`
  ///   `{files_changed}`  — `git diff --stat base..head`, capped 30 lines
  Pr {
    /// Render the body to stdout instead of creating the PR. The output
    /// is suitable for piping into `gh pr create --body-file -`.
    #[arg(long)]
    render: bool,
    /// Create the PR as a draft (shells out to `gh pr create --draft`).
    /// Ignored when `--render` is set.
    #[arg(long, conflicts_with = "render")]
    draft: bool,
    /// Override the base ref to compare against (defaults to the
    /// resolved trunk from `[doctor].trunks`, then `main`).
    #[arg(long, value_name = "REF")]
    base: Option<String>,
  },
  /// Materialise an existing GitHub PR into an isolated worktree (issue #308).
  ///
  /// Resolves the PR head via `gh` and fetches origin's universal
  /// `refs/pull/<N>/head` ref — cross-fork aware, and valid for PRs in any
  /// state (open / draft / closed / merged) — into a local
  /// `review/pr-<N>-<author>-<slug>` branch, attaches a worktree, and links
  /// the PR so the sidebar / CI indicator light up immediately. Tear down
  /// with `gwm remove <dir> --delete-branch` like any worktree.
  ///
  /// Safe-by-default: bootstrap and lifecycle hooks are NOT run, because a
  /// review worktree holds a contributor's (possibly fork) code and those
  /// steps execute commands against it (`npm install`, `composer install`,
  /// `direnv allow`, `post_create` hooks …) — i.e. arbitrary code. Pass
  /// `--bootstrap` to opt in once you trust the PR enough to set it up.
  Review {
    /// PR number to review (digits only).
    #[arg()]
    number: u64,
    /// Override the local review branch name (defaults to
    /// `review/pr-<N>-<author>-<slug>`). The worktree directory is derived
    /// from this name (slashes become dashes).
    #[arg(long, value_name = "BRANCH")]
    name: Option<String>,
    /// Run bootstrap + lifecycle hooks against the PR's code after creation.
    /// Off by default — these execute commands the PR can influence, so it's
    /// opt-in (see the command help for the security rationale).
    #[arg(long)]
    bootstrap: bool,
    /// Skip lifecycle hooks for comma-separated phases (e.g. pre_create,post_create).
    #[arg(long, value_name = "PHASES")]
    skip_hooks: Option<String>,
  },
  /// Create a GitHub issue from templates, then create its worktree.
  New {
    /// Branch type (feat, fix, hotfix, docs, test, refactor, chore, perf, ci, build).
    #[arg()]
    branch_type: String,
    /// Short description (kebab-case, will be normalized).
    #[arg()]
    desc: String,
    /// Skip bootstrap after creation.
    #[arg(long)]
    no_bootstrap: bool,
    /// Attach the new worktree to an already-existing local branch of the same name.
    #[arg(long)]
    reuse_branch: bool,
    /// Skip lifecycle hooks for comma-separated phases (e.g. pre_create,post_create).
    #[arg(long, value_name = "PHASES")]
    skip_hooks: Option<String>,
  },
  /// Remove a worktree by fuzzy name match.
  Remove {
    pattern: String,
    /// Also delete the branch.
    #[arg(long)]
    delete_branch: bool,
    /// Print the resolved worktree (name + path + branch + would-delete-branch
    /// flag) without touching anything. Exit code 0. If the pattern is
    /// ambiguous, the same non-zero candidate-list error fires as in the
    /// destructive form — `--dry-run` only suppresses *destruction*, not
    /// resolution failures. Issue #31.
    #[arg(long)]
    dry_run: bool,
    /// Emergency removal mode: skip pre_remove and post_remove hooks.
    #[arg(long)]
    force: bool,
    /// Skip lifecycle hooks for comma-separated phases.
    #[arg(long, value_name = "PHASES")]
    skip_hooks: Option<String>,
  },
  /// Print the on-disk path of a worktree (use `$(gwm path …)` to cd into it).
  ///
  /// Also available as `gwm cd <pattern>` — same semantics, framed for the
  /// cd flow. Pair with `gwm shell-init <shell>` for a one-line wrapper.
  #[command(visible_alias = "cd")]
  Path {
    pattern: String,
    /// Output format. `json` emits `{ name, path, branch }` (issue #38);
    /// the default `text` prints the bare path for shell consumption.
    #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
    format: OutputFormat,
  },
  /// Re-run bootstrap on an existing worktree.
  Bootstrap {
    /// Worktree path or name; defaults to CWD.
    target: Option<String>,
    /// Skip lifecycle hooks for comma-separated phases.
    #[arg(long, value_name = "PHASES")]
    skip_hooks: Option<String>,
  },
  /// Fetch + rebase (or merge) a worktree's branch onto its upstream.
  ///
  /// Resolves the target worktree (defaults to the CWD worktree when
  /// no pattern is given), runs `git fetch` for its upstream's remote,
  /// then rebases the branch onto the upstream — or merges with
  /// `--merge`. Reports the outcome with the same ✓ / ! / ✗ sigils as
  /// the rest of gwm.
  ///
  /// Refuses up front on a dirty working tree (commit or stash first)
  /// and on a branch with no upstream configured. A conflicting
  /// rebase/merge is aborted so the worktree stays usable, and the
  /// user is told to reconcile by hand. Issue #24.
  Sync {
    /// Worktree name/pattern; defaults to the worktree containing the CWD.
    pattern: Option<String>,
    /// Merge the upstream instead of rebasing onto it.
    #[arg(long)]
    merge: bool,
  },
  /// Prune stale worktree references (admin files without a working dir).
  Prune {
    /// List the prunable worktrees (name + path + reason) without
    /// touching the admin entries. Exit code 0. Useful for piping into
    /// a confirmation script before running the destructive form.
    /// Issue #31.
    #[arg(long)]
    dry_run: bool,
  },
  /// Diagnose the gwm setup (config, env, worktree state).
  ///
  /// Exit code 0 if all green, 1 if any warning, 2 if any failure —
  /// suitable for CI / pre-commit hooks.
  Doctor {
    /// Output format. `json` emits the checks array plus aggregate
    /// `severity` / `exit_code` (issue #38); the default `text` prints
    /// the sigil-prefixed report. The process exit code is identical
    /// either way.
    #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
    format: OutputFormat,
  },
  /// Run a long-running JSON-RPC 2.0 daemon over a local transport.
  ///
  /// Editors, statusbars, and tooling connect once and call `list` /
  /// `doctor` / `path`, or `subscribe` for pushed `worktrees.changed`
  /// notifications — instead of spawning `gwm` per query (issue #38).
  /// Newline-delimited JSON, one request and one response per line.
  ///
  /// The transport is a unix domain socket on unix and a named pipe under
  /// `\\.\pipe\` on Windows (issue #439). Built behind the default-on
  /// `daemon` feature; a `--no-default-features` build exits with an
  /// explanatory error.
  Daemon {
    /// Where to bind. On unix: a socket path, defaulting to
    /// `$XDG_RUNTIME_DIR/gwm.sock`, falling back to `$TMPDIR`, then
    /// `/tmp` — isolated in a per-user `<base>/gwm-<uid>/gwm.sock` when
    /// the base dir is not owner-only. On Windows: the pipe NAME under
    /// `\\.\pipe\` (not a filesystem path), defaulting to
    /// `gwm-<user>.sock`, restricted to the owner by its security
    /// descriptor.
    #[arg(long, value_name = "PATH")]
    socket: Option<PathBuf>,
    /// Worktree-state poll interval in milliseconds for `subscribe` push
    /// notifications. Lower = faster updates, more git scans. This MVP
    /// polls rather than watching the filesystem (no `notify` dep).
    /// Must be ≥ 1: `0` would spin a `subscribe` loop with no wait,
    /// re-scanning git as fast as the CPU allows (issue #38 review).
    #[arg(long, value_name = "MS", default_value_t = 1000, value_parser = clap::value_parser!(u64).range(1..))]
    poll_ms: u64,
  },
  /// Print a compact one-line worktree summary for shell prompts (issue #309).
  ///
  /// The first real consumer of `gwm daemon`: it connects to the daemon's
  /// transport (unix socket, or a named pipe on Windows, issue #439), asks
  /// for the worktree set, and renders a single line —
  /// active branch, worktree count, dirty / ahead / behind, linked issue /
  /// PR — suitable for a tmux / starship / zsh statusline. With `--watch`
  /// it subscribes to the daemon's `worktrees.changed` stream and reprints
  /// on every change (one line per update).
  ///
  /// Needs a running `gwm daemon` (one per repo). When none is reachable it
  /// prints an empty line and exits 0, so a prompt substitution degrades to
  /// nothing instead of erroring. A CI rollup is intentionally not shown —
  /// it is not part of the daemon's stable schema.
  Statusline {
    /// Daemon socket path (unix) or pipe name (Windows). Defaults to the
    /// same resolution as `gwm daemon`: `$XDG_RUNTIME_DIR/gwm.sock`, then
    /// `$TMPDIR`, then `/tmp` — isolated in a per-user
    /// `<base>/gwm-<uid>/gwm.sock` when the base dir isn't owner-only —
    /// and `gwm-<user>.sock` under `\\.\pipe\` on Windows.
    #[arg(long, value_name = "PATH")]
    socket: Option<PathBuf>,
    /// Stream live updates: subscribe to `worktrees.changed` and reprint
    /// the line on every change instead of printing once and exiting.
    #[arg(long)]
    watch: bool,
  },
  /// List the supported branch types.
  ///
  /// Pass `--gitmoji` to extend the output with two more columns: the
  /// resolved emoji (unicode) and its `:shortcode:` form (issue #85).
  /// The shortcode mapping is the built-in default plus any per-repo
  /// overrides under `[gitmoji]` in `.gwm.toml`.
  Types {
    /// Show the resolved emoji + shortcode for each branch type
    /// (issue #85). Without the flag, only `name` + `description`
    /// are printed — matches the pre-#85 surface.
    #[arg(long)]
    gitmoji: bool,
  },
  /// Print the Gitmoji + Conventional Commits prefix for the current
  /// (or named) branch (issue #85).
  ///
  /// Output shape: `:sparkles: feat(#41):` — the canonical commit
  /// prefix used across this repo (see CONTRIBUTING.md §Commits).
  /// `--unicode` substitutes the shortcode for the real emoji
  /// character (e.g. `✨` instead of `:sparkles:`); useful for shell
  /// prompts and the bundled `commit-msg` hook.
  ///
  /// Without `--branch`, reads the current branch from HEAD via
  /// libgit2 — requires the CWD to be inside a git repo.
  CommitPrefix {
    /// Branch name to resolve (e.g. `feat/#41-tui-search`). When
    /// omitted, defaults to HEAD of the current repo.
    #[arg(long)]
    branch: Option<String>,
    /// Emit the real emoji character (`✨`) instead of the
    /// shortcode form (`:sparkles:`).
    #[arg(long)]
    unicode: bool,
  },
  /// Manage git hooks installed by `gwm` (issue #85).
  ///
  /// Currently exposes a single hook: `commit-msg`, which
  /// auto-prepends the resolved Gitmoji + Conventional Commits
  /// prefix when the commit message doesn't already start with one.
  /// Hooks are **opt-in** — `gwm` never installs them implicitly.
  Hooks {
    #[command(subcommand)]
    action: HooksAction,
  },
  /// Generate a shell completion script on stdout.
  ///
  /// Install (zsh):  `gwm completions zsh > $fpath[1]/_gwm`
  /// Install (bash): `gwm completions bash > /etc/bash_completion.d/gwm`
  /// Install (fish): `gwm completions fish > ~/.config/fish/completions/gwm.fish`
  Completions {
    /// Target shell.
    #[arg(value_enum)]
    shell: Shell,
  },
  /// Print a shell wrapper exposing `gcd <pattern>` (one-line cd into a worktree).
  ///
  /// Install (zsh):        `echo 'eval "$(gwm shell-init zsh)"' >> ~/.zshrc`
  /// Install (bash):       `echo 'eval "$(gwm shell-init bash)"' >> ~/.bashrc`
  /// Install (fish):       `gwm shell-init fish | source` (also add to config.fish)
  /// Install (powershell): `Invoke-Expression (& gwm shell-init powershell | Out-String)`
  ShellInit {
    /// Target shell.
    #[arg(value_enum)]
    shell: InitShell,
  },
  /// Open an interactive picker; print the chosen worktree's path on stdout.
  ///
  /// Same TUI as `gwm` itself, minus the create / delete / bootstrap actions.
  /// The fuzzy filter bar opens immediately so typing narrows the list right
  /// away. Press Enter to commit the highlighted pick; Esc / Ctrl-C / `q`
  /// quits without printing anything (exit code 1).
  ///
  /// Typically invoked via `gcd` (no arg) from the bundled `gwm shell-init`
  /// wrapper, which cd's into the picked worktree in one keystroke. The raw
  /// form is `cd "$(gwm switch)"` (or `gwm s`, the alias).
  #[command(visible_alias = "s")]
  Switch,
  /// Open the matched worktree in a new tmux window (current session).
  ///
  /// Requires `$TMUX` to be set — i.e. gwm must be invoked from inside an
  /// existing tmux session. Outside a tmux session the command exits
  /// non-zero with a clear error rather than spawning a stray server.
  /// Use `--split` to open in a horizontal split of the current pane
  /// instead of a new window.
  Tmux {
    /// Fuzzy worktree name pattern (same matcher as `gwm path / remove`).
    pattern: String,
    /// Split the current pane instead of opening a new window.
    #[arg(short = 'p', long = "split")]
    split: bool,
  },
  /// Open the matched worktree in a new zellij tab (current session).
  ///
  /// Requires `$ZELLIJ` to be set. `--cwd` on `zellij action new-tab`
  /// needs zellij ≥ 0.40. Use `--split` to open in a new pane of the
  /// current tab instead of a new tab.
  Zellij {
    /// Fuzzy worktree name pattern (same matcher as `gwm path / remove`).
    pattern: String,
    /// Split the current tab into a new pane instead of opening a new tab.
    #[arg(short = 'p', long = "split")]
    split: bool,
  },
  /// Link the current (or named) worktree to a GitHub issue or pull request.
  ///
  /// The link is stored in `git config branch.<name>.gwm-issue` (or
  /// `gwm-pr`) — local, per-branch, survives worktree moves. Issue
  /// numbers are auto-detected from the `<type>/#<N>-<slug>` convention
  /// when no explicit override is set; `gwm link issue <N>` overrides
  /// that. PR numbers are not auto-detected; link them explicitly with
  /// `gwm link pr <N>`.
  Link {
    /// What to link: `issue` or `pr`.
    #[arg(value_enum)]
    target: LinkTarget,
    /// Number to link (digits only).
    number: u64,
    /// Optional worktree pattern; defaults to the current worktree (CWD).
    #[arg(long)]
    worktree: Option<String>,
  },
  /// Remove the explicit issue / PR link on the current (or named) worktree.
  ///
  /// After `gwm unlink issue`, auto-detection from the branch name
  /// resurfaces if the branch follows `<type>/#<N>-<slug>`. Idempotent —
  /// safe to run when nothing is linked.
  Unlink {
    /// What to unlink: `issue` or `pr`.
    #[arg(value_enum)]
    target: LinkTarget,
    /// Optional worktree pattern; defaults to the current worktree (CWD).
    #[arg(long)]
    worktree: Option<String>,
  },
  /// Open the linked issue or PR in the browser.
  ///
  /// Uses the OS opener (`open` on macOS, `xdg-open` on Linux,
  /// `explorer` on Windows). Pass `--print-url` to emit the URL on
  /// stdout instead — useful for piping, testing, and headless shells.
  Open {
    /// What to open: `issue` or `pr`.
    #[arg(value_enum)]
    target: LinkTarget,
    /// Optional worktree pattern; defaults to the current worktree (CWD).
    #[arg(long)]
    worktree: Option<String>,
    /// Print the URL on stdout instead of spawning the browser.
    #[arg(long)]
    print_url: bool,
  },
  /// Show the issue / PR link and (when `gh` is available) live GitHub status.
  ///
  /// Shells out to `gh issue view` and `gh pr view` to fetch state, title,
  /// labels, and CI rollup. Without `gh` (or outside a GitHub repo), prints
  /// only the local link. `--json` emits a stable schema for scripting.
  Status {
    /// Optional worktree pattern; defaults to the current worktree (CWD).
    #[arg(long)]
    worktree: Option<String>,
    /// Emit JSON instead of the human-readable summary.
    #[arg(long)]
    json: bool,
  },
  /// Manage the declarative GitHub label set from `.gwm.toml` (issue #81).
  ///
  /// Declares the desired label set under `[[labels]]` in `.gwm.toml`,
  /// then pushes it to the upstream `origin` remote via `gh label
  /// create --force`. Without a `[[labels]]` block, both subcommands
  /// are no-ops (`0 labels declared, nothing to push`).
  Labels {
    #[command(subcommand)]
    action: LabelsAction,
  },
  /// Manage the declarative GitHub milestone set from `.gwm.toml` (issue #82).
  ///
  /// Declares the desired milestone set under `[[milestones]]` in
  /// `.gwm.toml`, then pushes it to the upstream `origin` remote via
  /// `gh api repos/:owner/:repo/milestones` (no native `gh milestone`
  /// subcommand exists). Without a `[[milestones]]` block, both
  /// subcommands are no-ops (`0 milestones declared, nothing to push`).
  Milestones {
    #[command(subcommand)]
    action: MilestonesAction,
  },
  /// Manage the TOFU trust ledger for `.gwm.toml` files (issue #95).
  ///
  /// `gwm` runs `[[bootstrap.command]]` lines from `.gwm.toml` under
  /// the user's privileges — equivalent to `curl … | sh` against the
  /// repo author. The trust ledger at `~/.config/gwm/trust.toml`
  /// (override via `$GWM_TRUST_LEDGER`) records the `(origin URL,
  /// sha256 of .gwm.toml)` tuples the user has approved, so
  /// subsequent runs skip the prompt. Hash drift (any byte changes
  /// in `.gwm.toml`) re-prompts — see the module-level comment in
  /// `src/trust.rs` for the threat model.
  Trust {
    #[command(subcommand)]
    action: TrustAction,
  },
  /// List the resolved CLI aliases (built-in + repo + user). Issue #86.
  ///
  /// `gwm aliases list` surfaces every alias reachable from `gwm
  /// <name>`, grouped by source: `built-in` (clap `visible_alias`
  /// set), `repo (.gwm.toml)`, `user (~/.config/gwm/aliases.toml)`.
  /// The resolution chain favours repo aliases over user aliases when
  /// both declare the same name, but both rows are still printed so
  /// the user can see what's being shadowed.
  Aliases {
    #[command(subcommand)]
    action: AliasesAction,
  },
  /// Read, edit, and validate `.gwm.toml` values (issue #89).
  Config {
    #[command(subcommand)]
    action: ConfigAction,
  },
  /// List the recent destructive operations recorded by `gwm`
  /// (issue #29). One line per op, newest first, with timestamp,
  /// kind, and worktree name.
  ///
  /// Defaults to the current repo only — pass `--all` to list ops
  /// across every repo in the journal. The journal file lives at
  /// `$GWM_HISTORY_FILE` if set, otherwise
  /// `$XDG_DATA_HOME/gwm/history.toml`.
  History {
    /// Maximum number of entries to print (newest first). Default 20.
    #[arg(long, default_value_t = 20)]
    limit: usize,
    /// Show ops across every repo, not just the current one. Useful
    /// for power users grepping the journal for forensic purposes.
    #[arg(long)]
    all: bool,
  },
  /// Undo the most recent destructive operation recorded for the
  /// current repo (issue #29). Recreates the branch at the saved
  /// OID, re-adds the worktree at the saved path, then drops the
  /// entry from the journal.
  ///
  /// Pass `--bootstrap` to re-run the per-worktree bootstrap after
  /// the resurrection (off by default — bootstrap can be expensive
  /// and the user often just wants the directory back).
  Undo {
    /// Re-run bootstrap after the worktree is re-added. Off by
    /// default to keep undo cheap.
    #[arg(long)]
    bootstrap: bool,
  },
  /// TUI introspection / debugging subcommands (issue #87).
  ///
  /// Today exposes a single child — `keys` — which prints the
  /// resolved keymap (built-in defaults layered with `[tui.keys]`
  /// overrides from `.gwm.toml`). Reserved as a sub-tree so future
  /// TUI knobs (`gwm tui themes`, `gwm tui dump-state`, …) have a
  /// stable home without further crowding the top-level surface.
  Tui {
    #[command(subcommand)]
    action: TuiAction,
  },
  /// TUI theme subcommands (issue #33).
  ///
  /// `gwm theme list` prints the names of every built-in preset.
  /// `gwm theme show <name>` dumps the preset as a `[theme]` TOML
  /// block the user can paste into `.gwm.toml`.
  Theme {
    #[command(subcommand)]
    action: ThemeAction,
  },
  /// Run a shell command in each worktree, sequentially (issue #313).
  ///
  /// `gwm exec -- git fetch` runs in every non-main worktree; pass slugs
  /// before `--` to scope it: `gwm exec feat-1 fix-2 -- cargo check`.
  /// Prints a per-worktree ✓ / ✗ rollup and exits non-zero if any
  /// worktree's command failed. Everything after `--` is forwarded
  /// verbatim (flags and all). This is the user's own command against
  /// their own worktrees — no bootstrap trust gate applies (#95).
  Exec {
    /// Worktree slugs to target (fuzzy match, before `--`). Empty = all
    /// non-main worktrees.
    #[arg(value_name = "SLUG")]
    slugs: Vec<String>,
    /// Run a saved `[exec.profiles.<name>]` command instead of an inline
    /// `-- <cmd>` (issue #324). Mutually exclusive with an inline command;
    /// an unknown name exits 1.
    #[arg(long, value_name = "NAME")]
    profile: Option<String>,
    /// Bounded parallelism (issue #324). `1` (default) runs sequentially with
    /// live, inherited output; `> 1` runs up to N worktrees at once, capturing
    /// each one's output and printing it as a block at the end. Wins over a
    /// profile's / `[exec]`'s `jobs`.
    #[arg(long, value_name = "N")]
    jobs: Option<u32>,
    /// Command to run, after `--`. Everything past `--` is forwarded
    /// verbatim, e.g. `gwm exec -- git log --oneline`. Provide either this
    /// or `--profile`, never both, and at least one.
    #[arg(last = true, allow_hyphen_values = true, value_name = "CMD")]
    command: Vec<String>,
  },
  /// Report (and optionally reclaim) heavy build artifacts across worktrees (issue #313).
  ///
  /// Scans each worktree for `target/`, `node_modules/`, `dist/`, `build/`
  /// and prints the reclaimable size per worktree. Report-only by default;
  /// pass `--yes` to actually delete. Scope to a subset with slug
  /// positionals: `gwm clean feat-1`. Deliberately not journaled into
  /// `gwm history` (#29) — the artifacts are regenerable.
  ///
  /// Safety: `--yes` only deletes directories git treats as ignored. A
  /// non-ignored `dist/` / `build/` (tracked or hand-authored, hence
  /// non-regenerable) is reported as skipped, never removed.
  Clean {
    /// Worktree slugs to target (fuzzy match). Empty = all non-main worktrees.
    #[arg(value_name = "SLUG")]
    slugs: Vec<String>,
    /// Reclaim a saved `[clean.profiles.<name>]` directory set (a COMPLETE
    /// set that replaces the built-ins) instead of `target`/`node_modules`/
    /// `dist`/`build` (issue #324). An unknown name exits 1. Without it,
    /// `[clean.profiles.default]` is used when present, else the built-ins.
    #[arg(long, value_name = "NAME")]
    profile: Option<String>,
    /// Delete the listed artifacts instead of only reporting them.
    #[arg(long)]
    yes: bool,
  },
}

/// Subcommands of `gwm theme` (issue #33).
#[derive(Debug, Subcommand)]
pub enum ThemeAction {
  /// List the names of every built-in preset.
  List,
  /// Print a preset as a copy-pasteable `[theme]` TOML block.
  Show {
    /// Preset name (`catppuccin`, `gruvbox`, `tokyo-night`, `claude-dark`, …).
    name: String,
  },
}

/// Subcommands of `gwm tui` (issue #87).
#[derive(Debug, Subcommand)]
pub enum TuiAction {
  /// Print the resolved TUI keymap (built-in defaults + `[tui.keys]`
  /// overrides, with the source per row).
  ///
  /// Output shape:
  /// ```text
  /// action            keys              source
  /// down              j, Down           default
  /// up                Ctrl+n            .gwm.toml
  /// top               g g               default
  ///  /// ```
  ///
  /// The action column lists the slugs accepted in `[tui.keys]`;
  /// the keys column shows every chord bound to that action
  /// (comma-separated). Empty keys = action is currently unbound
  /// (the user explicitly cleared it).
  Keys,
}

/// Subcommands of `gwm aliases` (issue #86). Read-only for now —
/// declarative editing of the alias set stays in TOML files where
/// users can grep / diff / version-control them. A future `add` /
/// `remove` could land if real usage justifies it.
#[derive(Debug, Subcommand)]
pub enum AliasesAction {
  /// Print the resolved alias chain (built-in / repo / user).
  ///
  /// Reads `.gwm.toml`'s `[aliases]` block (if any) and the
  /// user-level fallback `~/.config/gwm/aliases.toml` (path resolved
  /// via `$XDG_CONFIG_HOME` first, then `dirs::config_dir()`). The
  /// output is grouped by source so users can audit which file
  /// declares which mapping and where they need to edit to change
  /// it.
  List,
}

/// Subcommands of `gwm config` (issue #89).
#[derive(Debug, Subcommand)]
pub enum ConfigAction {
  /// Print a single value resolved from `.gwm.toml` plus defaults.
  Get {
    /// Dot-path key, e.g. `worktree.base` or `labels[0].name`.
    key: String,
  },
  /// Set a value while preserving TOML comments and formatting.
  Set {
    /// Dot-path key, e.g. `tui.confirm_countdown_secs`, `labels[+].name`, or `key=value`.
    key: String,
    /// TOML scalar value. Bare strings are accepted for convenience.
    value: Option<String>,
  },
  /// Remove a value so the runtime default applies.
  Unset {
    /// Dot-path key to remove.
    key: String,
  },
  /// List resolved config values.
  List {
    /// Only print keys under this dot-path prefix.
    #[arg(long)]
    prefix: Option<String>,
  },
  /// Validate `.gwm.toml` syntax and schema.
  Validate,
  /// Print the resolved `.gwm.toml` path.
  Path,
  /// Open `.gwm.toml` in `$EDITOR`.
  Edit,
}

/// Subcommands of `gwm hooks` (issue #85). The split anticipates
/// future hook variants (`pre-push`, `pre-commit`); for now only
/// `install commit-msg` is wired up, which is the directly-load-bearing
/// surface for the auto-prefix workflow.
#[derive(Debug, Subcommand)]
pub enum HooksAction {
  /// Install a hook into `.git/hooks/`. Refuses to overwrite an
  /// existing hook unless `--force` is passed, so a pre-existing
  /// husky / commitlint / pre-commit installation is preserved by
  /// default.
  Install {
    /// Which hook to install. Today only `commit-msg` is supported.
    #[arg(value_enum)]
    hook: HookKind,
    /// Replace an existing hook of the same name. Without `--force`,
    /// the command exits non-zero with the path of the conflicting
    /// hook so the user can decide.
    #[arg(long)]
    force: bool,
  },
}

/// Discriminator for `gwm hooks install <kind>`. A `ValueEnum` (rather
/// than a free-form string) so clap rejects typos at parse time
/// (`gwm hooks install commit-msge` → "invalid value … expected one
/// of: commit-msg") rather than letting the installer fail with a
/// less-actionable error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum HookKind {
  /// Auto-prepend the Gitmoji + Conventional Commits prefix when
  /// the user's commit message doesn't already start with one.
  CommitMsg,
}

/// Subcommands of `gwm labels`. The split is intentional: `list` is
/// read-only and safe to run in CI; `push` mutates the remote and
/// therefore gets `--dry-run` / `--prune` flags of its own.
#[derive(Debug, Subcommand)]
pub enum LabelsAction {
  /// Print the declared label set plus the diff against the upstream remote.
  ///
  /// Each line is one of: `+ create`, `~ update (color/desc change)`,
  /// `= match`, `- extra-on-remote`. Without a `[[labels]]` block in
  /// `.gwm.toml`, prints `0 labels declared` and exits 0 without
  /// shelling out to `gh`.
  List,
  /// Apply the diff: create new labels and update mismatched ones on
  /// the upstream remote.
  ///
  /// `--dry-run` prints the plan without mutating the remote (it
  /// still reads the remote via `gh label list` to compute the
  /// diff; only create / update / delete calls are skipped).
  /// `--prune` opt-in deletes labels on remote that aren't declared in
  /// config (off by default — destructive). `--random-colors` picks a
  /// random pastel for labels with no `color` field instead of the
  /// default deterministic hash.
  Push {
    /// Print the plan without mutating the remote. Still reads remote
    /// labels via `gh label list` to compute the diff — only the
    /// create / update / delete calls are skipped.
    #[arg(long)]
    dry_run: bool,
    /// Delete remote labels that aren't declared in `.gwm.toml`.
    /// Destructive — off by default.
    #[arg(long)]
    prune: bool,
    /// Generate a random pastel for labels with no `color` field
    /// (overrides the default deterministic-hash colour).
    #[arg(long)]
    random_colors: bool,
  },
}

/// Subcommands of `gwm trust` (issue #95). All three are read-only or
/// purely local — no network, no git mutation — so they're safe to
/// surface in CI as inspection helpers.
#[derive(Debug, Subcommand)]
pub enum TrustAction {
  /// Approve the current repo's `.gwm.toml`, recording `(origin, hash)`
  /// in the ledger without running anything.
  ///
  /// The prompt on `gwm create` / `gwm bootstrap` only fires when the
  /// file has a bootstrap surface to run, so a `.gwm.toml` that only
  /// names `forge` could never be approved that way — and since #419
  /// that key decides which host receives an authenticated call
  /// (Codex review #458). This is how you answer that question
  /// deliberately, without executing anything.
  ///
  /// Approving covers the whole file as it is now: editing `.gwm.toml`
  /// changes its hash and revokes the approval.
  Add,
  /// List every recorded `(origin, hash)` pair in the active ledger.
  ///
  /// Empty ledger prints a single line and exits 0 — the no-op fast
  /// path for fresh installs. The `trusted_at` timestamp is the
  /// audit anchor; revoke entries whose age looks suspicious with
  /// `gwm trust revoke <origin>`.
  List,
  /// Remove every entry whose `origin` matches verbatim. After revoke,
  /// the next `gwm create` / `gwm bootstrap` against that repo
  /// re-prompts — use this when you change machines, rotate
  /// credentials, or no longer trust a previously approved repo.
  Revoke {
    /// Origin URL to revoke (must match the recorded form verbatim —
    /// SSH and HTTPS flavours of the same GitHub repo are recorded as
    /// distinct entries because they ARE distinct trust paths).
    origin: String,
  },
  /// Print the active ledger path and its raw TOML contents.
  ///
  /// Honours `$GWM_TRUST_LEDGER` if set, falls back to
  /// `$XDG_CONFIG_HOME/gwm/trust.toml` (or the platform-specific
  /// equivalent). Useful when triaging "why is gwm re-prompting?"
  /// situations — eyeball the recorded hash vs. what `sha256sum
  /// .gwm.toml` produces.
  Show,
}

/// Subcommands of `gwm milestones`. Mirrors `LabelsAction`: `list` is
/// read-only and safe to run in CI; `push` mutates the remote and
/// therefore gets `--dry-run` / `--prune` flags of its own.
#[derive(Debug, Subcommand)]
pub enum MilestonesAction {
  /// Print the declared milestone set plus the diff against the upstream remote.
  ///
  /// Each line is one of: `+ create`, `~ update (due/desc/state
  /// change)`, `= match`, `- extra-on-remote`. Without a
  /// `[[milestones]]` block in `.gwm.toml`, prints `0 milestones
  /// declared` and exits 0 without shelling out to `gh`.
  List,
  /// Apply the diff: create new milestones and update mismatched ones
  /// on the upstream remote.
  ///
  /// `--dry-run` prints the plan without mutating the remote (it
  /// still reads the remote via `gh api …/milestones` to compute the
  /// diff; only create / update / delete calls are skipped).
  /// `--prune` opt-in deletes milestones on remote that aren't
  /// declared in config (off by default — destructive).
  Push {
    /// Print the plan without mutating the remote. Still reads remote
    /// milestones via `gh api` to compute the diff — only the
    /// create / update / delete calls are skipped.
    #[arg(long)]
    dry_run: bool,
    /// Delete remote milestones that aren't declared in `.gwm.toml`.
    /// Destructive — off by default.
    #[arg(long)]
    prune: bool,
  },
}

pub fn run(cli: Cli) -> Result<()> {
  // Resolve the trust mode once at dispatch time so every handler
  // that gates bootstrap sees the same value — CLI subcommands AND
  // the TUI alike, both honour the same flags. `--deny-bootstrap`
  // wins over `--allow-bootstrap` if both are passed (clap's
  // `conflicts_with` already rejects this combination at parse time
  // — the explicit ordering inside `trust::resolve_mode` is defence
  // in depth).
  let mode = trust::resolve_mode(cli.allow_bootstrap, cli.deny_bootstrap);

  // Without a subcommand, we hand off to the TUI — but with the
  // resolved mode threaded through so the TUI's bootstrap call
  // sites (`submit_create`, `bootstrap_selected`) take the same
  // trust decision as `gwm create` / `gwm bootstrap`.
  let Some(cmd) = cli.command else {
    // Explicit workspace mode (issue #36): `gwm --workspace <root>` opens the
    // TUI across every child repo.
    if let Some(root) = cli.workspace {
      return crate::tui::run_workspace(&root, mode);
    }
    // Auto-detect: bare `gwm` in a repo-free directory that holds child repos
    // offers to open it as a workspace.
    if let Some(root) = autodetect_workspace_prompt()? {
      return crate::tui::run_workspace(&root, mode);
    }
    return crate::tui::run(mode);
  };

  // `--workspace` is global (clap accepts it everywhere) but only `list`,
  // `create`, `exec`, `clean` and the bare TUI implement it. Reject it on any
  // other subcommand rather than silently ignoring it and acting on the current
  // single repo — a wrong-target footgun for destructive commands (Codex review
  // #303 P2). `exec` / `clean` fan out across child repos (issue #326).
  if cli.workspace.is_some()
    && !matches!(
      cmd,
      Command::List { .. } | Command::Create { .. } | Command::Exec { .. } | Command::Clean { .. }
    )
  {
    return Err(GwmError::WorkspaceUnsupportedCommand);
  }

  match cmd {
    Command::Init {
      preset,
      list_presets,
      show,
    } => cmd_init(preset, list_presets, show),
    Command::List { format, detect_pr } => match cli.workspace {
      Some(root) => cmd_list_workspace(&root, format, detect_pr),
      None => cmd_list(format, detect_pr),
    },
    Command::Create {
      branch_type,
      issue,
      desc,
      name,
      no_bootstrap,
      reuse_branch,
      skip_hooks,
      repo,
    } => {
      let start = match &cli.workspace {
        Some(root) => Some(resolve_workspace_create_repo(root, repo)?),
        None => None,
      };
      cmd_create(
        branch_type,
        issue,
        desc,
        name,
        no_bootstrap,
        reuse_branch,
        skip_hooks,
        mode,
        start.as_deref(),
      )
    }
    Command::New {
      branch_type,
      desc,
      no_bootstrap,
      reuse_branch,
      skip_hooks,
    } => cmd_new(branch_type, desc, no_bootstrap, reuse_branch, skip_hooks, mode),
    Command::Pr { render, draft, base } => cmd_pr(render, draft, base),
    Command::Review {
      number,
      name,
      bootstrap,
      skip_hooks,
    } => cmd_review(number, name, bootstrap, skip_hooks, mode),
    Command::Remove {
      pattern,
      delete_branch,
      dry_run,
      force,
      skip_hooks,
    } => cmd_remove(pattern, delete_branch, dry_run, force, skip_hooks, mode),
    Command::Path { pattern, format } => cmd_path(pattern, format),
    Command::Bootstrap { target, skip_hooks } => cmd_bootstrap(target, skip_hooks, mode),
    Command::Sync { pattern, merge } => cmd_sync(pattern, merge),
    Command::Prune { dry_run } => cmd_prune(dry_run),
    Command::Agents { action, format } => cmd_agents(action, format),
    Command::Doctor { format } => cmd_doctor(format),
    Command::Daemon { socket, poll_ms } => cmd_daemon(socket, poll_ms),
    Command::Statusline { socket, watch } => cmd_statusline(socket, watch),
    Command::Types { gitmoji } => cmd_types(gitmoji),
    Command::CommitPrefix { branch, unicode } => cmd_commit_prefix(branch, unicode),
    Command::Hooks { action } => cmd_hooks(action),
    Command::Completions { shell } => cmd_completions(shell),
    Command::ShellInit { shell } => cmd_shell_init(shell),
    Command::Switch => cmd_switch(),
    Command::Tmux { pattern, split } => cmd_multiplexer(Multiplexer::Tmux, pattern, split),
    Command::Zellij { pattern, split } => cmd_multiplexer(Multiplexer::Zellij, pattern, split),
    Command::Link {
      target,
      number,
      worktree,
    } => cmd_link(target, number, worktree),
    Command::Unlink { target, worktree } => cmd_unlink(target, worktree),
    Command::Open {
      target,
      worktree,
      print_url,
    } => cmd_open(target, worktree, print_url),
    Command::Status { worktree, json } => cmd_status(worktree, json),
    Command::Labels { action } => cmd_labels(action),
    Command::Milestones { action } => cmd_milestones(action),
    Command::Trust { action } => cmd_trust(action),
    Command::Aliases { action } => cmd_aliases(action),
    Command::Config { action } => cmd_config(action),
    Command::History { limit, all } => cmd_history(limit, all),
    Command::Undo { bootstrap } => cmd_undo(bootstrap, mode),
    Command::Tui { action } => cmd_tui(action),
    Command::Theme { action } => cmd_theme(action),
    Command::Exec {
      slugs,
      profile,
      jobs,
      command,
    } => match cli.workspace {
      Some(root) => cmd_exec_workspace(&root, slugs, profile, jobs, command),
      None => cmd_exec(slugs, profile, jobs, command),
    },
    Command::Clean { slugs, profile, yes } => match cli.workspace {
      Some(root) => cmd_clean_workspace(&root, slugs, profile, yes),
      None => cmd_clean(slugs, profile, yes),
    },
  }
}

/// Resolve which worktrees `gwm exec` / `gwm clean` act on. With no slugs,
/// the target set is every non-main worktree (the main checkout is excluded
/// — running a fan-out command or deleting its `target/` is rarely intended
/// and matches `gwm list --format names` / `find_fuzzy`). With slugs, each is
/// fuzzy-resolved, surfacing the same ambiguity error as `path` / `remove`.
fn resolve_targets(repo: &Repository, slugs: &[String]) -> Result<Vec<worktree::WorktreeInfo>> {
  if slugs.is_empty() {
    Ok(worktree::list(repo)?.into_iter().filter(|w| !w.is_main).collect())
  } else {
    slugs.iter().map(|s| worktree::find_fuzzy(repo, s)).collect()
  }
}

/// `gwm exec [<slug>...] -- <cmd>` (issue #313). Runs the command in each
/// target worktree sequentially, prints a ✓ / ✗ rollup, and exits with the
/// aggregate code (non-zero if any worktree failed).
fn cmd_exec(slugs: Vec<String>, profile: Option<String>, jobs: Option<u32>, command: Vec<String>) -> Result<()> {
  let repo = worktree::discover_repo(None)?;
  let (argv, job_count) = exec_plan(&repo, profile.as_deref(), jobs, &command)?;
  let targets = resolve_targets(&repo, &slugs)?;
  if targets.is_empty() {
    println!("no worktrees to run in");
    return Ok(());
  }
  let outcomes = exec_run(&targets, &argv, job_count, None)?;
  print_exec_rollup_and_exit(&outcomes)
}

/// `gwm exec --workspace <root> ...` — fan out exec across the workspace's
/// child repos (issue #326). Every repo's argv + parallelism + targets are
/// resolved UPFRONT, so a missing `--profile` (or a config error) in any repo
/// surfaces before a single command runs. Repos then run SEQUENTIALLY
/// (parallelism stays bounded WITHIN a repo to avoid cross-repo output
/// interleaving), under a `══ <repo>` header, with a `<repo>/<worktree>`
/// repo-tagged rollup and an aggregated exit code.
fn cmd_exec_workspace(
  root: &Path,
  slugs: Vec<String>,
  profile: Option<String>,
  jobs: Option<u32>,
  command: Vec<String>,
) -> Result<()> {
  let opened = open_workspace_repos(root)?;
  let repos: Vec<&Repository> = opened.iter().map(|(_, r)| r).collect();
  // Resolve targets (ambiguity/typo errors surface here) AND each repo's argv +
  // jobs UPFRONT — before a single command runs.
  let targets_per_repo = resolve_workspace_targets(&repos, &slugs)?;
  // Resolve config/argv ONLY for repos that have targets. A repo a scoped slug
  // doesn't touch contributes nothing, so its `[exec]` / `--profile` must not
  // be resolved — an unrelated repo lacking the profile or with a bad `[exec]`
  // can't break a run scoped elsewhere (#326 review).
  let mut plans: Vec<(&str, &Vec<worktree::WorktreeInfo>, Vec<String>, usize)> = Vec::new();
  for ((name, repo), targets) in opened.iter().zip(&targets_per_repo) {
    if targets.is_empty() {
      continue;
    }
    let (argv, job_count) = exec_plan(repo, profile.as_deref(), jobs, &command)?;
    plans.push((name, targets, argv, job_count));
  }

  if plans.is_empty() {
    // Nothing participates (every repo is main-only, or the slug scoped them all
    // out). No run follows, so it's safe to validate the command/profile against
    // the repos — a usage error (no command) or a typo'd `--profile` must still
    // surface instead of a silent exit 0. Accept if ANY repo resolves.
    let opened_repos = opened.iter().map(|(_, r)| r);
    if let Some(err) = first_exec_plan_error(opened_repos, profile.as_deref(), jobs, &command) {
      return Err(err);
    }
    println!("no worktrees to run in");
    return Ok(());
  }

  // Run sequentially per repo, aggregating the repo-tagged outcomes.
  let mut all = Vec::new();
  for (name, targets, argv, job_count) in &plans {
    println!("\n══ {}", name);
    all.extend(exec_run(targets, argv, *job_count, Some(name))?);
  }
  print_exec_rollup_and_exit(&all)
}

/// Validate the exec command/profile when NO workspace repo has targets:
/// returns `None` if [`exec_plan`] resolves against any repo (the source is
/// usable — there's just nothing to run), or the last error if it fails for
/// every repo (a usage error / unknown profile that must surface).
fn first_exec_plan_error<'a>(
  repos: impl Iterator<Item = &'a Repository>,
  profile: Option<&str>,
  jobs: Option<u32>,
  command: &[String],
) -> Option<GwmError> {
  let mut last = None;
  for repo in repos {
    match exec_plan(repo, profile, jobs, command) {
      Ok(_) => return None,
      Err(e) => last = Some(e),
    }
  }
  last
}

/// Discover the workspace under `root` and open every child repo (erroring on
/// an empty workspace or an unopenable child — before any command runs).
/// Returns `(repo_name, Repository)` pairs in `discover` order.
fn open_workspace_repos(root: &Path) -> Result<Vec<(String, Repository)>> {
  // `workspace::discover` silently skips a child whose `Repository::open`
  // fails (fine for `list` / `create`), but `exec` / `clean` are destructive
  // and contract for upfront resolution: a child that LOOKS like a repo (has a
  // `.git`) but won't open must fail the whole fan-out before any side effect,
  // not be quietly dropped while the valid repos run (#326 review).
  //
  // Use `try_exists` and propagate read_dir / stat errors (e.g. a `.git` that
  // can't be statted because of permissions) rather than masking them as
  // "absent" — an UNREADABLE child must surface too, not be skipped (review).
  for entry in std::fs::read_dir(root)? {
    let path = entry?.path();
    if path.is_dir() && path.join(".git").try_exists()? && Repository::open(&path).is_err() {
      let name = path
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_default();
      return Err(GwmError::Other(format!(
        "workspace: child repo `{name}` has a `.git` but cannot be opened (corrupt or unreadable)"
      )));
    }
  }

  let ws = workspace::discover(root)?;
  if ws.is_empty() {
    return Err(GwmError::EmptyWorkspace {
      root: root.display().to_string(),
    });
  }
  ws.repos
    .iter()
    .map(|r| {
      Repository::open(&r.path)
        .map(|repo| (r.name.clone(), repo))
        .map_err(|e| GwmError::Other(format!("workspace: cannot open repo `{}`: {e}", r.name)))
    })
    .collect()
}

/// Resolve the argv to run and the parallelism for `gwm exec` against `repo`
/// (config load + profile/inline resolution + jobs precedence). No side
/// effects — shared by the single-repo and workspace paths so every repo can
/// be resolved upfront. See the precedence/config-loading notes inline.
fn exec_plan(
  repo: &Repository,
  profile: Option<&str>,
  jobs: Option<u32>,
  command: &[String],
) -> Result<(Vec<String>, usize)> {
  // Read `[exec]` only as strictly as the invocation needs (issue #324):
  //   - `--profile` → full `load_exec_config` (resolve + validate every
  //     profile); needs a workdir to locate `.gwm.toml`.
  //   - inline + no `--jobs` → only the `[exec] jobs` default; a bare repo (no
  //     workdir) skips the repo file but still honours the GLOBAL default.
  //   - inline + `--jobs` → the flag wins and the command is inline → no config.
  let exec_cfg = if profile.is_some() {
    let workdir = repo.workdir().ok_or(GwmError::NotInGitRepo)?;
    Config::load_exec_config(workdir)?
  } else if jobs.is_none() {
    crate::config::ExecConfig {
      jobs: Config::load_exec_jobs_default(repo.workdir())?,
      ..Default::default()
    }
  } else {
    crate::config::ExecConfig::default()
  };
  let argv = exec::resolve_exec_command(profile, command, &exec_cfg)?;
  let job_count = exec::resolve_jobs(jobs, profile, &exec_cfg);
  Ok((argv, job_count))
}

/// Run `argv` across one repo's `targets`: sequential (live inherited stdio)
/// when `job_count <= 1`, else bounded-parallel with per-worktree captured
/// blocks. `tag` (the workspace repo name) prefixes each outcome's display
/// name with `<repo>/` for the aggregated rollup; the per-worktree header
/// stays plain (it sits under the `══ <repo>` header). Returns the outcomes.
fn exec_run(
  targets: &[worktree::WorktreeInfo],
  argv: &[String],
  job_count: usize,
  tag: Option<&str>,
) -> Result<Vec<exec::ExecOutcome>> {
  // `exec_plan` (via `resolve_exec_command`) guarantees a non-empty argv, but
  // split defensively rather than indexing — a panic would be user-facing.
  let (program, args) = argv
    .split_first()
    .ok_or_else(|| GwmError::Other("exec: no command resolved".into()))?;
  let args = args.to_vec();
  let display = |name: &str| match tag {
    Some(t) => format!("{t}/{name}"),
    None => name.to_string(),
  };

  let mut outcomes = Vec::with_capacity(targets.len());
  if job_count <= 1 {
    // Sequential: inherit the parent's stdio so output streams live, in order.
    for w in targets {
      println!("\n━━ {} ({})", w.name, w.path.display());
      let status = exec::exec_in_dir(&w.path, program, &args);
      outcomes.push(exec::ExecOutcome {
        name: display(&w.name),
        status,
      });
    }
  } else {
    // Parallel (bounded by `job_count`): capture each worktree's output so
    // concurrent runs don't interleave, then print one block per worktree in
    // worktree order once the fan-out completes. Write the captured bytes RAW
    // (not via `String::from_utf8_lossy`) so binary / non-UTF-8 output is
    // re-emitted byte-for-byte, matching the sequential path's inherited stdio.
    use std::io::Write;
    let items: Vec<(String, std::path::PathBuf)> = targets.iter().map(|w| (w.name.clone(), w.path.clone())).collect();
    let results = exec::run_in_dirs_parallel(job_count, &items, program, &args);
    let stdout = std::io::stdout();
    let mut lock = stdout.lock();
    for ((name, path), (outcome, output)) in items.iter().zip(results) {
      // Ignore write errors: a closed stdout (e.g. `| head`) shouldn't panic
      // the whole fan-out, and the rollup/exit code still report the result.
      let _ = writeln!(lock, "\n━━ {} ({})", name, path.display());
      let _ = lock.write_all(&output);
      outcomes.push(exec::ExecOutcome {
        name: display(name),
        status: outcome.status,
      });
    }
    let _ = lock.flush();
  }
  Ok(outcomes)
}

/// Print the `✓ / ✗` rollup for the collected outcomes and exit with the
/// aggregate code (non-zero if any worktree, in any repo, failed). Shared by
/// the single-repo and workspace exec paths.
fn print_exec_rollup_and_exit(outcomes: &[exec::ExecOutcome]) -> Result<()> {
  println!("\nrollup:");
  for o in outcomes {
    println!("  {}", exec::format_outcome(o));
  }
  let code = exec::rollup_exit_code(outcomes);
  if code != 0 {
    std::process::exit(code);
  }
  Ok(())
}

/// Resolve `slugs` against the workspace's opened `repos` for a fan-out,
/// returning the per-repo target lists in `repos` order.
///
/// Empty slugs ⇒ all non-main worktrees per repo. With slugs, a slug naming a
/// worktree in one child repo is naturally absent from the others, so a
/// per-repo `WorktreeNotFound` just contributes nothing THERE — but the error
/// distinctions the single-repo path makes are preserved: an **ambiguous**
/// match in any repo surfaces (propagated), and a slug that matches in **no**
/// repo at all is an error (a typo must not silently run/clean nothing).
fn resolve_workspace_targets(repos: &[&Repository], slugs: &[String]) -> Result<Vec<Vec<worktree::WorktreeInfo>>> {
  if slugs.is_empty() {
    // Propagate a per-repo listing failure (corrupt / unreadable worktree
    // metadata) rather than silently skipping that repo — the single-repo path
    // surfaces it too, and the upfront-resolution contract must not let a
    // destructive `clean --yes` proceed in the other repos while one is broken.
    return repos
      .iter()
      .map(|repo| Ok(worktree::list(repo)?.into_iter().filter(|w| !w.is_main).collect()))
      .collect();
  }

  let mut per_repo: Vec<Vec<worktree::WorktreeInfo>> = (0..repos.len()).map(|_| Vec::new()).collect();
  let mut matched = vec![false; slugs.len()];
  for (ri, repo) in repos.iter().enumerate() {
    for (si, slug) in slugs.iter().enumerate() {
      match worktree::find_fuzzy(repo, slug) {
        Ok(wt) => {
          per_repo[ri].push(wt);
          matched[si] = true;
        }
        // Absent from THIS repo is normal in a fan-out — skip it.
        Err(GwmError::WorktreeNotFound(_)) => {}
        // Ambiguity (or any other resolution failure) must surface.
        Err(e) => return Err(e),
      }
    }
  }
  if let Some(si) = matched.iter().position(|m| !m) {
    return Err(GwmError::WorktreeNotFound(format!(
      "{} (no worktree matches it in any workspace repo)",
      slugs[si]
    )));
  }
  Ok(per_repo)
}

/// `gwm clean [<slug>...] [--profile <name>] [--yes]` (issues #313, #324).
/// Reports reclaimable build artifacts per worktree; deletes them only when
/// `--yes` is passed. The directory set comes from `--profile`, else the
/// `default` profile, else the built-ins (see [`clean::resolve_clean_dirs`]).
fn cmd_clean(slugs: Vec<String>, profile: Option<String>, yes: bool) -> Result<()> {
  let repo = worktree::discover_repo(None)?;
  let targets = resolve_targets(&repo, &slugs)?;
  // Scan even when empty so an unknown `--profile` / malformed `[clean]` errors
  // before the "no worktrees" message (it loads/validates the dir set).
  let (reclaims, skipped) = clean_scan_repo(&repo, &targets, profile.as_deref(), None)?;
  if targets.is_empty() {
    println!("no worktrees to clean");
    return Ok(());
  }
  clean_finish(&reclaims, &skipped, yes)
}

/// `gwm clean --workspace <root> ...` — fan out the reclaim across the
/// workspace's child repos (issue #326). Every repo is opened, its targets
/// resolved (ambiguity/typo errors surface), and its worktrees scanned UPFRONT
/// (so a missing `--profile` or a malformed `[clean]` in any repo errors before
/// a single `remove_dir_all`), then one aggregated `<repo>/<worktree>`-tagged
/// report drives a single `--yes` decision; a delete failure in one worktree is
/// reported but does not abort the rest (it surfaces in the exit code).
fn cmd_clean_workspace(root: &Path, slugs: Vec<String>, profile: Option<String>, yes: bool) -> Result<()> {
  let opened = open_workspace_repos(root)?;
  let repos: Vec<&Repository> = opened.iter().map(|(_, r)| r).collect();
  let targets_per_repo = resolve_workspace_targets(&repos, &slugs)?;

  // Scan every repo with targets upfront — resolution (config/profile) errors
  // surface here, before any deletion. A repo a scoped slug doesn't touch
  // contributes nothing, so its `[clean]` / `--profile` is NOT resolved (an
  // unrelated repo's bad config can't break a run scoped elsewhere — #326
  // review).
  let mut reclaims: Vec<clean::WorktreeReclaim> = Vec::new();
  let mut skipped: Vec<(String, String)> = Vec::new();
  let mut participated = false;
  for ((name, repo), targets) in opened.iter().zip(&targets_per_repo) {
    if targets.is_empty() {
      continue;
    }
    participated = true;
    let (mut rec, mut skip) = clean_scan_repo(repo, targets, profile.as_deref(), Some(name))?;
    reclaims.append(&mut rec);
    skipped.append(&mut skip);
  }

  if !participated {
    // Nothing participates — no deletion follows, so validate the `--profile`
    // (a typo / malformed `[clean]`) against the repos instead of silently
    // reporting "nothing to reclaim". Accept if it resolves against any repo.
    let mut last_err = None;
    let mut valid = false;
    for (_, repo) in &opened {
      match clean_scan_repo(repo, &[], profile.as_deref(), None) {
        Ok(_) => {
          valid = true;
          break;
        }
        Err(e) => last_err = Some(e),
      }
    }
    if !valid {
      // `last_err` is `Some` whenever the loop over `opened` ran and no repo
      // validated — and `open_workspace_repos` already rejects an empty
      // workspace with `EmptyWorkspace`, so `opened` is non-empty and the
      // `None` arm is unreachable. Return that same error defensively rather
      // than `expect`-panicking, so a future regression that lets an empty
      // workspace through fails loud with a `GwmError` instead of a panic
      // (issue #344).
      return Err(last_err.unwrap_or_else(|| GwmError::EmptyWorkspace {
        root: root.display().to_string(),
      }));
    }
  }
  clean_finish(&reclaims, &skipped, yes)
}

/// One repo's clean scan: the per-worktree reclaims plus the skipped
/// `(display-name, rel-dir)` pairs (not git-ignored / holds tracked files).
type CleanScan = (Vec<clean::WorktreeReclaim>, Vec<(String, String)>);

/// Scan `targets` (a repo's worktrees, resolved by the caller) for reclaimable
/// artifacts, classifying each through the safety gate. The dir-set resolution
/// (config load + `--profile`) happens here, so an error surfaces before the
/// caller deletes anything. `tag` (the workspace repo name) prefixes worktree
/// display names with `<repo>/` for the aggregated report. Returns the
/// per-worktree reclaims and the skipped `(name, rel)`s.
fn clean_scan_repo(
  repo: &Repository,
  targets: &[worktree::WorktreeInfo],
  profile: Option<&str>,
  tag: Option<&str>,
) -> Result<CleanScan> {
  // Load ONLY `[clean]` (tolerant of unrelated config errors, strict on
  // `[clean]` itself — issue #324); `None` workdir (bare repo) reads the global
  // section and falls back to the built-in set.
  let clean_cfg = Config::load_clean_config(repo.workdir())?;
  let patterns = clean::resolve_clean_dirs(profile, &clean_cfg)?;

  let display = |name: &str| match tag {
    Some(t) => format!("{t}/{name}"),
    None => name.to_string(),
  };

  // Classify every found artifact through the SAME safety gate the deletion
  // uses, BEFORE reporting — so the dry-run preview's total and promise match
  // what `--yes` would actually remove. A name that is not git-ignored or holds
  // tracked files is unrecoverable (clean is not journaled), so it is reported
  // as skipped rather than counted. The gate lives in `clean::scan_worktree_safe`
  // so the TUI clean overlay (#325) reuses the identical contract.
  let mut reclaims = Vec::with_capacity(targets.len());
  let mut skipped = Vec::new();
  for w in targets {
    let (mut reclaim, skips) = clean::scan_worktree_safe(&w.name, &w.path, &patterns);
    reclaim.name = display(&w.name);
    for rel in skips {
      skipped.push((display(&w.name), rel));
    }
    reclaims.push(reclaim);
  }
  Ok((reclaims, skipped))
}

/// Render the aggregated reclaim report and, when `yes`, delete the artifacts.
/// Shared by the single-repo and workspace clean paths. A delete failure in
/// one worktree is reported and counted but does not abort the rest; if any
/// failed, the process exits non-zero.
fn clean_finish(reclaims: &[clean::WorktreeReclaim], skipped: &[(String, String)], yes: bool) -> Result<()> {
  print!("{}", clean::format_report(reclaims));
  for (name, rel) in skipped {
    println!("skipped {}/{}: not git-ignored, or holds tracked files", name, rel);
  }

  let grand: u64 = reclaims.iter().map(|r| r.total_bytes).sum();
  if grand == 0 {
    println!("nothing to reclaim");
    return Ok(());
  }
  if !yes {
    println!("re-run with --yes to delete the listed artifacts");
    return Ok(());
  }

  let mut freed = 0u64;
  let mut failures = 0usize;
  for r in reclaims {
    match clean::delete_reclaim(r) {
      Ok(b) => freed = freed.saturating_add(b),
      Err(e) => {
        eprintln!("failed to reclaim {}: {e}", r.name);
        failures += 1;
      }
    }
  }
  println!("reclaimed {}", clean::human_size(freed));
  if failures > 0 {
    std::process::exit(1);
  }
  Ok(())
}

/// Auto-detect prompt for bare `gwm` (issue #36): when the cwd is not inside a
/// git repo but holds direct-child repos, ask whether to open it as a
/// workspace. Returns the chosen root on a yes (`Enter` / `y`), else `None` so
/// the caller falls through to single-repo discovery (which then surfaces
/// `NotInGitRepo`). Declines silently when stdin is not a terminal (pipes / CI)
/// so non-interactive `gwm` behaves exactly as before — never blocking on a
/// prompt nobody can answer.
fn autodetect_workspace_prompt() -> Result<Option<PathBuf>> {
  use std::io::{IsTerminal, Write};

  let cwd = std::env::current_dir()?;
  let Some(ws) = workspace::autodetect(&cwd) else {
    return Ok(None);
  };
  if !io::stdin().is_terminal() {
    return Ok(None);
  }
  eprint!(
    "No git repo here. Open {} as a workspace ({} repos)? [Y/n] ",
    cwd.display(),
    ws.repos.len()
  );
  io::stderr().flush().ok();
  let mut answer = String::new();
  io::stdin().read_line(&mut answer)?;
  let a = answer.trim().to_ascii_lowercase();
  if a.is_empty() || a == "y" || a == "yes" {
    Ok(Some(ws.root))
  } else {
    Ok(None)
  }
}

fn cmd_tui(action: TuiAction) -> Result<()> {
  match action {
    TuiAction::Keys => cmd_tui_keys(),
  }
}

fn cmd_theme(action: ThemeAction) -> Result<()> {
  match action {
    ThemeAction::List => cmd_theme_list(),
    ThemeAction::Show { name } => cmd_theme_show(&name),
  }
}

/// Print every built-in TUI preset name (issue #33).
///
/// Pure read against `crate::tui::theme::preset_names` so the
/// command works outside any repository and never needs a config
/// load.
fn cmd_theme_list() -> Result<()> {
  for name in crate::tui::theme::preset_names() {
    println!("{}", name);
  }
  Ok(())
}

/// Print a preset as a copy-pasteable `[theme]` TOML block (issue #33).
///
/// Every emitted value is a **quoted TOML string** so the output
/// round-trips cleanly through the `[theme]` parser
/// (`ThemeConfig.overrides: BTreeMap<String, String>` only accepts
/// string values; a bare integer for `Color::Indexed` would fail to
/// deserialize at re-parse). `Color::Rgb` renders as `#RRGGBB`,
/// named colours as their canonical lowercase slug, and
/// `Color::Indexed(n)` as the quoted decimal `"n"` form the
/// `parse_color` indexed branch already accepts.
fn cmd_theme_show(name: &str) -> Result<()> {
  use crate::tui::theme::Theme;
  use ratatui::style::Color;

  let theme = Theme::preset(name).ok_or_else(|| {
    let known = crate::tui::theme::preset_names().join(", ");
    GwmError::Other(format!("theme show: unknown preset {:?} (known: {})", name, known))
  })?;
  let color_str = |c: Color| -> String {
    match c {
      Color::Rgb(r, g, b) => format!("\"#{:02x}{:02x}{:02x}\"", r, g, b),
      Color::Reset => "\"reset\"".to_string(),
      Color::Black => "\"black\"".to_string(),
      Color::Red => "\"red\"".to_string(),
      Color::Green => "\"green\"".to_string(),
      Color::Yellow => "\"yellow\"".to_string(),
      Color::Blue => "\"blue\"".to_string(),
      Color::Magenta => "\"magenta\"".to_string(),
      Color::Cyan => "\"cyan\"".to_string(),
      Color::Gray => "\"gray\"".to_string(),
      Color::DarkGray => "\"dark_gray\"".to_string(),
      Color::LightRed => "\"bright_red\"".to_string(),
      Color::LightGreen => "\"bright_green\"".to_string(),
      Color::LightYellow => "\"bright_yellow\"".to_string(),
      Color::LightBlue => "\"bright_blue\"".to_string(),
      Color::LightMagenta => "\"bright_magenta\"".to_string(),
      Color::LightCyan => "\"bright_cyan\"".to_string(),
      Color::White => "\"white\"".to_string(),
      // Quote the indexed value so it round-trips through the
      // string-only `[theme]` map. `parse_color` accepts bare digit
      // strings as `Color::Indexed` (e.g. `"220"` → Color::Indexed(220)).
      Color::Indexed(n) => format!("\"{}\"", n),
    }
  };
  println!("[theme]");
  println!("preset       = {:?}", name);
  println!("focus        = {}", color_str(theme.focus));
  println!("accent       = {}", color_str(theme.accent));
  println!("branch       = {}", color_str(theme.branch));
  println!("clean        = {}", color_str(theme.clean));
  println!("dirty        = {}", color_str(theme.dirty));
  println!("main         = {}", color_str(theme.main));
  println!("locked       = {}", color_str(theme.locked));
  println!("prunable     = {}", color_str(theme.prunable));
  println!("muted        = {}", color_str(theme.muted));
  println!("selection_bg = {}", color_str(theme.selection_bg));
  println!("name         = {}", color_str(theme.name));
  println!("path         = {}", color_str(theme.path));
  println!("staged       = {}", color_str(theme.staged));
  println!("modified     = {}", color_str(theme.modified));
  println!("untracked    = {}", color_str(theme.untracked));
  Ok(())
}

/// Print the resolved TUI keymap as a 3-column table.
///
/// Resolves `[tui.keys]` against the current repo's `.gwm.toml`
/// (falling back to bare defaults if there is no `.gwm.toml` and to
/// repo-less defaults when invoked outside any repo, so the command
/// is useful even before a project is set up). The output is the
/// human-readable side of the keymap surface — `gwm doctor` (issue
/// #87 part 8) consumes the same `Keymap::list()` API for its
/// validation pass, so the column contents stay in sync.
fn cmd_tui_keys() -> Result<()> {
  use crate::tui::keymap::{Keymap, Source};
  use crate::tui::modal_keymap::{KeyContext, ModalKeymap};

  // Build the resolved keymaps. Outside a repo, OR inside a bare
  // repo (no workdir to read `.gwm.toml` from), fall back to
  // defaults so the command stays useful for new users discovering
  // the binary. Same fallback path either way — surfacing
  // `NotInGitRepo` on a bare repo would be misleading because the
  // command itself is repo-agnostic.
  let (keymap, modal) = match worktree::discover_repo(None) {
    Ok(repo) => match repo.workdir() {
      Some(workdir) => {
        let cfg = Config::load_for_repo(workdir)?;
        (cfg.tui.keys.resolved_keymap()?, cfg.tui.keys.resolved_modal_keymap()?)
      }
      None => (Keymap::defaults(), ModalKeymap::defaults()),
    },
    Err(_) => (Keymap::defaults(), ModalKeymap::defaults()),
  };

  let rows = keymap.list();
  // Column widths sized to the longest content so the table stays
  // aligned even when a chord runs long (`Ctrl+Alt+Shift+F12`).
  let action_w = rows
    .iter()
    .map(|b| b.action.slug().len())
    .max()
    .unwrap_or(0)
    .max("action".len());
  let keys_w = rows
    .iter()
    .map(|b| {
      b.chords
        .iter()
        .map(|c| c.iter().map(|k| k.to_string()).collect::<Vec<_>>().join(" "))
        .collect::<Vec<_>>()
        .join(", ")
        .len()
    })
    .max()
    .unwrap_or(0)
    .max("keys".len());

  println!("{:<aw$}  {:<kw$}  source", "action", "keys", aw = action_w, kw = keys_w);
  for binding in rows {
    let keys = binding
      .chords
      .iter()
      .map(|c| c.iter().map(|k| k.to_string()).collect::<Vec<_>>().join(" "))
      .collect::<Vec<_>>()
      .join(", ");
    let source = match binding.source {
      Source::Default => "default",
      Source::UserConfig => ".gwm.toml",
    };
    println!(
      "{:<aw$}  {:<kw$}  {}",
      binding.action.slug(),
      keys,
      source,
      aw = action_w,
      kw = keys_w
    );
  }

  // Issue #219: contextual modal / overlay bindings, grouped by context.
  // Printed under their `[tui.keys.modal.<context>]` heading so the user can copy
  // a heading straight into `.gwm.toml` to start an override.
  let fmt_keys = |keys: &[crate::tui::keymap::KeyStroke]| -> String {
    keys.iter().map(|k| k.to_string()).collect::<Vec<_>>().join(", ")
  };
  for ctx in KeyContext::all() {
    let bindings = modal.bindings_for(*ctx);
    if bindings.is_empty() {
      continue;
    }
    println!("\n[tui.keys.modal.{}]", ctx.config_path());
    let verb_w = bindings
      .iter()
      .map(|b| b.action.verb().len())
      .max()
      .unwrap_or(0)
      .max("verb".len());
    let keys_w = bindings
      .iter()
      .map(|b| fmt_keys(&b.keys).len())
      .max()
      .unwrap_or(0)
      .max("keys".len());
    println!("{:<vw$}  {:<kw$}  source", "verb", "keys", vw = verb_w, kw = keys_w);
    for binding in bindings {
      let source = match binding.source {
        Source::Default => "default",
        Source::UserConfig => ".gwm.toml",
      };
      println!(
        "{:<vw$}  {:<kw$}  {}",
        binding.action.verb(),
        fmt_keys(&binding.keys),
        source,
        vw = verb_w,
        kw = keys_w
      );
    }
  }
  Ok(())
}

fn cmd_init(preset: Option<String>, list_presets: bool, show: bool) -> Result<()> {
  // `--list-presets` is a pure enumeration: it wins over everything and
  // returns before touching the filesystem or resolving a git repo.
  if list_presets {
    let name_w = presets::all().iter().map(|p| p.name.len()).max().unwrap_or(0);
    for p in presets::all() {
      let aliases = if p.aliases.is_empty() {
        String::new()
      } else {
        format!(" (alias: {})", p.aliases.join(", "))
      };
      println!("  {:<w$}  {}{}", p.name, p.description, aliases, w = name_w);
    }
    return Ok(());
  }

  // Resolve the preset (default `generic` = the documented example).
  let name = preset.as_deref().unwrap_or("generic");
  let resolved = presets::lookup(name).ok_or_else(|| {
    GwmError::Config(format!(
      "unknown preset {name:?} — run `gwm init --list-presets` to see the built-ins"
    ))
  })?;

  // `--show` prints the body and writes nothing, so it needs no git repo.
  if show {
    print!("{}", resolved.body);
    return Ok(());
  }

  let repo = worktree::discover_repo(None)?;
  let workdir = repo.workdir().ok_or(GwmError::NotInGitRepo)?;
  let path = Config::write_preset(workdir, resolved.body)?;
  println!("wrote {} (preset: {})", path.display(), resolved.name);
  Ok(())
}

/// `gwm agents` (issue #408 US4): list detected agent sessions per worktree,
/// or pin/unpin one manually. Pins live in git branch config
/// (`gwm-agent-pin`) and overlay auto-detection everywhere.
fn cmd_agents(action: Option<AgentsAction>, format: AgentsFormat) -> Result<()> {
  let repo = worktree::discover_repo(None)?;
  let trees = worktree::list(&repo)?;

  match action {
    None => {
      let mut rows: Vec<json_api::JsonWorktree> = trees.iter().map(json_api::JsonWorktree::from).collect();
      let pins = json_api::agent_pins_for_rows(&repo, &trees);
      let reals: Vec<PathBuf> = trees.iter().map(|w| w.path.clone()).collect();
      // JSON mirrors `gwm list --format=json` and has no `unmatched`
      // section, so it must not pay the full foreign-dir sweep the pool
      // costs (Codex review round U) — only the human table does.
      if format == AgentsFormat::Json {
        json_api::attach_agents(&mut rows, &reals, &pins);
        println!("{}", serde_json::to_string_pretty(&rows)?);
        return Ok(());
      }
      let pool = json_api::attach_agents_with_pool(&mut rows, &reals, &pins);
      // The pinned marker is scoped per (worktree, session): a session
      // detected on A but pinned on B is flagged only under B (Codex
      // review round A).
      let pinned_pairs: std::collections::BTreeSet<(&str, &str)> =
        pins.iter().map(|(path, sid)| (path.as_str(), sid.as_str())).collect();
      let now_epoch = std::time::SystemTime::now()
        .duration_since(std::time::SystemTime::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
      let mut any = false;
      for (row, tree) in rows.iter().zip(&trees) {
        let Some(agents) = &row.agents else {
          continue;
        };
        any = true;
        let row_key = crate::agent_sessions::path_display_key(&tree.path);
        println!("{}", row.name);
        for s in &agents.sessions {
          let pin_mark = if pinned_pairs.contains(&(row_key.as_str(), s.id.as_str())) {
            "  pinned"
          } else {
            ""
          };
          // Relative last activity (spec US4): the human table must let old
          // sessions be told apart at a glance.
          let ago = worktree::format_relative_duration(std::time::Duration::from_secs(
            now_epoch.saturating_sub(s.last_activity),
          ));
          let name_part = s.name.as_deref().map(|n| format!("  {n}")).unwrap_or_default();
          println!(
            "  {:<9} {:<7} {:>4} ago  {}{}{}",
            s.kind, s.freshness, ago, s.id, name_part, pin_mark
          );
        }
      }
      // Sessions no worktree matched (Codex review round C): the attach
      // error points here for ids, so the ones worth attaching — launched
      // in another repo, a subdirectory, an old path — must be visible.
      let shown: std::collections::BTreeSet<&str> = rows
        .iter()
        .filter_map(|r| r.agents.as_ref())
        .flat_map(|a| a.sessions.iter().map(|s| s.id.as_str()))
        .collect();
      let mut unmatched: Vec<&crate::agent_sessions::AgentSession> =
        pool.iter().filter(|s| !shown.contains(s.id.as_str())).collect();
      unmatched.sort_by_key(|s| (s.ended, std::cmp::Reverse(s.last_activity)));
      if !unmatched.is_empty() {
        any = true;
        let now_sys = std::time::SystemTime::now();
        println!("unmatched");
        for s in &unmatched {
          let word = match crate::agent_sessions::Freshness::classify(s.last_activity, s.ended, now_sys) {
            crate::agent_sessions::Freshness::Active => "active",
            crate::agent_sessions::Freshness::Idle => "idle",
          };
          let ago = worktree::format_relative_duration(now_sys.duration_since(s.last_activity).unwrap_or_default());
          let name_part = s.name.as_deref().map(|n| format!("  {n}")).unwrap_or_default();
          println!(
            "  {:<9} {:<7} {:>4} ago  {}{}",
            s.kind.display(),
            word,
            ago,
            s.id,
            name_part
          );
        }
      }
      if !any {
        println!("no agent session found");
      }
      Ok(())
    }
    Some(AgentsAction::Attach { pattern, session_id }) => {
      let target = resolve_agents_worktree(&trees, &pattern)?;
      let Some(branch) = github::pinnable_branch(target.branch.as_deref()).map(str::to_string) else {
        return Err(GwmError::Config(format!(
          "worktree '{}' has no branch (detached HEAD) — a pin lives in branch config",
          target.name
        )));
      };
      // Validate the id resolves from artefacts before persisting, so a
      // typo fails now instead of pinning dead weight.
      let home = crate::agent_sessions::agents_home()
        .ok_or_else(|| GwmError::Config("no home directory to scan for agent sessions".into()))?;
      let key = crate::agent_sessions::path_display_key(&target.path);
      let keyed: Vec<(String, PathBuf)> = trees
        .iter()
        .map(|w| (crate::agent_sessions::path_display_key(&w.path), w.path.clone()))
        .collect();
      let probe = [(key.clone(), session_id.clone())];
      let map = crate::agent_sessions::detect_all(&home, &keyed, &probe, std::time::SystemTime::now());
      let found = map
        .get(&key)
        .is_some_and(|a| a.sessions.iter().any(|s| s.id == session_id));
      if !found {
        return Err(GwmError::Config(format!(
          "no agent session with id '{session_id}' — run `gwm agents` to see the detected ids"
        )));
      }
      github::add_agent_pin(&repo, &branch, &session_id)?;
      println!("pinned {session_id} to {}", target.name);
      Ok(())
    }
    Some(AgentsAction::Detach { pattern, session_id }) => {
      let target = resolve_agents_worktree(&trees, &pattern)?;
      let Some(branch) = github::pinnable_branch(target.branch.as_deref()).map(str::to_string) else {
        return Err(GwmError::Config(format!(
          "worktree '{}' has no branch (detached HEAD) — nothing to detach",
          target.name
        )));
      };
      match session_id {
        Some(sid) => {
          if !github::remove_agent_pin(&repo, &branch, &sid)? {
            return Err(GwmError::Config(format!(
              "no pin '{sid}' on {} — run `gwm agents` to see the pinned ids",
              target.name
            )));
          }
          println!("detached {sid} from {}", target.name);
        }
        None => {
          github::clear_agent_pins(&repo, &branch)?;
          println!("detached every agent pin from {}", target.name);
        }
      }
      Ok(())
    }
  }
}

/// Resolve `pattern` against the full worktree set with
/// [`worktree::find_fuzzy`]'s tiering — exact name, then exact id, then
/// case-insensitive substring (Codex review round K) — but unlike it the
/// main checkout is included (a pin on it is legitimate) and `.` selects
/// the worktree enclosing the cwd.
fn resolve_agents_worktree(trees: &[worktree::WorktreeInfo], pattern: &str) -> Result<worktree::WorktreeInfo> {
  if pattern == "." {
    let cwd = std::env::current_dir()?;
    let cwd = cwd.canonicalize().unwrap_or(cwd);
    return trees
      .iter()
      .filter(|w| {
        let wp = w.path.canonicalize().unwrap_or_else(|_| w.path.clone());
        cwd.starts_with(&wp)
      })
      .max_by_key(|w| w.path.as_os_str().len())
      .cloned()
      .ok_or_else(|| GwmError::WorktreeNotFound(".".into()));
  }
  let exact: Vec<&worktree::WorktreeInfo> = trees.iter().filter(|w| w.name == pattern).collect();
  match exact.as_slice() {
    [one] => {
      // find_fuzzy: a token that is one worktree's display name and
      // another's stable id must not silently pick the name match.
      if let Some(by_id) = trees.iter().find(|w| w.id == pattern && w.id != one.id) {
        return Err(GwmError::Other(format!(
          "'{}' is ambiguous: the display name of '{}' and the id of '{}'; target one by its unique id",
          pattern, one.id, by_id.id
        )));
      }
      return Ok((*one).clone());
    }
    [] => {
      if let Some(by_id) = trees.iter().find(|w| w.id == pattern) {
        return Ok(by_id.clone());
      }
    }
    many => {
      let ids = many.iter().map(|w| w.id.as_str()).collect::<Vec<_>>().join(", ");
      return Err(GwmError::Other(format!(
        "name '{pattern}' is ambiguous ({} worktrees share it); target one by id: {ids}",
        many.len()
      )));
    }
  }
  let pat = pattern.to_lowercase();
  let matches: Vec<&worktree::WorktreeInfo> = trees.iter().filter(|w| w.name.to_lowercase().contains(&pat)).collect();
  match matches.as_slice() {
    [one] => Ok((*one).clone()),
    [] => Err(GwmError::WorktreeNotFound(pattern.into())),
    many => Err(GwmError::Config(format!(
      "pattern '{pattern}' is ambiguous: {}",
      many.iter().map(|w| w.name.as_str()).collect::<Vec<_>>().join(", ")
    ))),
  }
}

fn cmd_list(format: ListFormat, detect_pr: bool) -> Result<()> {
  let repo = worktree::discover_repo(None)?;
  let trees = worktree::list(&repo)?;

  if format == ListFormat::Names {
    // Mirror `worktree::find_fuzzy`, which excludes the main workdir:
    // emitting its name here would suggest a completion candidate that
    // `path` / `remove` / `bootstrap` can never accept.
    for w in trees.iter().filter(|w| !w.is_main) {
      println!("{}", w.name);
    }
    return Ok(());
  }

  // PR auto-detection (issue #181): off by default to keep the listing
  // network-free. When `--detect-pr` is set and a GitHub remote resolves,
  // detect each branch's PR via `gh pr list --head <branch>` — one `gh`
  // call per worktree. The detected number is rendered in an extra
  // column; an explicit `gwm link --pr` still wins via `read_link`.
  // Computed before the JSON branch so `--format=json --detect-pr` agrees
  // with the table (issue #38 review): the JSON `pr` field uses the same
  // detected number rather than only the persisted link.
  // `None` = detection did not run for that row (no GitHub slug / no
  // branch); `Some(inner)` = it ran and `inner` is the authoritative
  // result (`None` meaning "no PR", which clears a stale persisted one).
  // The distinction lets the JSON keep an explicit link when detection
  // can't run, yet clear a stale PR when it ran and found none (issue #38
  // review — resolves the round-4/round-5 tension on a plain `Option`).
  let detected_prs: Vec<Option<Option<u64>>> = if detect_pr {
    // `.gwm.toml` selects the forge (issue #419), so a malformed file is
    // surfaced rather than swallowed (Codex review #458): silently falling
    // back to host inference would drop a `forge = "gitlab"` a self-hosted
    // instance depends on, and detection could then persist a number read
    // from an entirely different repo.
    let config = Config::load_for_repo(repo.workdir().unwrap_or_else(|| repo.path()))?;
    match forge::resolve(&repo, &config).ok() {
      None => vec![None; trees.len()],
      Some(forge) => trees
        .iter()
        .map(|w| {
          w.branch.as_deref().map(|branch| {
            github::read_link_with_pr_detection(&repo, branch, forge.as_ref())
              .ok()
              .and_then(|l| l.pr)
          })
        })
        .collect(),
    }
  } else {
    Vec::new()
  };

  if format == ListFormat::Json {
    // Stable machine-readable array (issue #38). Includes the main
    // worktree — unlike `names`, a JSON consumer wants the full picture
    // (an editor statusbar resolves the active worktree from the set).
    let mut dto: Vec<json_api::JsonWorktree> = trees.iter().map(json_api::JsonWorktree::from).collect();
    // Agent sessions (issue #408): the shared `attach_agents` pass keeps
    // this surface byte-identical to the daemon's `list`.
    let pins = json_api::agent_pins_for_rows(&repo, &trees);
    let reals: Vec<PathBuf> = trees.iter().map(|w| w.path.clone()).collect();
    json_api::attach_agents(&mut dto, &reals, &pins);
    if detect_pr {
      // When detection RAN for a row its result is authoritative — apply
      // it even when `None` (clears a stale persisted PR). When it did NOT
      // run, keep the explicit/persisted link `JsonWorktree::from` set.
      for (d, outcome) in dto.iter_mut().zip(&detected_prs) {
        if let Some(pr) = outcome {
          d.pr = *pr;
        }
      }
    }
    println!("{}", serde_json::to_string_pretty(&dto)?);
    return Ok(());
  }

  // Dynamic widths based on observed content.
  let name_w = trees.iter().map(|w| w.name.len()).max().unwrap_or(4).clamp(4, 40);
  let branch_w = trees
    .iter()
    .map(|w| w.branch.as_deref().unwrap_or("-").len())
    .max()
    .unwrap_or(6)
    .clamp(6, 40);
  let status_w = 14;
  let pr_w = 6;
  // AGENT column (issue #408): the same compact indicator as the TUI table —
  // the most recently active agent per worktree, or `-`. Sized to the
  // longest agent name ("opencode").
  let agent_w = 8;
  let agent_cells: Vec<String> = {
    let mut cells = vec!["-".to_string(); trees.len()];
    if let Some(home) = crate::agent_sessions::agents_home() {
      let keyed: Vec<(String, PathBuf)> = trees
        .iter()
        .map(|w| (crate::agent_sessions::path_display_key(&w.path), w.path.clone()))
        .collect();
      let pins: Vec<(String, String)> = trees
        .iter()
        .flat_map(|w| {
          let pins = github::pinnable_branch(w.branch.as_deref())
            .map(|b| github::agent_pins(&repo, b).unwrap_or_default())
            .unwrap_or_default();
          let path = crate::agent_sessions::path_display_key(&w.path);
          pins.into_iter().map(move |sid| (path.clone(), sid))
        })
        .collect();
      let map = crate::agent_sessions::detect_all(&home, &keyed, &pins, std::time::SystemTime::now());
      for (i, w) in trees.iter().enumerate() {
        if let Some(top) = map
          .get(&crate::agent_sessions::path_display_key(&w.path))
          .and_then(|a| a.top())
        {
          cells[i] = top.kind.display().to_string();
        }
      }
    }
    cells
  };
  // Column shown only when a session was detected (Codex review round D):
  // a no-agent setup keeps the exact pre-#408 table layout. The pre-padded
  // fragment (cell + separator, or nothing) keeps one format string per row.
  let show_agent = agent_cells.iter().any(|c| c != "-");
  let agent_col = |cell: &str| {
    if show_agent {
      format!("{cell:<agent_w$}  ")
    } else {
      String::new()
    }
  };

  if detect_pr {
    println!(
      "  {:<nw$}  {:<bw$}  {:<sw$}  {:<pw$}  {}PATH",
      "NAME",
      "BRANCH",
      "STATUS",
      "PR",
      agent_col("AGENT"),
      nw = name_w,
      bw = branch_w,
      sw = status_w,
      pw = pr_w,
    );
  } else {
    println!(
      "  {:<nw$}  {:<bw$}  {:<sw$}  {}PATH",
      "NAME",
      "BRANCH",
      "STATUS",
      agent_col("AGENT"),
      nw = name_w,
      bw = branch_w,
      sw = status_w,
    );
  }
  for (i, w) in trees.iter().enumerate() {
    let mark = if w.is_main { "*" } else { " " };
    let branch = w.branch.clone().unwrap_or_else(|| "-".into());
    let status = format_status_text(w);
    if detect_pr {
      // Outer `Option` = detection ran?; inner = the PR number. Flatten
      // both for display (didn't-run and ran-without-PR both render `-`).
      let pr = detected_prs.get(i).copied().flatten().flatten();
      let pr_cell = pr.map(|n| format!("#{n}")).unwrap_or_else(|| "-".into());
      println!(
        "{} {:<nw$}  {:<bw$}  {:<sw$}  {:<pw$}  {}{}",
        mark,
        w.name,
        branch,
        status,
        pr_cell,
        agent_col(&agent_cells[i]),
        w.path.display(),
        nw = name_w,
        bw = branch_w,
        sw = status_w,
        pw = pr_w,
      );
    } else {
      println!(
        "{} {:<nw$}  {:<bw$}  {:<sw$}  {}{}",
        mark,
        w.name,
        branch,
        status,
        agent_col(&agent_cells[i]),
        w.path.display(),
        nw = name_w,
        bw = branch_w,
        sw = status_w,
      );
    }
  }
  Ok(())
}

/// `gwm list --workspace <root>`: the merged, repo-tagged table across every
/// git repo one level below `root` (issue #36). Mirrors [`cmd_list`]'s columns
/// but prepends a `REPO` column; `--detect-pr` is honoured per row against the
/// owning repo. `--format names` qualifies each worktree as `<repo>/<name>`
/// (including the main worktree, which in workspace mode is the primary `cd`
/// target) so a completion candidate is unambiguous across repos.
fn cmd_list_workspace(root: &Path, format: ListFormat, detect_pr: bool) -> Result<()> {
  let ws = workspace::discover(root)?;
  if ws.is_empty() {
    return Err(GwmError::EmptyWorkspace {
      root: root.display().to_string(),
    });
  }
  let rows = workspace::merge_worktrees(&ws)?;

  if format == ListFormat::Names {
    for row in &rows {
      println!("{}/{}", row.repo_name, row.info.name);
    }
    return Ok(());
  }

  // PR auto-detection (issue #181) resolved per row against its own repo.
  // `None` = detection did not run for that row (repo unopenable / no
  // branch / no slug); `Some(inner)` = it ran (`inner` is the result,
  // `None` clearing a stale PR). Same ran-vs-not distinction as the
  // single-repo path (issue #38 review). Computed before the JSON branch
  // so `--format=json --detect-pr` agrees with the table.
  let detected_prs: Vec<Option<Option<u64>>> = if detect_pr {
    rows
      .iter()
      .map(|row| {
        let repo = Repository::open(&row.repo_path).ok()?;
        let branch = row.info.branch.as_deref()?;
        // Each repo in a workspace picks its own forge: one may be on
        // GitHub and the next on a self-hosted GitLab, so the `forge` key
        // is read from that repo's own `.gwm.toml` (issue #419). A
        // malformed config makes the row's forge *unknown*, so detection
        // is skipped for it (`None` = "did not run") rather than guessed
        // from the host — a wrong guess would persist a number from
        // another repo (Codex review #458). One bad child config still
        // must not abort the whole workspace listing, hence skip-not-fail.
        let config = Config::load_for_repo(&row.repo_path).ok()?;
        let forge = forge::resolve(&repo, &config).ok()?;
        Some(
          github::read_link_with_pr_detection(&repo, branch, forge.as_ref())
            .ok()
            .and_then(|l| l.pr),
        )
      })
      .collect()
  } else {
    Vec::new()
  };

  // Pins live in each row's OWNING repo branch config — open it per row
  // (`agent_pins_for_rows` is single-repo; a workspace spans several). A
  // session pinned in a child repo must survive on every workspace surface
  // (Codex review round I).
  let agent_pins: Vec<(String, String)> = rows
    .iter()
    .filter_map(|row| {
      let repo = Repository::open(&row.repo_path).ok()?;
      let branch = github::pinnable_branch(row.info.branch.as_deref())?;
      let pins = github::agent_pins(&repo, branch).ok()?;
      let path = crate::agent_sessions::path_display_key(&row.info.path);
      Some(pins.into_iter().map(move |sid| (path.clone(), sid)).collect::<Vec<_>>())
    })
    .flatten()
    .collect();

  if format == ListFormat::Json {
    // Workspace JSON tags each worktree with its owning `repo` so a
    // cross-repo consumer can disambiguate (issue #36 + #38).
    #[derive(serde::Serialize)]
    struct WorkspaceJsonWorktree<'a> {
      repo: &'a str,
      #[serde(flatten)]
      worktree: json_api::JsonWorktree,
    }
    let mut worktree_rows: Vec<json_api::JsonWorktree> = rows
      .iter()
      .enumerate()
      .map(|(i, row)| {
        let mut worktree = json_api::JsonWorktree::from(&row.info);
        // When detection ran for this row its result is authoritative
        // (applied even when `None`, clearing a stale PR); when it did not
        // run, keep the link `JsonWorktree::from` set (issue #38 review).
        if let Some(pr) = detected_prs.get(i).copied().flatten() {
          worktree.pr = pr;
        }
        worktree
      })
      .collect();
    // Issue #408: same shared agents pass as single-repo list / daemon,
    // with each row's own repo pins overlaid (round I).
    let reals: Vec<PathBuf> = rows.iter().map(|r| r.info.path.clone()).collect();
    json_api::attach_agents(&mut worktree_rows, &reals, &agent_pins);
    let dto: Vec<WorkspaceJsonWorktree> = rows
      .iter()
      .zip(worktree_rows)
      .map(|(row, worktree)| WorkspaceJsonWorktree {
        repo: &row.repo_name,
        worktree,
      })
      .collect();
    println!("{}", serde_json::to_string_pretty(&dto)?);
    return Ok(());
  }

  let repo_w = rows.iter().map(|r| r.repo_name.len()).max().unwrap_or(4).clamp(4, 30);
  // AGENT parity with the single-repo table (Codex review round A): one
  // detection pass over the merged rows, each row's own repo pins overlaid
  // (round I).
  let agent_w = 8;
  let agent_cells: Vec<String> = {
    let mut cells = vec!["-".to_string(); rows.len()];
    if let Some(home) = crate::agent_sessions::agents_home() {
      let keyed: Vec<(String, PathBuf)> = rows
        .iter()
        .map(|r| {
          (
            crate::agent_sessions::path_display_key(&r.info.path),
            r.info.path.clone(),
          )
        })
        .collect();
      let map = crate::agent_sessions::detect_all(&home, &keyed, &agent_pins, std::time::SystemTime::now());
      for (i, r) in rows.iter().enumerate() {
        if let Some(top) = map
          .get(&crate::agent_sessions::path_display_key(&r.info.path))
          .and_then(|a| a.top())
        {
          cells[i] = top.kind.display().to_string();
        }
      }
    }
    cells
  };
  // Same conditional column as the single-repo table (round D).
  let show_agent = agent_cells.iter().any(|c| c != "-");
  let agent_col = |cell: &str| {
    if show_agent {
      format!("{cell:<agent_w$}  ")
    } else {
      String::new()
    }
  };
  let name_w = rows.iter().map(|r| r.info.name.len()).max().unwrap_or(4).clamp(4, 40);
  let branch_w = rows
    .iter()
    .map(|r| r.info.branch.as_deref().unwrap_or("-").len())
    .max()
    .unwrap_or(6)
    .clamp(6, 40);
  let status_w = 14;
  let pr_w = 6;

  if detect_pr {
    println!(
      "  {:<rw$}  {:<nw$}  {:<bw$}  {:<sw$}  {:<pw$}  {}PATH",
      "REPO",
      "NAME",
      "BRANCH",
      "STATUS",
      "PR",
      agent_col("AGENT"),
      rw = repo_w,
      nw = name_w,
      bw = branch_w,
      sw = status_w,
      pw = pr_w,
    );
  } else {
    println!(
      "  {:<rw$}  {:<nw$}  {:<bw$}  {:<sw$}  {}PATH",
      "REPO",
      "NAME",
      "BRANCH",
      "STATUS",
      agent_col("AGENT"),
      rw = repo_w,
      nw = name_w,
      bw = branch_w,
      sw = status_w,
    );
  }
  for (i, row) in rows.iter().enumerate() {
    let w = &row.info;
    let mark = if w.is_main { "*" } else { " " };
    let branch = w.branch.clone().unwrap_or_else(|| "-".into());
    let status = format_status_text(w);
    if detect_pr {
      // Flatten both the ran?-Option and the PR-Option for display.
      let pr = detected_prs.get(i).copied().flatten().flatten();
      let pr_cell = pr.map(|n| format!("#{n}")).unwrap_or_else(|| "-".into());
      println!(
        "{} {:<rw$}  {:<nw$}  {:<bw$}  {:<sw$}  {:<pw$}  {}{}",
        mark,
        row.repo_name,
        w.name,
        branch,
        status,
        pr_cell,
        agent_col(&agent_cells[i]),
        w.path.display(),
        rw = repo_w,
        nw = name_w,
        bw = branch_w,
        sw = status_w,
        pw = pr_w,
      );
    } else {
      println!(
        "{} {:<rw$}  {:<nw$}  {:<bw$}  {:<sw$}  {}{}",
        mark,
        row.repo_name,
        w.name,
        branch,
        status,
        agent_col(&agent_cells[i]),
        w.path.display(),
        rw = repo_w,
        nw = name_w,
        bw = branch_w,
        sw = status_w,
      );
    }
  }
  Ok(())
}

fn format_status_text(w: &worktree::WorktreeInfo) -> String {
  if w.is_prunable {
    return "prunable".into();
  }
  if w.is_locked {
    return "locked".into();
  }
  let s = &w.status;
  if s.unknown {
    return "unknown".into();
  }
  let mut parts: Vec<String> = Vec::new();
  if s.is_dirty {
    parts.push("● dirty".into());
  }
  if s.has_upstream {
    if s.ahead > 0 {
      parts.push(format!("{}", s.ahead));
    }
    if s.behind > 0 {
      parts.push(format!("{}", s.behind));
    }
    if !s.is_dirty && s.synced() {
      parts.push("✓ synced".into());
    }
  } else if !s.is_dirty {
    parts.push("clean".into());
  }
  parts.join(" ")
}

/// The repo prelude shared by most CLI subcommands: an open
/// [`Repository`], its working directory, and the resolved
/// [`Config`]. Owned values so call sites keep borrowing `&repo`,
/// `&workdir`, `&config` exactly as they did when the triplet was
/// inlined.
pub struct RepoContext {
  pub repo: Repository,
  pub workdir: PathBuf,
  pub config: Config,
}

/// Discover the repo, resolve its workdir, and load `.gwm.toml`.
///
/// `start` mirrors [`worktree::discover_repo`]: `None` discovers from
/// the current directory (the behaviour every CLI call site relies
/// on), `Some(path)` discovers from an explicit root (used by tests).
///
/// Surfaces [`GwmError::NotInGitRepo`] outside a repo or in a bare
/// repo (no workdir), and propagates any `.gwm.toml` parse error from
/// [`Config::load_for_repo`].
pub fn repo_context(start: Option<&Path>) -> Result<RepoContext> {
  let repo = worktree::discover_repo(start)?;
  let workdir = repo.workdir().ok_or(GwmError::NotInGitRepo)?.to_path_buf();
  let config = Config::load_for_repo(&workdir)?;
  Ok(RepoContext { repo, workdir, config })
}

/// Like [`repo_context`], but tolerates a missing or malformed
/// `.gwm.toml` by falling back to [`Config::default`]. The repo and
/// workdir gates stay strict — only the config *load* is lenient.
/// Used by `gwm doctor`, which must run even when the config it is
/// about to diagnose is broken.
pub fn repo_context_lenient(start: Option<&Path>) -> Result<RepoContext> {
  let repo = worktree::discover_repo(start)?;
  let workdir = repo.workdir().ok_or(GwmError::NotInGitRepo)?.to_path_buf();
  let config = Config::load_for_repo(&workdir).unwrap_or_default();
  Ok(RepoContext { repo, workdir, config })
}

/// Resolve which child repo a workspace-mode `gwm create` targets (issue #36).
/// `--repo` is required there to disambiguate; an absent flag lists the
/// candidates, an unknown name lists them too. Returns the chosen repo's path
/// so [`cmd_create`] can discover from it instead of the current directory.
fn resolve_workspace_create_repo(root: &Path, repo: Option<String>) -> Result<PathBuf> {
  let ws = workspace::discover(root)?;
  if ws.is_empty() {
    return Err(GwmError::EmptyWorkspace {
      root: root.display().to_string(),
    });
  }
  let available = ws.repos.iter().map(|r| r.name.as_str()).collect::<Vec<_>>().join(", ");
  let name = repo.ok_or_else(|| GwmError::WorkspaceRepoRequired {
    available: available.clone(),
  })?;
  ws.repos
    .iter()
    .find(|r| r.name == name)
    .map(|r| r.path.clone())
    .ok_or(GwmError::WorkspaceRepoNotFound { name, available })
}

// `cmd_create` mirrors the `Create` subcommand's independent CLI args 1:1
// (three positionals + three flags + the resolved trust mode), and #36 adds
// the workspace `start` path. Bundling them into a struct would only add an
// indirection that obscures the direct subcommand → handler mapping the rest
// of this dispatcher follows, so the arg count is deliberate here.
#[allow(clippy::too_many_arguments)]
fn cmd_create(
  branch_type: Option<String>,
  issue: Option<String>,
  desc: Option<String>,
  name: Option<String>,
  no_bootstrap: bool,
  reuse_branch: bool,
  skip_hooks: Option<String>,
  trust_mode: TrustMode,
  start: Option<&Path>,
) -> Result<()> {
  let RepoContext { repo, workdir, config } = repo_context(start)?;
  let repo_name = worktree::repo_name(&repo);

  // clap guarantees exactly one of the two shapes reaches here:
  // `--name` conflicts with all three positionals, and each positional is
  // `required_unless_present = "name"`, so a partial triple is rejected
  // before dispatch rather than silently read as a free-form request.
  let wt_name = match name {
    Some(name) => WorktreeName::freeform(&name)?,
    None => {
      let resolved_types = config.resolved_branch_types();
      let (branch_type, issue, desc) = match (branch_type, issue, desc) {
        (Some(t), Some(i), Some(d)) => (t, i, d),
        _ => {
          return Err(GwmError::Other(
            "`gwm create` needs <TYPE> <ISSUE> <DESC> or --name".into(),
          ))
        }
      };
      WorktreeName::Structured(BranchSpec::new_with_types(
        branch_type,
        issue,
        desc,
        &resolved_types.types,
      )?)
    }
  };

  let branch = wt_name.branch_name(&config.worktree, &repo_name)?;
  let dirname = wt_name.worktree_dirname(&config.worktree, &repo_name)?;
  let target = wt_name.worktree_path(&config.worktree, &repo_name, &workdir)?;
  let skips = HookSkips::parse(skip_hooks.as_deref())?;

  // Gate the bootstrap RCE primitive on the TOFU ledger BEFORE
  // creating the worktree — a deny / abort here leaves the user's
  // disk state untouched (no orphaned worktree to clean up).
  let create_hooks_present = !config.hooks.pre_create.is_empty()
    || !config.hooks.post_create.is_empty()
    || (!no_bootstrap && !config.bootstrap.command.is_empty());
  if !no_bootstrap || create_hooks_present {
    trust_or_prompt(&workdir, Some(&repo), trust_mode)?;
  }

  // `for_worktree` derives the context by re-parsing the branch, exactly as
  // a later `gwm remove` on the same worktree would, so the two phases
  // agree. Note what that means: the placeholders resolve empty only when
  // the name does not match the branch convention. `--name 'feat/#42-x'`
  // parses, so its context populates — and that is right, because nothing
  // downstream knows how a worktree was named, only what its branch is
  // (Codex review on PR #474).
  let pre_ctx = match &wt_name {
    WorktreeName::Structured(spec) => HookContext::for_create(&repo, &workdir, &workdir, &target, &branch, spec),
    WorktreeName::Freeform(_) => HookContext::for_worktree(&repo, &workdir, &workdir, &target, Some(&branch)),
  };
  let report = lifecycle::run_phase(&config, HookPhase::PreCreate, &pre_ctx, &skips, false)?;
  print_lifecycle_report(&report);

  println!("creating worktree:");
  println!("  branch : {}", branch);
  println!("  dir    : {}", dirname);
  println!("  path   : {}", target.display());

  let created = worktree::add(&repo, &dirname, &target, &branch, reuse_branch)?;
  println!("✓ worktree created at {}", created.display());

  let post_ctx = pre_ctx.with_cwd(&created);

  if no_bootstrap {
    println!("(skipped bootstrap)");
  } else {
    let report = lifecycle::run_phase(&config, HookPhase::PreBootstrap, &post_ctx, &skips, false)?;
    print_lifecycle_report(&report);

    let ctx = BootstrapCtx {
      main_repo: &workdir,
      worktree: &created,
      config: &config,
    };
    let report = bootstrap::run_core(&ctx)?;
    print_report(&report);

    let report = lifecycle::run_phase(&config, HookPhase::PostBootstrap, &post_ctx, &skips, false)?;
    print_lifecycle_report(&report);
  }

  if config.hooks.has_any() && !config.bootstrap.command.is_empty() {
    eprintln!("warning: [[bootstrap.command]] is deprecated as a post_create hook when [hooks.*] is present");
  }
  let report = lifecycle::run_phase(&config, HookPhase::PostCreate, &post_ctx, &skips, !no_bootstrap)?;
  print_lifecycle_report(&report);
  Ok(())
}

/// `gwm review <PR#>` (issue #308) — the inbound counterpart to
/// `cmd_create`. Resolves the PR head via `gh`, materialises a worktree on
/// origin's `refs/pull/<N>/head` ref (see [`crate::review`]), and links the
/// PR. Setup (bootstrap + lifecycle hooks) is **opt-in** via `--bootstrap`:
/// the worktree holds a contributor's possibly-untrusted code and those
/// steps run commands against it, so review is safe-by-default (see
/// [`review::run_post_setup`] for the threat model).
fn cmd_review(
  number: u64,
  name: Option<String>,
  bootstrap: bool,
  skip_hooks: Option<String>,
  trust_mode: TrustMode,
) -> Result<()> {
  let RepoContext { repo, workdir, config } = repo_context(None)?;
  let repo_name = worktree::repo_name(&repo);
  let forge = forge::resolve(&repo, &config)?;

  println!("resolving {} #{number} on {}", forge.pr_noun(), forge.slug());
  let head = forge.fetch_pr_head(number)?;
  let slug = review::head_slug(&head.head_ref_name);

  let branch = name
    .clone()
    .unwrap_or_else(|| review::review_branch_name(number, &head.author, &slug));
  let dirname = match &name {
    Some(n) => review::dirname_from_branch(n),
    None => review::review_dirname(number, &head.author, &slug),
  };
  // Land the review worktree under the same `base` as every other
  // worktree so `gwm list` / the TUI pick it up. The synthetic
  // type/issue/desc feed any `{type}`/`{issue}`/`{desc}` placeholders a
  // custom base might carry.
  let base = crate::config::expand_placeholders(
    &config.worktree.base,
    &repo_name,
    Some("review"),
    Some(&number.to_string()),
    Some(&slug),
    Some(&workdir),
  )?;
  let target = PathBuf::from(base).join(&dirname);
  let skips = HookSkips::parse(skip_hooks.as_deref())?;

  // A `review/…` branch carries no BranchSpec of its own; synthesize one
  // (bypassing the type validation that would reject `review`) purely to
  // drive the hook placeholders, so the hooks see the same
  // `{type}`/`{issue}`/`{desc}` surface they do under `gwm create`.
  let spec = BranchSpec {
    type_: "review".to_string(),
    issue: number.to_string(),
    desc: slug.clone(),
  };
  let pre_ctx = HookContext::for_create(&repo, &workdir, &workdir, &target, &branch, &spec);

  // Setup runs arbitrary commands against the PR's code, so it is opt-in.
  // Only when `--bootstrap` is passed do we gate the RCE primitives on the
  // TOFU ledger and run `pre_create` before materialising.
  if bootstrap {
    trust_or_prompt(&workdir, Some(&repo), trust_mode)?;
    let report = lifecycle::run_phase(&config, HookPhase::PreCreate, &pre_ctx, &skips, false)?;
    print_lifecycle_report(&report);
  }

  println!("creating review worktree:");
  println!(
    "  PR     : #{number} by {} ({}{})",
    head.author, head.head_ref_name, head.base_ref_name
  );
  println!("  branch : {branch}");
  println!("  dir    : {dirname}");
  println!("  path   : {}", target.display());

  // Record `origin/<base>` (a remote-tracking ref) as the diff base, not the
  // bare local `<base>` — a review-only checkout may have a stale or absent
  // local base branch, and the `R` launcher passes the recorded value
  // straight to `git diff`/`git rev-list`, where a missing ref reads as zero
  // commits ("no changes" against a stale base). Fetch with an *explicit*,
  // *forced* `+refs/heads/<base>:refs/remotes/origin/<base>` refspec: explicit
  // so the tracking ref is actually written (a bare `git fetch origin <base>`
  // only updates `FETCH_HEAD` unless the remote's configured refspec covers
  // it), and `+`-forced so a rebased/force-pushed base still updates instead
  // of failing the non-fast-forward — matching git's own default
  // `+refs/heads/*:refs/remotes/origin/*` mirror for tracking refs. Best-
  // effort, since the head fetch in `materialize` is the load-bearing one.
  let base_ref = (!head.base_ref_name.is_empty()).then(|| {
    let refspec = format!("+refs/heads/{0}:refs/remotes/origin/{0}", head.base_ref_name);
    let _ = worktree::run_git_logged(&workdir, &["fetch", "origin", &refspec]);
    format!("origin/{}", head.base_ref_name)
  });
  let head_ref = forge.pr_head_refspec(number);
  let rspec = review::ReviewSpec {
    number,
    head_ref: &head_ref,
    branch: &branch,
    dirname: &dirname,
    target: &target,
    base_ref: base_ref.as_deref(),
  };
  let created = review::materialize(&repo, &workdir, &rspec)?;
  println!("✓ review worktree created at {}", created.display());
  println!("✓ linked to {} #{number}", forge.pr_noun());

  let post_ctx = pre_ctx.with_cwd(&created);
  match review::run_post_setup(&config, &post_ctx, &workdir, &created, &skips, bootstrap)? {
    Some(reports) => {
      print_lifecycle_report(&reports.pre_bootstrap);
      print_report(&reports.bootstrap);
      print_lifecycle_report(&reports.post_bootstrap);
      if config.hooks.has_any() && !config.bootstrap.command.is_empty() {
        eprintln!("warning: [[bootstrap.command]] is deprecated as a post_create hook when [hooks.*] is present");
      }
      print_lifecycle_report(&reports.post_create);
    }
    None => {
      println!("(skipped bootstrap + hooks — pass --bootstrap to run setup against the PR's code)");
    }
  }
  Ok(())
}

fn cmd_new(
  branch_type: String,
  desc: String,
  no_bootstrap: bool,
  reuse_branch: bool,
  skip_hooks: Option<String>,
  trust_mode: TrustMode,
) -> Result<()> {
  let RepoContext { repo, config, .. } = repo_context(None)?;
  let repo_name = worktree::repo_name(&repo);
  let resolved_types = config.resolved_branch_types();
  let spec = BranchSpec::new_with_types(branch_type.clone(), "0", desc, &resolved_types.types)?;
  let draft = issue_templates::render_issue_draft(&repo, &config, &spec.type_, &spec.desc)?;
  let forge = forge::resolve_or_default(&repo, &config)?;
  let created = forge.create_issue(&forge::IssueCreateRequest {
    title: &draft.title,
    body_file: draft.body_file.path(),
    labels: &draft.labels,
  })?;

  let label_summary = if draft.labels.is_empty() {
    String::new()
  } else {
    format!(" (labels: {})", draft.labels.join(", "))
  };
  println!("✓ created issue #{} {}{}", created.number, draft.title, label_summary);
  let issue = created.number.to_string();
  let branch = BranchSpec::new_with_types(
    spec.type_.clone(),
    issue.clone(),
    spec.desc.clone(),
    &resolved_types.types,
  )?
  .branch_name(&config.worktree, &repo_name)?;
  println!("  {}", created.url);
  println!("creating linked worktree for {}", branch);

  cmd_create(
    Some(spec.type_),
    Some(issue),
    Some(spec.desc),
    // `gwm new` always produces a structured worktree — it has just created
    // the issue whose number the branch carries.
    None,
    no_bootstrap,
    reuse_branch,
    skip_hooks,
    trust_mode,
    None,
  )
}

/// Maximum number of lines kept from `git diff --stat <base>..<head>`
/// when rendering the `{files_changed}` placeholder. Hardcoded by issue
/// #84 so a sprawling refactor PR doesn't push the body past GitHub's
/// 65 535-byte limit; the renderer appends a `… (N more lines trimmed)`
/// rider when the cap fires.
const PR_FILES_CHANGED_MAX_LINES: usize = 30;

fn cmd_pr(render_only: bool, draft: bool, base_override: Option<String>) -> Result<()> {
  let RepoContext { repo, workdir, config } = repo_context(None)?;
  // Issue #477: from the invoking checkout, not from `repo` — that handle
  // has walked back to the main working directory. Everything else below
  // keeps using `repo`, which is what it wants.
  let head_name = current_branch_at(None)?;
  // Issue #417: `[pr_template.by_type]` selection and the body placeholders
  // read the branch back, so they read it with this repo's own pattern.
  let branch_spec = crate::naming::BranchParser::from_config(&config, &worktree::repo_name(&repo)).parse(&head_name);

  // `.filter` and not just `.map`: since #417 a pattern with no `{type}` still
  // parses, reporting the segments it *does* carry, so the type comes back
  // empty rather than as a failed parse. An empty type selects no
  // `[pr_template.by_type]` entry and renders `{type}` blank, which is exactly
  // what this fallback exists to prevent.
  let branch_type = branch_spec
    .as_ref()
    .map(|s| s.type_.clone())
    .filter(|t| !t.is_empty())
    .unwrap_or_else(|| "chore".into());
  let issue = branch_spec.as_ref().map(|s| s.issue.clone()).unwrap_or_default();
  let desc = branch_spec.as_ref().map(|s| s.desc.clone()).unwrap_or_default();

  let base = base_override
    .or_else(|| worktree::resolve_trunk(&repo, &config.doctor.trunks))
    .unwrap_or_else(|| "main".into());

  let commits = worktree::git_log_subject_between(&workdir, &base, &head_name)
    .inspect_err(|e| {
      eprintln!(
        "note: could not collect `{{commits}}` from `git log {}..{}`: {} (placeholder will be empty)",
        base, head_name, e
      );
    })
    .unwrap_or_default();
  let files_changed = worktree::git_diff_stat_between(&workdir, &base, &head_name, PR_FILES_CHANGED_MAX_LINES)
    .inspect_err(|e| {
      eprintln!(
        "note: could not collect `{{files_changed}}` from `git diff --stat {}..{}`: {} (placeholder will be empty)",
        base, head_name, e
      );
    })
    .unwrap_or_default();
  // Best-effort: `--render-only` must keep working in a repo with no
  // `origin`, where the `{{repo}}` placeholder simply renders empty.
  // The forge is resolved *strictly* further down, only on the path that
  // actually talks to the network.
  let repo_slug = forge::repo_slug(&repo).unwrap_or_default();

  let ctx = PrTemplateContext {
    branch_type: branch_type.clone(),
    issue,
    desc,
    base: base.clone(),
    head: head_name.clone(),
    commits,
    files_changed,
    repo: repo_slug.clone(),
  };
  let body = pr_templates::render_pr_body(&config.pr_template, &workdir, &ctx)?;

  if render_only {
    print!("{}", body);
    if !body.ends_with('\n') {
      println!();
    }
    return Ok(());
  }

  let mut body_file = tempfile::NamedTempFile::new()?;
  use std::io::Write;
  body_file.write_all(body.as_bytes())?;
  body_file.flush()?;

  let title = pr_title(&ctx);
  let forge = forge::resolve_or_default(&repo, &config)?;
  let created = forge.create_pr(&forge::PrCreateRequest {
    title: &title,
    body_file: body_file.path(),
    head: &head_name,
    base: Some(base.as_str()),
    draft,
  })?;
  println!("✓ created {} #{}", forge.pr_noun(), created.number);
  println!("  {}", created.url);
  if let Err(e) = github::link_pr(&repo, &head_name, created.number) {
    // Linking is a best-effort convenience: surface the failure but
    // don't drop the freshly-created PR on the floor.
    eprintln!("note: could not record gwm-pr config for {}: {}", head_name, e);
  }
  Ok(())
}

fn pr_title(ctx: &PrTemplateContext) -> String {
  // Title heuristic mirrors `me:issue-worktree-pr`: take the latest
  // commit subject if there is one, else fall back to "<type>: <desc>"
  // so the user gets a deterministic, non-empty title.
  if let Some(first) = ctx.commits.lines().next() {
    let trimmed = first.trim_start_matches("- ").trim();
    if !trimmed.is_empty() {
      return trimmed.to_string();
    }
  }
  if !ctx.desc.is_empty() {
    return format!("{}: {}", ctx.branch_type, ctx.desc);
  }
  format!("update {}", ctx.head)
}

/// Render the would-do plan for `gwm remove --dry-run` (issue #31).
/// Extracted from `cmd_remove` so the formatter is unit-testable
/// without spinning up a real worktree. Pure function: takes the
/// resolved name + path + branch, returns a multi-line string
/// (trailing newline included).
///
/// `delete_branch` only adds "(would be deleted)" when there *is* a
/// branch to delete — a detached HEAD worktree with
/// `--delete-branch` reports "(no branch to delete)" instead, mirror-
/// ing `worktree::remove`'s actual behaviour (it only drops a branch
/// when one is resolvable).
pub fn format_remove_plan(name: &str, path: &Path, branch: Option<&str>, delete_branch: bool) -> String {
  use std::fmt::Write;
  let mut out = String::new();
  let _ = writeln!(out, "would remove:");
  let _ = writeln!(out, "  name:   {}", name);
  let _ = writeln!(out, "  path:   {}", path.display());
  match (branch, delete_branch) {
    (Some(b), true) => {
      let _ = writeln!(out, "  branch: {} (would be deleted)", b);
    }
    (Some(b), false) => {
      let _ = writeln!(out, "  branch: {}", b);
    }
    (None, true) => {
      // Detached HEAD worktree: `worktree::remove` only drops a
      // branch when one is resolvable, so the dry-run must not
      // claim a deletion that will never happen. The clarifying
      // rider tells the user why `--delete-branch` is a no-op
      // here without forcing them to re-read the docs.
      let _ = writeln!(out, "  branch: - (no branch to delete)");
    }
    (None, false) => {
      let _ = writeln!(out, "  branch: -");
    }
  }
  out
}

/// Render the would-do plan for `gwm prune --dry-run` (issue #31).
/// Extracted from `cmd_prune` so the formatter is unit-testable on
/// arbitrary `PrunableEntry` fixtures (non-ASCII names / paths
/// without needing a real repo). Pure function: trailing newline
/// included; empty input still emits the canonical
/// "0 worktree(s) to prune" line so piped consumers get a stable
/// signal instead of empty stdout.
///
/// Column widths are computed in Unicode characters
/// (`.chars().count()`), not bytes (`.len()`), so non-ASCII paths
/// stay aligned in a fixed-width terminal.
pub fn format_prune_plan(entries: &[worktree::PrunableEntry]) -> String {
  use std::fmt::Write;
  let mut out = String::new();
  if entries.is_empty() {
    let _ = writeln!(out, "0 worktree(s) to prune");
    return out;
  }
  // Widths in Unicode characters, not bytes — non-ASCII names or
  // paths would otherwise drift the reason column right by the
  // (byte_len - char_count) delta. Rust's `{:<width$}` format spec
  // pads to a *character* count, so feeding it `.len()` is the bug
  // Copilot flagged on PR #154.
  let name_w = entries.iter().map(|e| e.name.chars().count()).max().unwrap_or(4);
  let path_w = entries
    .iter()
    .map(|e| e.path.display().to_string().chars().count())
    .max()
    .unwrap_or(4);
  let _ = writeln!(out, "would prune {} worktree(s):", entries.len());
  for entry in entries {
    let _ = writeln!(
      out,
      "  {:<nw$}  {:<pw$}  ({})",
      entry.name,
      entry.path.display(),
      entry.reason,
      nw = name_w,
      pw = path_w,
    );
  }
  out
}

fn cmd_remove(
  pattern: String,
  delete_branch: bool,
  dry_run: bool,
  force: bool,
  skip_hooks: Option<String>,
  trust_mode: TrustMode,
) -> Result<()> {
  let repo = worktree::discover_repo(None)?;
  let workdir = repo.workdir().ok_or(GwmError::NotInGitRepo)?.to_path_buf();
  let found = worktree::find_fuzzy(&repo, &pattern)?;
  if dry_run {
    // Issue #31: print the would-remove plan and exit. Resolution
    // already happened above — an ambiguous pattern surfaced via
    // `find_fuzzy` returns the same `Other(... ambiguous ...)` error
    // the destructive form raises, satisfying the spec's "same error
    // contract" requirement. The journal hook MUST NOT fire here —
    // a preview that wrote to the journal would let the user "undo"
    // something that never happened.
    worktree::remove_dry_run(&repo, &found.id)?;
    print!(
      "{}",
      format_remove_plan(&found.name, &found.path, found.branch.as_deref(), delete_branch)
    );
    return Ok(());
  }

  let config = Config::load_for_repo(&workdir)?;
  let mut skips = HookSkips::parse(skip_hooks.as_deref())?;
  if force {
    skips = skips.with(HookPhase::PreRemove).with(HookPhase::PostRemove);
  }
  if config.hooks.has_any() {
    trust_or_prompt(&workdir, Some(&repo), trust_mode)?;
  }
  let pre_ctx = HookContext::for_worktree(&repo, &workdir, &found.path, &found.path, found.branch.as_deref());
  let report = lifecycle::run_phase(&config, HookPhase::PreRemove, &pre_ctx, &skips, false)?;
  print_lifecycle_report(&report);

  // Issue #29: capture the branch OID via libgit2 BEFORE the
  // destructive call so we can resurrect the branch on `gwm undo`.
  // We swallow any journal IO failure with a stderr warning rather
  // than blocking a destruction the user explicitly asked for —
  // losing recoverability is unfortunate, but failing the remove
  // because we can't write to `~/.local/share/gwm/history.toml` would
  // be far more surprising. (Disk full, read-only FS, sandboxed
  // CI runner without home dir, …)
  let branch_oid = found.branch.as_deref().and_then(|b| {
    repo
      .find_branch(b, git2::BranchType::Local)
      .ok()
      .and_then(|br| br.into_reference().target())
      .map(|o| o.to_string())
  });
  let repo_root = repo
    .workdir()
    .map(|p| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()))
    .unwrap_or_default();
  let entry = OpEntry {
    ts: chrono::Utc::now(),
    kind: crate::history::OpKind::Remove,
    worktree: found.name.clone(),
    branch: found.branch.clone(),
    branch_oid,
    path: found.path.clone(),
    deleted_branch: delete_branch,
    repo_root,
    undone: false,
  };
  if let Err(e) = history::record(entry) {
    eprintln!(
      "warning: failed to record undo journal entry: {} (continuing with the remove anyway)",
      e
    );
  }

  worktree::remove(&repo, &found.id, delete_branch)?;
  println!("✓ removed {} ({})", found.name, found.path.display());
  if delete_branch {
    if let Some(b) = &found.branch {
      println!("  branch {} deleted", b);
    }
  }
  let post_ctx = pre_ctx.with_cwd(&workdir);
  let report = lifecycle::run_phase(&config, HookPhase::PostRemove, &post_ctx, &skips, false)?;
  print_lifecycle_report(&report);
  Ok(())
}

fn cmd_path(pattern: String, format: OutputFormat) -> Result<()> {
  let repo = worktree::discover_repo(None)?;
  let found = worktree::find_fuzzy(&repo, &pattern)?;
  match format {
    OutputFormat::Text => println!("{}", found.path.display()),
    OutputFormat::Json => {
      let dto = json_api::JsonPath::from(&found);
      println!("{}", serde_json::to_string_pretty(&dto)?);
    }
  }
  Ok(())
}

fn cmd_bootstrap(target: Option<String>, skip_hooks: Option<String>, trust_mode: TrustMode) -> Result<()> {
  let RepoContext { repo, workdir, config } = repo_context(None)?;

  let mut worktree_branch: Option<String> = None;
  let worktree_path: PathBuf = match target {
    Some(t) => {
      let p = PathBuf::from(&t);
      if p.is_dir() {
        p
      } else {
        let found = worktree::find_fuzzy(&repo, &t)?;
        worktree_branch = found.branch.clone();
        found.path
      }
    }
    None => std::env::current_dir()?,
  };
  // Issue #477: only the fuzzy arm above resolves a branch, off the worktree
  // record. The other two left it `None`, so hooks received an empty
  // `{branch}` / `{type}` / `{issue}` — the same defect as `pr` and
  // `commit-prefix` with a quieter symptom. Read it from the target itself,
  // which covers a path that was given outright as well as the CWD.
  if worktree_branch.is_none() {
    worktree_branch = current_branch_at(Some(&worktree_path)).ok();
  }
  let skips = HookSkips::parse(skip_hooks.as_deref())?;

  trust_or_prompt(&workdir, Some(&repo), trust_mode)?;

  let hook_ctx = HookContext::for_worktree(
    &repo,
    &workdir,
    &worktree_path,
    &worktree_path,
    worktree_branch.as_deref(),
  );
  let report = lifecycle::run_phase(&config, HookPhase::PreBootstrap, &hook_ctx, &skips, false)?;
  print_lifecycle_report(&report);

  let ctx = BootstrapCtx {
    main_repo: &workdir,
    worktree: &worktree_path,
    config: &config,
  };
  let report = bootstrap::run_core(&ctx)?;
  print_report(&report);
  let report = lifecycle::run_phase(&config, HookPhase::PostBootstrap, &hook_ctx, &skips, false)?;
  print_lifecycle_report(&report);
  Ok(())
}

fn cmd_sync(pattern: Option<String>, merge: bool) -> Result<()> {
  // Resolve the target worktree. With a pattern, fuzzy-match against the
  // main repo's worktree list like the rest of gwm. Without one, default
  // to the worktree *containing* the CWD — which, unlike `find_fuzzy`,
  // may legitimately be the main worktree (syncing trunk is valid). We
  // discover that worktree's own workdir (not the CWD basename) so a
  // `gwm sync` from a subdirectory still names and targets the worktree
  // root rather than the subdir.
  let (target_path, name) = match pattern {
    Some(p) => {
      let repo = worktree::discover_repo(None)?;
      let found = worktree::find_fuzzy(&repo, &p)?;
      (found.path, found.name)
    }
    None => {
      let cwd = std::env::current_dir()?;
      let repo = Repository::discover(&cwd).map_err(|_| GwmError::NotInGitRepo)?;
      let workdir = repo.workdir().ok_or(GwmError::NotInGitRepo)?.to_path_buf();
      let name = workdir
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "worktree".into());
      (workdir, name)
    }
  };

  let strategy = if merge {
    SyncStrategy::Merge
  } else {
    SyncStrategy::Rebase
  };
  let report = sync::sync(&target_path, strategy)?;
  print!("{}", format_sync_report(&name, &report));
  Ok(())
}

/// Render a successful [`SyncReport`] as a single ✓ status line. The
/// error paths (dirty tree, missing upstream, conflicts) surface as
/// `GwmError` and are printed by `main`'s top-level handler, so this
/// only ever formats the success cases.
pub fn format_sync_report(name: &str, report: &SyncReport) -> String {
  match report.action {
    SyncAction::UpToDate => {
      format!("{} already up to date with {}\n", name, report.upstream)
    }
    SyncAction::Integrated => {
      let verb = match report.strategy {
        SyncStrategy::Rebase => "rebased",
        SyncStrategy::Merge => "merged",
      };
      let plural = if report.behind_before == 1 { "" } else { "s" };
      format!(
        "{} {} {} commit{} from {}\n",
        name, verb, report.behind_before, plural, report.upstream
      )
    }
  }
}

fn cmd_prune(dry_run: bool) -> Result<()> {
  let repo = worktree::discover_repo(None)?;
  if dry_run {
    // Issue #31: enumerate prunable worktrees (name + path + reason)
    // and render the plan through the shared formatter. Empty input
    // still emits "0 worktree(s) to prune" so piped consumers always
    // get a stable signal.
    let plan = worktree::prunable_worktrees(&repo)?;
    print!("{}", format_prune_plan(&plan));
    return Ok(());
  }
  let n = worktree::prune(&repo)?;
  println!("pruned {} stale worktree(s)", n);
  Ok(())
}

fn cmd_doctor(format: OutputFormat) -> Result<()> {
  let RepoContext { repo, workdir, config } = repo_context_lenient(None)?;

  // Thread the real global layer so the keymap check re-reads exactly what the
  // TUI loads, while keeping the ambient read out of `doctor::run` itself
  // (issue #219 review — injected contexts stay deterministic).
  let global = crate::config::global_config_path();
  let ctx = DoctorCtx {
    repo_workdir: &workdir,
    repo: &repo,
    config: &config,
    global_config_path: global.as_deref(),
  };
  let report = doctor::run(&ctx)?;
  match format {
    OutputFormat::Text => print_doctor_report(&report),
    OutputFormat::Json => {
      let dto = json_api::JsonDoctorReport::from(&report);
      println!("{}", serde_json::to_string_pretty(&dto)?);
    }
  }

  // The process exit code is identical in both formats: the JSON payload
  // also carries `exit_code`, but a `gwm doctor --format json` in a CI
  // `if`-guard must still see the conventional 0/1/2.
  let code = report.exit_code();
  if code != 0 {
    std::process::exit(code);
  }
  Ok(())
}

/// `gwm daemon` (issue #38, phase 2). Discovers the repo from the CWD,
/// binds the JSON-RPC socket, and serves until killed. The serving path
/// needs the `daemon` feature plus a supported transport — a unix domain
/// socket, or a named pipe on Windows (#439); elsewhere it returns a clean
/// error so the subcommand stays present (and help identical) everywhere.
#[cfg(all(any(unix, windows), feature = "daemon"))]
fn cmd_daemon(socket: Option<PathBuf>, poll_ms: u64) -> Result<()> {
  use std::sync::atomic::AtomicBool;
  use std::sync::Arc;

  let repo = worktree::discover_repo(None)?;
  let workdir = repo.workdir().ok_or(GwmError::NotInGitRepo)?.to_path_buf();
  // A user `--socket` is taken verbatim (we never touch its parent dir); the
  // default resolution may nest the socket in a private `gwm-<uid>/` dir on a
  // shared base, in which case `serve` owns and secures that dir (issue #341).
  let (socket, manage_socket_dir) = match socket {
    Some(s) => (s, false),
    None => crate::daemon::default_socket(),
  };
  let mut opts = crate::daemon::ServeOptions::new(socket, workdir, std::time::Duration::from_millis(poll_ms));
  opts.manage_socket_dir = manage_socket_dir;
  // `serve` prints the "listening" line itself, but only after the socket
  // is actually bound — so the message can't precede a bind failure (issue
  // #38 review). `socket` is kept by `opts`; nothing more to do here.
  crate::daemon::serve(&opts, Arc::new(AtomicBool::new(false)))
}

#[cfg(not(all(any(unix, windows), feature = "daemon")))]
fn cmd_daemon(socket: Option<PathBuf>, poll_ms: u64) -> Result<()> {
  let _ = (socket, poll_ms);
  Err(GwmError::Other(
    "daemon mode is unavailable in this build (requires the `daemon` feature on a supported platform)".into(),
  ))
}

/// Print one rendered statusline for the current cwd. Flushes immediately
/// so a `--watch` consumer (tmux / prompt) sees each update without buffer
/// lag. An empty render (no daemon, empty set) still prints a blank line so
/// the consumer's line count stays predictable.
fn print_statusline(worktrees: &[crate::json_api::JsonWorktree], cwd: &Path) {
  use std::io::Write;
  // Canonicalise both the cwd and each worktree path so a symlinked path
  // (macOS /var ↔ /private/var, or a worktree under a symlink) still
  // matches — the daemon hands back raw libgit2 paths (Codex review #311).
  let active = crate::statusline::active_index_with(worktrees, cwd, |p| {
    std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf())
  });
  println!("{}", crate::statusline::render(worktrees, active));
  let _ = io::stdout().flush();
}

#[cfg(all(any(unix, windows), feature = "daemon"))]
fn cmd_statusline(socket: Option<PathBuf>, watch: bool) -> Result<()> {
  let socket = socket.unwrap_or_else(crate::daemon::socket_path);
  // `print_statusline` canonicalises both the cwd and each worktree path,
  // so the raw cwd is fine here.
  let cwd = std::env::current_dir().unwrap_or_default();

  if watch {
    // Stream until the daemon goes away; the callback never asks to stop, so
    // `subscribe` returns only when the stream ends — unreachable, or the
    // daemon stopped / restarted after pushing snapshots. `statusline::watch`
    // renders each push and then emits a trailing blank so a long-running
    // consumer clears the now-stale line instead of freezing on it (#309).
    crate::statusline::watch(
      |cb| crate::daemon::client::subscribe(&socket, cb),
      |worktrees| print_statusline(worktrees, &cwd),
    );
    return Ok(());
  }

  match crate::daemon::client::list_once(&socket) {
    Ok(worktrees) => print_statusline(&worktrees, &cwd),
    // No daemon (or a transport error): graceful blank line, exit 0.
    Err(_) => print_statusline(&[], &cwd),
  }
  Ok(())
}

#[cfg(not(all(any(unix, windows), feature = "daemon")))]
fn cmd_statusline(socket: Option<PathBuf>, watch: bool) -> Result<()> {
  // No daemon transport in this build (`--no-default-features`, or an
  // unsupported platform): the statusline has no source, so it degrades to
  // the documented empty line (exit 0) rather than erroring. The statusline
  // is deliberately daemon-fed (#309: a prompt path must never open the
  // repo or scan artefact stores itself); unix rides the socket, Windows
  // the named pipe (#439).
  let _ = (socket, watch);
  let cwd = std::env::current_dir().unwrap_or_default();
  print_statusline(&[], &cwd);
  Ok(())
}

fn print_doctor_report(report: &doctor::DoctorReport) {
  // Issue #473: several checks quote config-supplied strings in their detail
  // (`base directory writable` renders `[worktree].base`, the guard checks
  // name their entries). Neutralised here, at the single sink, rather than in
  // each `Check::ok` / `failed` call, so a check added later is covered
  // without anyone having to remember.
  //
  // A detail can span rows: `check_config_parses` puts `toml`'s whole
  // caret-under-the-column diagnostic in it. Flattening that turned the output
  // of the recovery command into `?  |?1 | [worktree?`, so line breaks survive
  // here too. They are safe for the same reason they are safe in `main`: this
  // printer owns the margin, and every row it emits is indented under the
  // check that produced it.
  let clean = crate::naming::sanitise_block_for_terminal;
  let indented = |text: &str, first: &str| {
    let cleaned = clean(text);
    let mut lines = cleaned.split('\n');
    let mut out = format!("{}{}", first, lines.next().unwrap_or_default());
    for line in lines {
      out.push_str("\n      ");
      out.push_str(line);
    }
    out
  };
  for c in &report.checks {
    let sigil = match c.status {
      CheckStatus::Ok => "",
      CheckStatus::Warning => "!",
      CheckStatus::Failed => "",
    };
    // The check name is a fixed label, never config text, but it shares the
    // helper so a check that starts naming its subject cannot slip through.
    println!("{} {}", sigil, crate::naming::sanitise_for_terminal(&c.name));
    if !c.detail.is_empty() {
      println!("{}", indented(&c.detail, "    "));
    }
    if let Some(hint) = &c.fix_hint {
      println!("{}", indented(hint, ""));
    }
  }
}

fn cmd_types(gitmoji_flag: bool) -> Result<()> {
  // Resolve the active branch-type list. When invoked inside a repo
  // with a workdir we honour any `[[branch_types]]` override in
  // `.gwm.toml`; outside of one — or inside a bare repo where
  // `repo.workdir()` is `None` and there's no place to look for
  // `.gwm.toml` — we silently fall back to the built-in defaults so
  // `gwm types` remains useful as a discovery command (used by `gwm`
  // newcomers before they've initialised a config, and from CI inspect
  // commands that point at bare clones).
  let workdir = match worktree::discover_repo(None) {
    Ok(repo) => repo.workdir().map(|w| w.to_path_buf()),
    Err(_) => None,
  };
  let resolved = match &workdir {
    Some(w) => Config::load_for_repo(w)?.resolved_branch_types(),
    None => Config::default().resolved_branch_types(),
  };

  // Resolve the gitmoji map only when the caller asked for it — the
  // default `gwm types` output stays a stable two-column shape every
  // scripted parser of the pre-#85 surface depended on.
  let gitmoji_map = if gitmoji_flag {
    Some(gitmoji::load(workdir.as_deref())?)
  } else {
    None
  };

  // Align the description column on the longest name so a custom list
  // with a long entry (e.g. `migration`) still renders cleanly.
  let width = resolved.types.iter().map(|t| t.name.len()).max().unwrap_or(0).max(8);
  // When the gitmoji columns are active, align the shortcode column on
  // the widest shortcode (`:white_check_mark:`, currently 18 chars) so
  // the description column doesn't drift between rows.
  // Issue #473: `description` (from `[[branch_types]]`) and the shortcodes
  // (from `[gitmoji]`) are free text out of an unvetted `.gwm.toml`; `name` is
  // not, it is already constrained to `^[a-z]+$` by `validate_branch_types`.
  // Widths are measured on the neutralised strings so the columns still line
  // up: a replaced C1 control character is two bytes narrower than the one
  // it replaced.
  let clean = crate::naming::sanitise_for_terminal;
  let sc_width = match &gitmoji_map {
    Some(map) => map.iter().map(|(_, sc)| clean(sc).len()).max().unwrap_or(0).max(10),
    None => 0,
  };

  for t in &resolved.types {
    match &gitmoji_map {
      Some(map) => {
        // Two extra columns: unicode glyph (1 cell wide, padded for
        // BMP code points; emoji ZWJ sequences would break alignment
        // but our built-in set is all single-glyph) + shortcode.
        let shortcode = clean(map.get(&t.name).unwrap_or(":question:"));
        let unicode = gitmoji::shortcode_to_unicode(&shortcode);
        println!(
          "  {:<width$}  {}  {:<sw$}  {}",
          t.name,
          unicode,
          shortcode,
          clean(&t.description),
          width = width,
          sw = sc_width,
        );
      }
      None => {
        println!("  {:<width$}  {}", t.name, clean(&t.description), width = width);
      }
    }
  }
  println!();
  println!("(source: {})", resolved.source.label());
  Ok(())
}

/// `gwm commit-prefix [--branch <name>] [--unicode]` (issue #85).
/// Renders `:sparkles: feat(#41):` (or `✨ feat(#41):` with `--unicode`)
/// for the supplied branch or HEAD. Useful for shell prompts, AI
/// assistants, and the bundled `commit-msg` hook.
fn cmd_commit_prefix(branch_override: Option<String>, unicode: bool) -> Result<()> {
  // Two resolution paths: an explicit `--branch <name>` (no repo
  // *required* — useful for scripted contexts outside a repo) and
  // the implicit "use HEAD" branch (requires a repo). Both go through the
  // same parser so the prefix shape stays canonical regardless of entry
  // point — the repo's own where there is a repo, the built-in pattern
  // otherwise (issue #417).
  //
  // For BOTH paths we still attempt repo discovery so the workdir
  // handle is fed into `gitmoji::load` — this is what makes
  // per-repo `.gwm.toml` `[gitmoji]` overrides apply uniformly to
  // `gwm commit-prefix` (no flag, --branch, or whatever the
  // installed commit-msg hook ends up calling). Discovery failures
  // are silently downgraded to "no workdir" so the `--branch` form
  // still works outside a git checkout — that's the whole point of
  // the explicit-branch entry point.
  // `repo_name` rides along for issue #417: `{repo}` is a legal token in
  // `worktree.branch_pattern`, so compiling the parser needs the same name
  // the formatter used.
  let (workdir, repo_name, branch_name) = match branch_override {
    Some(name) => {
      // Best-effort discovery: outside a repo the user passed
      // `--branch` precisely because there's no HEAD to read; we
      // must not fail here. Inside a repo we want the workdir so
      // `.gwm.toml` overrides apply.
      let repo = worktree::discover_repo(None).ok();
      let workdir = repo.as_ref().and_then(|r| r.workdir().map(|w| w.to_path_buf()));
      (workdir, repo.as_ref().map(worktree::repo_name), name)
    }
    None => {
      let repo = worktree::discover_repo(None)?;
      let wd = repo.workdir().map(|w| w.to_path_buf());
      // Issue #477: the workdir and the repo name come from the main
      // checkout, because that is where `.gwm.toml` lives and what `{repo}`
      // expands to. The branch does not: the bundled `commit-msg` hook runs
      // this with git's working directory inside the worktree, so reading
      // `repo`'s HEAD prefixed every commit made from a worktree with
      // whatever the main checkout happened to be sitting on.
      let name = current_branch_at(None)?;
      (wd, Some(worktree::repo_name(&repo)), name)
    }
  };

  // Issue #417: the branch was written by expanding this repo's
  // `worktree.branch_pattern`, so it is read back by a parser compiled from
  // that same pattern — otherwise a repo that customised it gets no prefix
  // for branches gwm itself created. Outside a checkout there is no config to
  // consult and the built-in shape is all `--branch` can mean.
  let config = workdir.as_deref().and_then(|wd| Config::load_for_repo(wd).ok());
  let parser = match (config.as_ref(), repo_name.as_deref()) {
    (Some(cfg), Some(repo)) => crate::naming::BranchParser::from_config(cfg, repo),
    _ => crate::naming::BranchParser::builtin().clone(),
  };
  // Neutralised before it is ever quoted: `branch_pattern` is repo-supplied
  // and this command does not go through the trust gate, so an unvetted
  // `.gwm.toml` must not get a terminal escape channel out of an error message
  // (Codex review on PR #476).
  let pattern = crate::naming::sanitise_for_terminal(
    &config
      .as_ref()
      .map(|c| c.worktree.branch_pattern.clone())
      .unwrap_or_else(crate::config::default_branch_pattern),
  );

  // Issue #416: a free-form branch reaches here legitimately. This command
  // exists solely to derive a prefix from the branch *type* and issue, and a
  // name the user chose has neither — there is no honest default to fall back
  // to, so it stays an error. The message says the shape is unavailable
  // rather than implying the branch is wrong.
  let spec = parser.parse(&branch_name).ok_or_else(|| {
    GwmError::Other(format!(
      "branch '{}' does not match this repo's branch pattern `{}`, so it carries no branch type to \
       read — a commit prefix is derived from one, and a free-form branch has none. Pass --branch \
       <name written by the pattern>, or write the prefix by hand",
      branch_name, pattern
    ))
  })?;

  // Issue #417: a pattern that carries no `{type}` or `{issue}` *and* freezes
  // neither as a literal — `{type}/{desc}`, `{issue}-{desc}` — parses
  // perfectly and yields an empty segment. Rendering `resolve_prefix` from
  // that prints ` (#):`, a broken prefix shipped as a success straight into a
  // commit message. A pattern that hardcodes one (`feat/#{issue}-{desc}`) does
  // not land here: the literal is recovered, so the prefix is right.
  if spec.type_.is_empty() || spec.issue.is_empty() {
    let want = match (spec.type_.is_empty(), spec.issue.is_empty()) {
      // `and`, not `or`: a prefix needs both, so adding one placeholder on the
      // strength of this message would leave the command failing (Codex review
      // on PR #476).
      (true, true) => "`{type}` and `{issue}`",
      (true, false) => "`{type}`",
      _ => "`{issue}`",
    };
    return Err(GwmError::Other(format!(
      "this repo's branch pattern `{}` carries no {}, so branch '{}' has none to read — a commit \
       prefix is built from the branch type and issue number. Add {} to worktree.branch_pattern, \
       or write the prefix by hand",
      pattern, want, branch_name, want
    )));
  }

  let map = gitmoji::load(workdir.as_deref())?;
  let prefix = gitmoji::resolve_prefix(&map, &spec, unicode);
  // Issue #473: the prefix is assembled from `[gitmoji]` shortcodes read out
  // of `.gwm.toml`, and this command is ungated by design: shell prompts and
  // the bundled commit-msg hook call it on every commit, in whatever repo the
  // user happens to be sitting in.
  println!("{}", crate::naming::sanitise_for_terminal(&prefix));
  Ok(())
}

/// `gwm hooks <action>` (issue #85). Currently only `install
/// commit-msg` is wired up; the subcommand layer is shaped so future
/// hooks (`pre-push`, `pre-commit`) drop in without breaking the
/// existing CLI surface.
fn cmd_hooks(action: HooksAction) -> Result<()> {
  match action {
    HooksAction::Install { hook, force } => cmd_hooks_install(hook, force),
  }
}

fn cmd_hooks_install(hook: HookKind, force: bool) -> Result<()> {
  let repo = worktree::discover_repo(None)?;
  let workdir = repo.workdir().ok_or(GwmError::NotInGitRepo)?.to_path_buf();
  match hook {
    HookKind::CommitMsg => {
      let path = hooks::install_commit_msg(&workdir, force)?;
      println!("✓ installed {}", path.display());
      println!("  (auto-prepends gitmoji+type prefix when missing)");
    }
  }
  Ok(())
}

fn cmd_completions(shell: Shell) -> Result<()> {
  let mut cmd = Cli::command();
  let name = cmd.get_name().to_string();
  generate(shell, &mut cmd, name, &mut io::stdout());
  Ok(())
}

fn cmd_shell_init(shell: InitShell) -> Result<()> {
  print!("{}", shell_init_script(shell));
  Ok(())
}

/// `gwm switch` — open the TUI picker and emit the chosen worktree's path
/// on stdout. Returning a non-zero exit code when the user cancels lets the
/// shell wrapper (`gcd` in `shell-init`) skip the `cd` instead of cd'ing to
/// an empty argument.
///
/// The git-repo check runs before `tui::run_picker()` to keep the error
/// path identical to every other repo-bound subcommand (clean stderr,
/// no flicker into the alternate screen).
fn cmd_switch() -> Result<()> {
  // Probe the repo first; this is also what surfaces "not inside a git
  // repository" before we touch the terminal. Discarding the handle is
  // fine — `run_picker` re-discovers it via its own `App::new_picker_at`.
  let _ = worktree::discover_repo(None)?;
  match crate::tui::run_picker()? {
    Some(path) => {
      println!("{}", path.display());
      Ok(())
    }
    None => std::process::exit(1),
  }
}

/// `gwm tmux <pattern>` / `gwm zellij <pattern>` — open the matched
/// worktree in a new window/tab (or split with `--split`). The handler
/// is shared between the two multiplexers because the only difference
/// is the argv shape, already encoded in `multiplexer::build_*_command`.
///
/// Error contract (ordered, first match wins):
///   1. Not inside a git repo → `NotInGitRepo`.
///   2. Multiplexer not running → `Other("<bin> session not running …")`.
///   3. Worktree pattern doesn't match → `WorktreeNotFound`.
///   4. Spawn or non-zero exit from the multiplexer → `CommandFailed`.
///
/// Ordering #1 before #2 matches `gwm cd` / `gwm switch`: the repo gate
/// is the more fundamental problem, so we surface it first.
fn cmd_multiplexer(mux: Multiplexer, pattern: String, split: bool) -> Result<()> {
  let repo = worktree::discover_repo(None)?;

  let env_name = match mux {
    Multiplexer::Tmux => "TMUX",
    Multiplexer::Zellij => "ZELLIJ",
  };
  let env_value = std::env::var(env_name).ok();
  let running = match mux {
    Multiplexer::Tmux => detect_tmux(env_value),
    Multiplexer::Zellij => detect_zellij(env_value),
  };
  if !running {
    // `${env_name}` renders bare in stderr (not shell source, so no
    // backslash escaping). Pre-fix this read `\\${env_name}` and
    // surfaced `\$TMUX` to the user — caught at PR #65 review.
    return Err(GwmError::Other(format!(
      "{0} session not running (${1} unset) — run `gwm {0} <pattern>` from inside a {0} session",
      mux.binary(),
      env_name,
    )));
  }

  let found = worktree::find_fuzzy(&repo, &pattern)?;
  let mode = if split { SpawnMode::Split } else { SpawnMode::Window };
  let argv = match mux {
    Multiplexer::Tmux => build_tmux_command(&found.name, &found.path, mode),
    Multiplexer::Zellij => build_zellij_command(&found.name, &found.path, mode),
  };
  spawn_multiplexer(mux, &argv)
}

/// Spawn the multiplexer command and surface its exit status. argv[0] is
/// the binary; argv[1..] are the args. Matches `tui::mod::run_lazygit`
/// in shape — `.status()` so the user sees the child's own stderr live
/// instead of swallowing it into a buffered `CommandFailed`.
fn spawn_multiplexer(mux: Multiplexer, argv: &[String]) -> Result<()> {
  let (bin, rest) = argv.split_first().ok_or_else(|| {
    GwmError::Other(format!(
      "empty argv for {} spawn (build_*_command returned [])",
      mux.binary()
    ))
  })?;
  // The data string already names the binary (`tmux` / `zellij`), so
  // the rendered message reads `command failed: tmux exited with
  // status Some(1)` — attributable to the verb the user typed.
  let status = std::process::Command::new(bin)
    .args(rest)
    .status()
    .map_err(|e| GwmError::CommandFailed(format!("could not spawn {}: {}", bin, e)))?;
  if !status.success() {
    return Err(GwmError::CommandFailed(format!(
      "{} exited with status {:?}",
      bin,
      status.code()
    )));
  }
  Ok(())
}

// ---- Issue / PR link commands (issue #67) -------------------------------

/// Resolve the repo + branch + repo-relative path to operate on.
///
/// `--worktree <pattern>` overrides; otherwise we use the current directory.
/// The returned Repository is opened *at the target worktree*, so reading
/// HEAD gives the branch the user expects, but git config writes still land
/// on the main repo's config (git2 propagates branch.* config up).
fn resolve_target_repo(worktree: Option<String>) -> Result<(Repository, String, PathBuf)> {
  let path: PathBuf = match worktree {
    Some(pat) => {
      // Allow either a fuzzy worktree pattern or a direct path.
      let p = PathBuf::from(&pat);
      if p.is_dir() {
        p
      } else {
        let main = worktree::discover_repo(None)?;
        worktree::find_fuzzy(&main, &pat)?.path
      }
    }
    None => std::env::current_dir()?,
  };
  let repo = Repository::discover(&path).map_err(|_| GwmError::NotInGitRepo)?;
  let branch = current_branch(&repo)?;
  Ok((repo, branch, path))
}

/// The branch checked out *at* `start`, or at the current directory when
/// `start` is `None`.
///
/// Issue #477. [`worktree::discover_repo`] deliberately walks back to the
/// main working directory when it lands inside a linked worktree, which is
/// what every command operating on the whole worktree **set** needs: `list`,
/// `remove`, `switch`, `prune` all want the one handle that knows about all
/// of them. Asking that handle "which branch am I on" answers for the main
/// checkout instead, so `gwm commit-prefix` run by the bundled `commit-msg`
/// hook — which git invokes with the working directory inside the worktree —
/// derived its prefix from whatever the main checkout was sitting on.
///
/// So this discovers without the walk-back. It is deliberately *not* a
/// replacement for `repo_context`: `.gwm.toml`, the workdir and
/// [`worktree::repo_name`] all still want the main repo, and `{repo}` is a
/// legal token in `branch_pattern`, so widening this to the whole context
/// would compile the branch parser with the worktree directory's name and
/// stop reading branches gwm itself wrote. Only the branch moves.
///
/// [`resolve_target_repo`] already had the right shape, which is why
/// `gwm status` reported the right branch from the same directory all along.
fn current_branch_at(start: Option<&Path>) -> Result<String> {
  let from = match start {
    Some(p) => p.to_path_buf(),
    None => std::env::current_dir()?,
  };
  let repo = Repository::discover(&from).map_err(|_| GwmError::NotInGitRepo)?;
  current_branch(&repo)
}

fn current_branch(repo: &Repository) -> Result<String> {
  let head = repo.head().map_err(|_| GwmError::UnbornHead {
    reason: "HEAD is unborn or detached".into(),
  })?;
  head
    .shorthand()
    .ok()
    .map(|s| s.to_string())
    .ok_or_else(|| GwmError::UnbornHead {
      reason: "HEAD has no shorthand (detached?)".into(),
    })
}

fn cmd_link(target: LinkTarget, number: u64, worktree: Option<String>) -> Result<()> {
  let (repo, branch, _path) = resolve_target_repo(worktree)?;
  // Write under the backend marker that will later be checked against
  // this line, or the next command that resolves a forge deletes it.
  let config = Config::load_for_repo(repo.workdir().unwrap_or_else(|| repo.path()))?;
  forge::reconcile_links(&repo, &config);
  match target {
    LinkTarget::Issue => {
      github::link_issue(&repo, &branch, number)?;
      println!("✓ linked issue #{} to branch {}", number, branch);
    }
    LinkTarget::Pr => {
      github::link_pr(&repo, &branch, number)?;
      println!("✓ linked PR #{} to branch {}", number, branch);
    }
  }
  Ok(())
}

fn cmd_unlink(target: LinkTarget, worktree: Option<String>) -> Result<()> {
  let (repo, branch, _path) = resolve_target_repo(worktree)?;
  match target {
    LinkTarget::Issue => {
      github::unlink_issue(&repo, &branch)?;
      println!("✓ unlinked issue on branch {}", branch);
    }
    LinkTarget::Pr => {
      github::unlink_pr(&repo, &branch)?;
      println!("✓ unlinked PR on branch {}", branch);
    }
  }
  Ok(())
}

fn cmd_open(target: LinkTarget, worktree: Option<String>, print_url: bool) -> Result<()> {
  let (repo, branch, _path) = resolve_target_repo(worktree)?;
  // Resolve first: `forge::resolve` reconciles the persisted links
  // against the backend about to read them, and `gwm open` is exactly
  // the command that would otherwise send the user to the stale
  // number's page one last time.
  let config = Config::load_for_repo(repo.workdir().unwrap_or_else(|| repo.path()))?;
  let forge = forge::resolve(&repo, &config)?;
  let link = github::read_link(&repo, &branch)?;

  let url = match target {
    LinkTarget::Issue => {
      let n = link.issue.ok_or_else(|| GwmError::LinkMissing {
        kind: LinkKind::Issue,
        branch: branch.clone(),
      })?;
      forge.issue_url_confirmed(n)
    }
    LinkTarget::Pr => {
      let n = link.pr.ok_or_else(|| GwmError::LinkMissing {
        kind: LinkKind::Pr,
        branch: branch.clone(),
      })?;
      forge.pr_url_confirmed(n)
    }
  };

  if print_url {
    println!("{}", url);
    return Ok(());
  }
  spawn_opener(&url)
}

fn spawn_opener(url: &str) -> Result<()> {
  let opener = if cfg!(target_os = "macos") {
    "open"
  } else if cfg!(target_os = "windows") {
    "explorer"
  } else {
    "xdg-open"
  };
  let status = std::process::Command::new(opener)
    .arg(url)
    .status()
    .map_err(|e| GwmError::CommandFailed(format!("could not spawn {}: {}", opener, e)))?;
  if !status.success() {
    return Err(GwmError::CommandFailed(format!(
      "{} exited with status {:?}",
      opener,
      status.code()
    )));
  }
  Ok(())
}

fn cmd_status(worktree: Option<String>, json: bool) -> Result<()> {
  let (repo, branch, _path) = resolve_target_repo(worktree)?;

  // Forge + fetched status are best-effort: if there's no remote or the
  // forge CLI isn't installed, we still print the local link.
  let config = Config::load_for_repo(repo.workdir().unwrap_or_else(|| repo.path()))?;
  let forge = forge::resolve(&repo, &config).ok();
  let slug = forge.as_ref().map(|f| f.slug().to_string());
  // When a remote is present, auto-detect the branch's PR if none is
  // explicitly linked (issue #181). Falls back to the plain local read
  // with no remote — keeping the "local link only" mode network-free.
  let link = match forge.as_ref() {
    Some(f) => github::read_link_with_pr_detection(&repo, &branch, f.as_ref())?,
    None => github::read_link(&repo, &branch)?,
  };
  let (issue_status, pr_status) = fetch_link_status(&repo, &branch, &link, forge.as_deref());

  if json {
    println!(
      "{}",
      build_status_json(&branch, slug.as_deref(), &link, &issue_status, &pr_status)
    );
  } else {
    let pr_noun = forge.as_ref().map_or("PR", |f| f.pr_noun());
    print_status_human(&branch, slug.as_deref(), &link, &issue_status, &pr_status, pr_noun);
  }
  Ok(())
}

fn fetch_link_status(
  repo: &Repository,
  branch: &str,
  link: &BranchLink,
  forge: Option<&dyn forge::Forge>,
) -> (Option<IssueStatus>, Option<PrStatus>) {
  let Some(forge) = forge else {
    return (None, None);
  };
  // The forge CLI is optional — if either call fails we degrade gracefully.
  let issue = link.issue.and_then(|n| forge.fetch_issue(n).ok());
  let pr = link.pr.and_then(|n| forge.fetch_pr(n).ok());
  if let Some(issue) = &issue {
    let _ = github::persist_issue_title(repo, branch, &issue.title);
    let _ = github::persist_issue_state(repo, branch, issue.state);
  }
  if let Some(pr) = &pr {
    let _ = match link.pr_source {
      LinkSource::Detected => github::persist_detected_pr_title(repo, branch, &pr.title)
        .and_then(|()| github::persist_detected_pr_state(repo, branch, pr.state)),
      LinkSource::Explicit => github::persist_pr_title(repo, branch, &pr.title)
        .and_then(|()| github::persist_pr_state(repo, branch, pr.state)),
      LinkSource::BranchName | LinkSource::None => Ok(()),
    };
  }
  (issue, pr)
}

fn issue_state_str(s: IssueState) -> &'static str {
  match s {
    IssueState::Open => "open",
    IssueState::Closed => "closed",
  }
}

fn pr_state_str(s: PrState) -> &'static str {
  match s {
    PrState::Open => "open",
    PrState::Draft => "draft",
    PrState::Closed => "closed",
    PrState::Merged => "merged",
  }
}

fn link_source_str(s: LinkSource) -> &'static str {
  match s {
    LinkSource::None => "none",
    LinkSource::BranchName => "branch-name",
    LinkSource::Explicit => "explicit",
    LinkSource::Detected => "detected",
  }
}

fn print_status_human(
  branch: &str,
  slug: Option<&str>,
  link: &BranchLink,
  issue: &Option<IssueStatus>,
  pr: &Option<PrStatus>,
  // "PR" / "MR" (issue #419). The `issue:` / `pr:` field labels below stay
  // put: they are output *keys* a script greps for, not prose, and the
  // `--json` payload freezes the same names.
  pr_noun: &str,
) {
  println!("branch: {}", branch);
  if let Some(s) = slug {
    println!("repo:   {}", s);
  }
  println!("link:   {}", link.summary(pr_noun));

  if let Some(n) = link.issue {
    print!("issue:  #{}", n);
    match issue {
      Some(s) => println!(" [{}] {}", issue_state_str(s.state), s.title),
      None => println!(" (status unavailable)"),
    }
  }
  if let Some(n) = link.pr {
    print!("pr:     #{}", n);
    match pr {
      Some(s) => {
        let checks = if s.checks_total > 0 {
          format!(" · checks {}/{}", s.checks_passed, s.checks_total)
        } else {
          String::new()
        };
        println!(" [{}]{} {}", pr_state_str(s.state), checks, s.title);
      }
      None => println!(" (status unavailable)"),
    }
  }
}

/// Build the `gwm status --json` payload — a stable, hand-built schema for
/// scripting (frozen by `tests/contract_tests.rs`, documented in
/// `docs/schema/status.schema.json`, issue #317). Pure: returns the value so
/// the contract test can pin its shape without spawning the binary or hitting
/// GitHub. `print`-ing is the caller's job.
pub fn build_status_json(
  branch: &str,
  slug: Option<&str>,
  link: &BranchLink,
  issue: &Option<IssueStatus>,
  pr: &Option<PrStatus>,
) -> serde_json::Value {
  let mut obj = serde_json::Map::new();
  obj.insert("branch".into(), serde_json::Value::String(branch.into()));
  if let Some(s) = slug {
    obj.insert("repo".into(), serde_json::Value::String(s.into()));
  }
  obj.insert(
    "issue".into(),
    match link.issue {
      Some(n) => {
        let mut o = serde_json::Map::new();
        o.insert("number".into(), serde_json::Value::Number(n.into()));
        o.insert(
          "source".into(),
          serde_json::Value::String(link_source_str(link.issue_source).into()),
        );
        if let Some(s) = issue {
          o.insert(
            "state".into(),
            serde_json::Value::String(issue_state_str(s.state).into()),
          );
          o.insert("title".into(), serde_json::Value::String(s.title.clone()));
          o.insert(
            "labels".into(),
            serde_json::Value::Array(s.labels.iter().map(|l| serde_json::Value::String(l.clone())).collect()),
          );
          o.insert("url".into(), serde_json::Value::String(s.url.clone()));
        }
        serde_json::Value::Object(o)
      }
      None => serde_json::Value::Null,
    },
  );
  obj.insert(
    "pr".into(),
    match link.pr {
      Some(n) => {
        let mut o = serde_json::Map::new();
        o.insert("number".into(), serde_json::Value::Number(n.into()));
        o.insert(
          "source".into(),
          serde_json::Value::String(link_source_str(link.pr_source).into()),
        );
        if let Some(s) = pr {
          o.insert("state".into(), serde_json::Value::String(pr_state_str(s.state).into()));
          o.insert("title".into(), serde_json::Value::String(s.title.clone()));
          o.insert(
            "checks_passed".into(),
            serde_json::Value::Number(s.checks_passed.into()),
          );
          o.insert("checks_total".into(), serde_json::Value::Number(s.checks_total.into()));
          o.insert("url".into(), serde_json::Value::String(s.url.clone()));
        }
        serde_json::Value::Object(o)
      }
      None => serde_json::Value::Null,
    },
  );
  serde_json::Value::Object(obj)
}

// ---- Labels commands (issue #81) ----------------------------------------

fn cmd_labels(action: LabelsAction) -> Result<()> {
  match action {
    LabelsAction::List => cmd_labels_list(),
    LabelsAction::Push {
      dry_run,
      prune,
      random_colors,
    } => cmd_labels_push(dry_run, prune, random_colors),
  }
}

fn cmd_labels_list() -> Result<()> {
  let config = load_labels_config()?;
  if config.labels.is_empty() {
    println!("0 labels declared in .gwm.toml — nothing to push.");
    return Ok(());
  }
  // Resolve (and validate colours) before touching the network, so a
  // typo in `.gwm.toml` surfaces "label 'bug' has invalid color: …"
  // rather than the unrelated "no origin remote" error.
  let declared = labels::resolve_labels(&config.labels, false)?;
  let forge = labels_forge(&config)?;
  let remote = forge.fetch_remote_labels()?;
  let diff = labels::diff_labels(&declared, &remote);
  print_labels_diff(forge.slug(), &declared, &diff);
  Ok(())
}

fn cmd_labels_push(dry_run: bool, prune: bool, random_colors: bool) -> Result<()> {
  let config = load_labels_config()?;
  if config.labels.is_empty() {
    println!("0 labels declared in .gwm.toml — nothing to push.");
    return Ok(());
  }
  let declared = labels::resolve_labels(&config.labels, random_colors)?;
  let forge = labels_forge(&config)?;
  let remote = forge.fetch_remote_labels()?;
  let diff = labels::diff_labels(&declared, &remote);
  let (n_create, n_update, n_match, n_extra) = diff.counts();

  // Before the dry-run branch, mirroring the milestone path: a prune
  // that trips over a hostile remote label name must not have deleted
  // half the batch first, and a dry-run must not advertise a plan that
  // cannot run (Codex review #458).
  if prune {
    for remote_label in &diff.extra_on_remote {
      labels::validate_label_name(&remote_label.name).map_err(|e| {
        let inner = match e {
          GwmError::Config(msg) => msg,
          other => other.to_string(),
        };
        GwmError::Config(format!("labels (remote): {inner} — refusing to prune"))
      })?;
    }
  }

  if dry_run {
    print_labels_diff(forge.slug(), &declared, &diff);
    let pruned = if prune { n_extra } else { 0 };
    println!(
      "{}",
      labels::diff_dry_run_line(n_create, n_update, n_match, n_extra, pruned)
    );
    return Ok(());
  }

  for spec in &diff.to_create {
    forge.create_label(spec)?;
    println!("✓ created {}", spec.name);
  }
  for upd in &diff.to_update {
    forge.update_label(&upd.spec)?;
    println!("✓ updated {}", upd.spec.name);
  }
  if prune {
    for remote_label in &diff.extra_on_remote {
      forge.delete_label(&remote_label.name)?;
      println!("✗ pruned {}", remote_label.name);
    }
  } else if !diff.extra_on_remote.is_empty() {
    println!(
      "{} label(s) on remote not in config — pass --prune to delete",
      diff.extra_on_remote.len()
    );
  }
  println!("{} label(s) untouched", n_match);
  Ok(())
}

/// Open the repo and parse `.gwm.toml`. Shared by `labels list /
/// push`; both surface a uniform "not inside a git repository" error
/// before they touch network or config-resolve logic.
fn load_labels_config() -> Result<Config> {
  Ok(repo_context(None)?.config)
}

/// Resolve the `origin` remote slug. Called *after* `resolve_labels`
/// in both subcommands so a config typo (bad colour) surfaces with
/// the offending label name rather than the unrelated "no origin
/// remote" error.
/// Resolve the forge for the discovered repo. Called *after*
/// `resolve_labels` / `resolve_milestones` in all four subcommands so a
/// config typo (bad colour, bad due_on) surfaces with the offending entry
/// name rather than the unrelated "no origin remote" error.
fn labels_forge(config: &Config) -> Result<std::sync::Arc<dyn forge::Forge>> {
  let repo = worktree::discover_repo(None)?;
  forge::resolve(&repo, config)
}

fn print_labels_diff(slug: &str, declared: &[labels::LabelSpec], diff: &LabelDiff) {
  for line in labels_diff_lines(slug, declared, diff) {
    println!("{}", line);
  }
}

/// The rows `gwm labels list` / `push --dry-run` print, as values (issue
/// #473). Same seam and same reason as [`milestones_diff_lines`].
///
/// A declared `name` is the least exposed field here: `labels::
/// validate_label_name` already rejects it at load. But it rejects
/// `is_ascii_control` only, which leaves the C1 range (U+0080..U+009F, CSI
/// among them) through, and `remote.name` / `slug` come off the forge rather
/// than the config and are validated by nobody.
pub fn labels_diff_lines(slug: &str, declared: &[labels::LabelSpec], diff: &LabelDiff) -> Vec<String> {
  let clean = crate::naming::sanitise_for_terminal;
  let (n_create, n_update, n_match, n_extra) = diff.counts();
  let mut lines = vec![format!(
    "declared in .gwm.toml: {} labels — diff against {}:",
    declared.len(),
    clean(slug)
  )];
  for spec in &diff.to_create {
    lines.push(format!(
      "  + {:<20} (will create, color #{})",
      clean(&spec.name),
      clean(&spec.color)
    ));
  }
  for upd in &diff.to_update {
    let detail = match (&upd.previous_color, &upd.previous_description) {
      (Some(old), _) => format!("color #{} → #{}", old, upd.spec.color),
      (None, Some(_)) => "description changed".into(),
      _ => "diff".into(),
    };
    lines.push(format!("  ~ {:<20} ({})", clean(&upd.spec.name), clean(&detail)));
  }
  for spec in &diff.matching {
    lines.push(format!("  = {:<20} (match)", clean(&spec.name)));
  }
  for remote in &diff.extra_on_remote {
    lines.push(format!("  - {:<20} (on remote, not in config)", clean(&remote.name)));
  }
  lines.push(labels::diff_summary_line(n_create, n_update, n_match, n_extra));
  lines
}

// ---- Milestones commands (issue #82) ------------------------------------

fn cmd_milestones(action: MilestonesAction) -> Result<()> {
  match action {
    MilestonesAction::List => cmd_milestones_list(),
    MilestonesAction::Push { dry_run, prune } => cmd_milestones_push(dry_run, prune),
  }
}

fn cmd_milestones_list() -> Result<()> {
  let config = load_milestones_config()?;
  if config.milestones.is_empty() {
    println!("0 milestones declared in .gwm.toml — nothing to push.");
    return Ok(());
  }
  // Resolve (and validate due_on / state) before touching the network,
  // so a typo in `.gwm.toml` surfaces "milestone 'v0.7.0' has invalid
  // …" rather than the unrelated "no origin remote" error.
  let declared = milestones::resolve_milestones(&config.milestones)?;
  let forge = labels_forge(&config)?;
  let remote = forge.fetch_remote_milestones()?;
  let diff = milestones::diff_milestones(&declared, &remote);
  print_milestones_diff(forge.slug(), &declared, &diff);
  Ok(())
}

fn cmd_milestones_push(dry_run: bool, prune: bool) -> Result<()> {
  let config = load_milestones_config()?;
  if config.milestones.is_empty() {
    println!("0 milestones declared in .gwm.toml — nothing to push.");
    return Ok(());
  }
  let declared = milestones::resolve_milestones(&config.milestones)?;
  let forge = labels_forge(&config)?;
  let remote = forge.fetch_remote_milestones()?;
  let diff = milestones::diff_milestones(&declared, &remote);
  let (n_create, n_update, n_match, n_extra) = diff.counts();

  // Before the dry-run branch on purpose: a plan the forge will reject
  // must not be printed as runnable, and a real push must not apply half
  // the batch before hitting the bad entry (Codex review #458).
  for spec in &diff.to_create {
    forge.validate_milestone(spec)?;
  }
  for upd in &diff.to_update {
    forge.validate_milestone(&upd.spec)?;
  }

  if dry_run {
    print_milestones_diff(forge.slug(), &declared, &diff);
    let pruned = if prune { n_extra } else { 0 };
    println!(
      "{}",
      labels::diff_dry_run_line(n_create, n_update, n_match, n_extra, pruned)
    );
    return Ok(());
  }

  for spec in &diff.to_create {
    forge.create_milestone(spec)?;
    println!("✓ created {}", spec.title);
  }
  for upd in &diff.to_update {
    forge.update_milestone(upd.number, &upd.spec)?;
    println!("✓ updated {}", upd.spec.title);
  }
  if prune {
    for remote_milestone in &diff.extra_on_remote {
      forge.delete_milestone(remote_milestone.number)?;
      println!("✗ pruned {}", remote_milestone.title);
    }
  } else if !diff.extra_on_remote.is_empty() {
    println!(
      "{} milestone(s) on remote not in config — pass --prune to delete",
      diff.extra_on_remote.len()
    );
  }
  println!("{} milestone(s) untouched", n_match);
  Ok(())
}

/// Open the repo and parse `.gwm.toml`. Shared by `milestones list /
/// push`; both surface a uniform "not inside a git repository" error
/// before they touch network or config-resolve logic.
fn load_milestones_config() -> Result<Config> {
  Ok(repo_context(None)?.config)
}

fn print_milestones_diff(slug: &str, declared: &[milestones::MilestoneSpec], diff: &MilestoneDiff) {
  for line in milestones_diff_lines(slug, declared, diff) {
    println!("{}", line);
  }
}

/// The rows `gwm milestones list` / `push --dry-run` print, as values rather
/// than `println!` side effects (issue #473).
///
/// A value because the printer is only reachable after a live forge round
/// trip (`fetch_remote_milestones`), so there is no way to assert on it from a
/// test without mocking `gh`. Unlike a label name, a milestone `title` is free
/// text that nothing validates on load, and `gwm milestones list` reads
/// `.gwm.toml` without the trust gate.
pub fn milestones_diff_lines(slug: &str, declared: &[milestones::MilestoneSpec], diff: &MilestoneDiff) -> Vec<String> {
  let clean = crate::naming::sanitise_for_terminal;
  let (n_create, n_update, n_match, n_extra) = diff.counts();
  let mut lines = vec![format!(
    "declared in .gwm.toml: {} milestones — diff against {}:",
    declared.len(),
    clean(slug)
  )];
  for spec in &diff.to_create {
    let due = spec.due_on.as_deref().unwrap_or("no due date");
    lines.push(format!(
      "  + {:<20} (will create, state {}, due {})",
      clean(&spec.title),
      spec.state.as_str(),
      clean(due)
    ));
  }
  for upd in &diff.to_update {
    let detail = match (&upd.previous_due_on, &upd.previous_state, &upd.previous_description) {
      (Some(old_due), _, _) => format!("due {}{}", old_due, upd.spec.due_on.as_deref().unwrap_or("cleared")),
      (None, Some(old_state), _) => format!("state {}{}", old_state.as_str(), upd.spec.state.as_str()),
      (None, None, Some(_)) => "description changed".into(),
      _ => "diff".into(),
    };
    lines.push(format!("  ~ {:<20} ({})", clean(&upd.spec.title), clean(&detail)));
  }
  for spec in &diff.matching {
    lines.push(format!("  = {:<20} (match)", clean(&spec.title)));
  }
  for remote in &diff.extra_on_remote {
    lines.push(format!(
      "  - {:<20} (#{} on remote, not in config)",
      clean(&remote.title),
      remote.number
    ));
  }
  lines.push(labels::diff_summary_line(n_create, n_update, n_match, n_extra));
  lines
}

// ---- Trust ledger commands (issue #95) ----------------------------------

fn cmd_trust(action: TrustAction) -> Result<()> {
  match action {
    TrustAction::Add => cmd_trust_add(),
    TrustAction::List => cmd_trust_list(),
    TrustAction::Revoke { origin } => cmd_trust_revoke(origin),
    TrustAction::Show => cmd_trust_show(),
  }
}

fn cmd_trust_list() -> Result<()> {
  let path = trust::default_ledger_path()?;
  let ledger = TrustLedger::load(&path)?;
  if ledger.entries.is_empty() {
    println!("0 entries in trust ledger ({}).", path.display());
    return Ok(());
  }
  println!("trust ledger: {}", path.display());
  println!(
    "  {} entr{} recorded:",
    ledger.entries.len(),
    if ledger.entries.len() == 1 { "y" } else { "ies" }
  );
  // Issue #473, Codex pass 2: `trust show` cats the ledger file, where TOML
  // has already escaped any control byte in a value, but `load` DECODES it, so
  // every command that reads the ledger back through `TrustLedger` handles the
  // real character. `origin` is a remote URL that arrived with a clone, and
  // this listing is exactly what someone runs to audit what they trusted.
  let clean = crate::naming::sanitise_for_terminal;
  let origin_w = ledger
    .entries
    .iter()
    .map(|e| clean(&e.origin).len())
    .max()
    .unwrap_or(6)
    .clamp(6, 60);
  for e in &ledger.entries {
    // First 12 chars of the sha256 is plenty for a visual diff; the
    // full digest still ships in the toml file for forensic use.
    // Truncate by chars (not bytes) so a hand-edited ledger with a
    // multi-byte `config_sha` (corrupt but parseable TOML) renders
    // instead of panicking on a UTF-8 boundary.
    let short_sha: String = e.config_sha.chars().take(12).collect();
    println!(
      "  {:<ow$}  {}  trusted_at {}  by {}",
      clean(&e.origin),
      clean(&short_sha),
      e.trusted_at.to_rfc3339(),
      clean(&e.trusted_by),
      ow = origin_w,
    );
  }
  Ok(())
}

fn cmd_trust_revoke(origin: String) -> Result<()> {
  let path = trust::default_ledger_path()?;
  let mut ledger = TrustLedger::load(&path)?;
  let removed = ledger.revoke(&origin);
  // Echoed back rather than read from the ledger, but it lands in the same
  // terminal and costs one call (issue #473).
  let shown = crate::naming::sanitise_for_terminal(&origin);
  if removed == 0 {
    println!("0 entries matched origin {} (nothing to revoke).", shown);
    return Ok(());
  }
  ledger.save(&path)?;
  println!(
    "✓ revoked {} entr{} for {}",
    removed,
    if removed == 1 { "y" } else { "ies" },
    shown
  );
  Ok(())
}

fn cmd_trust_add() -> Result<()> {
  let cwd = std::env::current_dir()?;
  let repo = Repository::discover(&cwd).map_err(|_| GwmError::NotInGitRepo)?;
  let workdir = repo.workdir().unwrap_or_else(|| repo.path()).to_path_buf();
  // Same key every other gate uses — see `trust::origin_key_for_repo`.
  let key = trust::origin_key_for_repo(&repo, &workdir);
  match trust::record_config(&workdir, &key, &trust::current_actor())? {
    Some(sha) => {
      let short: String = sha.chars().take(12).collect();
      // `key` is the repo's origin URL (issue #473).
      println!(
        "✓ trusted {} (.gwm.toml {})",
        crate::naming::sanitise_for_terminal(&key),
        short
      );
      Ok(())
    }
    None => Err(GwmError::Other(format!(
      "no .gwm.toml in {} — there is nothing to trust here",
      workdir.display()
    ))),
  }
}

fn cmd_trust_show() -> Result<()> {
  let path = trust::default_ledger_path()?;
  println!("ledger path: {}", path.display());
  match std::fs::read_to_string(&path) {
    Ok(body) => {
      // Issue #473: the ledger records one origin key per trusted repo, and
      // an origin is a remote URL that arrived with a clone. Block variant,
      // the ledger is a file and its rows are its shape.
      let body = crate::naming::sanitise_block_for_terminal(&body);
      println!("---");
      print!("{}", body);
      if !body.ends_with('\n') {
        println!();
      }
    }
    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
      println!("(file does not exist yet — nothing has been trusted on this machine)");
    }
    Err(e) => return Err(e.into()),
  }
  Ok(())
}

/// TOFU gate called by `cmd_create` and `cmd_bootstrap` before any
/// `bootstrap::run` invocation. The contract:
///
///   * Returns `Ok(())` when the caller is cleared to proceed.
///   * Returns `Err(GwmError::Other(..))` when the user declined,
///     `--deny-bootstrap` was passed, or stdin isn't interactive and
///     no `--allow-bootstrap` bypass was provided.
///   * No-ops silently when there is no `.gwm.toml` in the workdir
///     (nothing for bootstrap to execute — no trust decision needed).
///
/// The `repo` is passed in so we can read `origin` from the existing
/// `Repository` handle (already opened by every caller) without
/// re-discovering it. Falls back to the canonical workdir path when
/// there is no origin remote — local-only repos still benefit from
/// the drift-detection half of the feature even when the threat model
/// is weaker.
fn trust_or_prompt(workdir: &Path, repo: Option<&Repository>, mode: TrustMode) -> Result<()> {
  let origin_key = match repo {
    Some(r) => trust::origin_key_for_repo(r, workdir),
    None => trust::resolve_origin_key(None, workdir),
  };

  match trust::evaluate(workdir, &origin_key, mode)? {
    TrustOutcome::Proceed => Ok(()),
    TrustOutcome::Refuse { message } => Err(GwmError::Other(message)),
    TrustOutcome::Prompt {
      cfg_path,
      body,
      sha,
      origin,
      mut ledger,
      ledger_path,
    } => {
      // Refuse cleanly if stdin isn't a tty rather than hanging on a
      // read that will never see input — this is the case that makes
      // `--allow-bootstrap` actually load-bearing in CI.
      use std::io::IsTerminal;
      if !std::io::stdin().is_terminal() {
        return Err(GwmError::Other(format!(
          ".gwm.toml at {} is not in the trust ledger and stdin is not interactive — \
           pass --allow-bootstrap (or set GWM_ALLOW_BOOTSTRAP=1) to bypass, \
           or run interactively to approve",
          cfg_path.display()
        )));
      }

      let granted = prompt_user(&cfg_path, &body, &origin, &sha)?;
      if !granted {
        return Err(GwmError::Other(format!(
          "trust prompt declined for {} — aborting bootstrap",
          cfg_path.display()
        )));
      }

      ledger.record(&origin, &sha, &trust::current_actor());
      ledger.save(&ledger_path)?;
      println!(
        "✓ recorded trust for {} in {}",
        crate::naming::sanitise_for_terminal(&origin),
        ledger_path.display()
      );
      Ok(())
    }
  }
}

/// Pull the `origin` remote URL out of a Repository handle, if there
/// is one. Returns `None` for repos with no `origin` remote — caller
/// (or `trust::resolve_origin_key`) falls back to the canonical
/// workdir path in that case.
/// Interactive y/N/show loop. Prints a one-shot summary of the
/// bootstrap surface (copy targets, guards, command lines, no-symlink
/// declarations) so the user has the relevant signal before answering.
/// `show` re-prints the raw `.gwm.toml`.
fn prompt_user(cfg_path: &Path, bytes: &[u8], origin: &str, sha: &str) -> Result<bool> {
  use std::io::{BufRead, Write};

  let body = String::from_utf8_lossy(bytes);
  let parsed: Option<Config> = toml::from_str(&body).ok();
  let stdin = std::io::stdin();
  let mut stdout = std::io::stdout();

  println!();
  println!("gwm: this repo's .gwm.toml has not been trusted yet.");
  println!("     path   : {}", cfg_path.display());
  // Issue #473: `origin` is a remote URL out of `.git/config`, which travels
  // with a clone just like `.gwm.toml` does. Nothing here has been vetted yet
  // That is what the prompt below is asking.
  println!("     origin : {}", crate::naming::sanitise_for_terminal(origin));
  println!("     hash   : {}", sha);
  if let Some(cfg) = parsed.as_ref() {
    print_bootstrap_summary(cfg);
  } else {
    println!("     (could not parse .gwm.toml for summary — see raw via `show` below)");
  }
  println!();

  loop {
    print!("Trust this .gwm.toml? [y/N/show]: ");
    stdout.flush().ok();
    let mut line = String::new();
    let n = stdin.lock().read_line(&mut line)?;
    if n == 0 {
      // EOF without an answer — same conservative default as `N`.
      return Ok(false);
    }
    match line.trim().to_ascii_lowercase().as_str() {
      "y" | "yes" => return Ok(true),
      "n" | "no" | "" => return Ok(false),
      "show" | "s" => {
        // Issue #473: the block variant, because this IS the file and its
        // line breaks are its shape. Neutralising the rest is not "breaking
        // raw": an escape sequence buried in the body defeats the very
        // inspection `show` exists to provide.
        let body = crate::naming::sanitise_block_for_terminal(&body);
        println!("---");
        print!("{}", body);
        if !body.ends_with('\n') {
          println!();
        }
        println!("---");
      }
      other => {
        println!(
          "unrecognised answer '{}': answer y, N, or show",
          crate::naming::sanitise_for_terminal(other)
        );
      }
    }
  }
}

fn print_bootstrap_summary(cfg: &Config) {
  for line in bootstrap_summary_lines(cfg) {
    println!("{}", line);
  }
}

/// The lines the TOFU prompt shows for an **untrusted** `.gwm.toml`, as
/// values rather than as `println!` side effects (issue #473).
///
/// A value so the highest-stakes echo in the binary can be asserted on
/// without driving a PTY: this summary is rendered immediately above
/// `Trust this .gwm.toml? [y/N/show]:`, from a file the user has by
/// definition not vetted, and it is the only thing standing between them
/// and a `[[bootstrap.command]]` that runs arbitrary shell.
pub fn bootstrap_summary_lines(cfg: &Config) -> Vec<String> {
  let bs = &cfg.bootstrap;
  if bs.copy.is_empty() && bs.command.is_empty() && bs.guard.is_empty() && bs.no_symlink.is_empty() {
    return vec!["     bootstrap surface: (empty, no copies/commands/guards/no_symlinks declared)".to_string()];
  }
  // Issue #473: every field below is verbatim text from a file the user has
  // NOT trusted, which is the whole premise of the prompt this feeds. Left
  // raw, `\u{1b}[1A\u{1b}[2K` in a `[[bootstrap.command]]` name walks the
  // cursor up and erases the row above, so the malicious `run` line can
  // delete the very evidence the summary exists to show.
  let clean = crate::naming::sanitise_for_terminal;
  let mut lines = vec!["     bootstrap surface:".to_string()];
  for c in &bs.copy {
    lines.push(format!("       - copy   {}{}", clean(&c.from), clean(&c.to)));
  }
  for g in &bs.guard {
    lines.push(format!(
      "       - guard  {} (on_match={}, deny={} pattern(s))",
      clean(&g.name),
      g.on_match,
      g.deny_patterns.len()
    ));
  }
  for ns in &bs.no_symlink {
    lines.push(format!("       - no-symlink {}", clean(&ns.path)));
  }
  for c in &bs.command {
    lines.push(format!("       - run    {} ({})", clean(&c.name), clean(&c.run)));
  }
  lines
}

// ---- Aliases commands (issue #86) ---------------------------------------

fn cmd_aliases(action: AliasesAction) -> Result<()> {
  match action {
    AliasesAction::List => cmd_aliases_list(),
  }
}

fn cmd_config(action: ConfigAction) -> Result<()> {
  match action {
    ConfigAction::Get { key } => config_cli::get(&key),
    ConfigAction::Set { key, value } => config_cli::set(&key, value.as_deref()),
    ConfigAction::Unset { key } => config_cli::unset(&key),
    ConfigAction::List { prefix } => config_cli::list(prefix.as_deref()),
    ConfigAction::Validate => config_cli::validate(),
    ConfigAction::Path => config_cli::path(),
    ConfigAction::Edit => config_cli::edit(),
  }
}

/// `gwm aliases list` — print the resolved alias chain. Reads
/// `.gwm.toml` from the current repo workdir when available (gracefully
/// degrades to "no repo" when invoked outside a git repo) and the
/// user-level fallback `~/.config/gwm/aliases.toml`.
///
/// Output shape (matches the issue example verbatim):
///
/// ```text
/// built-in:
///   s    → switch
///   cd   → path
/// repo (.gwm.toml):
///   wip    → create feat 0 wip
///   ll     → list --format names
/// user (~/.config/gwm/aliases.toml):
///   copy   → path
/// ```
fn cmd_aliases_list() -> Result<()> {
  // Discover the repo workdir if any — outside a repo this is `None`
  // and the repo section degrades to "(no .gwm.toml — not inside a
  // git repository)". `aliases list` is intentionally tolerant of
  // running outside a repo so power users can audit their user-level
  // file without cd'ing first.
  let repo_workdir: Option<PathBuf> = crate::worktree::discover_repo(None)
    .ok()
    .and_then(|r| r.workdir().map(|w| w.to_path_buf()));

  let resolved = crate::aliases::load(repo_workdir.as_deref(), None)?;

  // Issue #473: repo and user alias tables are arbitrary key/value text from
  // a `.gwm.toml` this command reads WITHOUT the trust gate: auditing an
  // unfamiliar repo's aliases before running anything is exactly what it is
  // for. Built-ins are compiled in and need no cleaning, but they share the
  // helper so a future built-in read from a file cannot slip through.
  let clean = crate::naming::sanitise_for_terminal;

  // built-in section ---------------------------------------------------
  println!("built-in:");
  if resolved.built_in.is_empty() {
    println!("  (none)");
  } else {
    let width = resolved.built_in.iter().map(|e| e.name.len()).max().unwrap_or(2).max(2);
    for e in &resolved.built_in {
      println!("  {:<width$} → {}", clean(e.name), clean(e.expansion), width = width);
    }
  }

  // repo section -------------------------------------------------------
  println!("repo (.gwm.toml):");
  if repo_workdir.is_none() {
    println!("  (not inside a git repository — repo aliases are read from <repo>/.gwm.toml)");
  } else if resolved.repo.is_empty() {
    println!("  (none declared)");
  } else {
    let width = resolved.repo.keys().map(|k| clean(k).len()).max().unwrap_or(2).max(2);
    for (name, expansion) in &resolved.repo {
      println!("  {:<width$} → {}", clean(name), clean(expansion), width = width);
    }
  }

  // user section -------------------------------------------------------
  // The display path mirrors the issue example. We don't call into
  // `default_user_path()` for the label because that function is
  // private to the `aliases` module; the rendered string is purely
  // informational here.
  println!("user (~/.config/gwm/aliases.toml):");
  if resolved.user.is_empty() {
    println!("  (none declared)");
  } else {
    let width = resolved.user.keys().map(|k| clean(k).len()).max().unwrap_or(2).max(2);
    for (name, expansion) in &resolved.user {
      // Mark entries shadowed by a repo declaration so the user can
      // see why a `gwm <name>` does not pick up the user expansion.
      // Shadowing is probed on the raw name, which is the identity the
      // resolver matches on, and two distinct names must not look shadowed
      // just because they neutralise to the same string.
      let shadowed = resolved.repo.contains_key(name);
      let suffix = if shadowed { "  (shadowed by repo)" } else { "" };
      println!(
        "  {:<width$} → {}{}",
        clean(name),
        clean(expansion),
        suffix,
        width = width
      );
    }
  }

  Ok(())
}

pub fn shell_init_script(shell: InitShell) -> &'static str {
  match shell {
    InitShell::Bash | InitShell::Zsh => POSIX_SHELL_INIT,
    InitShell::Fish => FISH_SHELL_INIT,
    InitShell::Powershell => POWERSHELL_SHELL_INIT,
  }
}

const POSIX_SHELL_INIT: &str = r#"# gwm shell helper — wraps `gwm cd` / `gwm switch` so the parent shell can cd.
# Install: eval "$(gwm shell-init bash)"   # or zsh
#
# Two paths:
#   gcd <pattern>        # fuzzy resolve via `gwm cd <pattern>`, then cd
#   gcd                  # no arg → opens the interactive picker via `gwm switch`, then cd
#
# Note: the `function name { ... }` form (zsh/bash-extended) is used instead
# of the parenthesised POSIX form so the parser does not error out with
# `defining function based on alias 'gcd'` when zsh already has a `gcd`
# alias (e.g. oh-my-zsh's `gcd=git checkout`). The `unalias` after the
# definition is what makes the function reachable at call time, since zsh
# still resolves the alias first when both exist.
function gcd {
  local target
  if [ "$#" -eq 0 ]; then
    # No arg → open the interactive picker. `gwm switch` exits non-zero on
    # cancel, in which case `gcd` must NOT attempt the `cd` (would land in $HOME).
    target="$(command gwm switch)" || return $?
  else
    target="$(command gwm cd "$@")" || return $?
  fi
  cd "$target" || return $?
}
unalias gcd 2>/dev/null || true
"#;

const FISH_SHELL_INIT: &str = r#"# gwm shell helper — wraps `gwm cd` / `gwm switch` so the parent shell can cd.
# Install: gwm shell-init fish | source   # then persist in ~/.config/fish/config.fish
#
# Two paths:
#   gcd <pattern>        # fuzzy resolve via `gwm cd <pattern>`, then cd
#   gcd                  # no arg → opens the interactive picker via `gwm switch`, then cd
function gcd --description 'cd into a gwm worktree (no arg = interactive picker)'
  set -l target
  if test (count $argv) -eq 0
    # No arg → open the interactive picker; cancel exits non-zero, in which
    # case we must NOT attempt the cd (would land in $HOME).
    set target (command gwm switch)
    or return $status
  else
    set target (command gwm cd $argv)
    or return $status
  end
  # `--` stops option parsing, "$target" prevents wildcard expansion on
  # paths containing `[`, `]`, or `*`.
  cd -- "$target"
end
"#;

const POWERSHELL_SHELL_INIT: &str = r#"# gwm shell helper — wraps `gwm cd` / `gwm switch` so the parent shell can cd.
# Install: Invoke-Expression (& gwm shell-init powershell | Out-String)
#
# Two paths:
#   gcd <pattern>        # fuzzy resolve via `gwm cd <pattern>`, then Set-Location
#   gcd                  # no arg → opens the interactive picker via `gwm switch`, then Set-Location
#
# Note: this clears any prior `gcd` alias so the function takes effect.
Remove-Alias -Name gcd -Force -ErrorAction SilentlyContinue
function gcd {
  param([string]$Pattern)
  if ([string]::IsNullOrEmpty($Pattern)) {
    # No arg → open the interactive picker. The binary exits non-zero on
    # cancel; bail out before attempting Set-Location so we don't land in $HOME.
    $target = & gwm switch
  } else {
    $target = & gwm cd $Pattern
  }
  if ($LASTEXITCODE -ne 0) { return }
  Set-Location $target
}
"#;

fn print_report(report: &bootstrap::BootstrapReport) {
  if report.steps.is_empty() {
    return;
  }
  println!();
  println!("bootstrap report:");
  for s in &report.steps {
    let sigil = s.status.sigil();
    println!("  {} {}", sigil, s.label);
    if !s.detail.is_empty() {
      for line in s.detail.lines() {
        println!("      {}", line);
      }
    }
  }
}

fn print_lifecycle_report(report: &bootstrap::BootstrapReport) {
  if report.steps.is_empty() {
    return;
  }
  lifecycle::print_report(report);
}

// ---------------------------------------------------------------------------
// Issue #29 — `gwm history` + `gwm undo`
// ---------------------------------------------------------------------------

/// Resolve the canonicalised main repo workdir for journal lookups.
/// `gwm undo` / `gwm history` filter on this path verbatim, so the
/// canonicalisation step matters: `/var` vs `/private/var` on macOS
/// would otherwise cross-pollute repos that happen to live on
/// different symlink chains.
fn current_repo_root() -> Result<PathBuf> {
  let repo = worktree::discover_repo(None)?;
  let workdir = repo.workdir().ok_or(GwmError::NotInGitRepo)?.to_path_buf();
  Ok(std::fs::canonicalize(&workdir).unwrap_or(workdir))
}

/// Render one journal entry as a single line for `gwm history`. Shape:
/// `<ago>  <kind>  <worktree>  [(undone)]`. Extracted as a pure
/// function so the formatter is unit-testable without spinning up a
/// real journal (see `cli_format_tests.rs`).
pub fn format_history_row(entry: &OpEntry, now: chrono::DateTime<chrono::Utc>) -> String {
  let delta = (now - entry.ts).to_std().unwrap_or(std::time::Duration::from_secs(0));
  let ago = worktree::format_relative_duration(delta);
  let suffix = if entry.undone { "  (undone)" } else { "" };
  format!("{:<5}  {:<7}  {}{}", ago, entry.kind.as_str(), entry.worktree, suffix)
}

fn cmd_history(limit: usize, all: bool) -> Result<()> {
  let path = history::default_journal_path()?;
  let journal = history::Journal::load(&path)?;

  // Build the filtered+sorted view. With `--all`, surface every entry
  // regardless of `repo_root`. Without it, restrict to the current
  // repo's canonicalised workdir. Resolving the root outside the
  // `if` so its lifetime spans the whole function — the `else` arm
  // returns an iterator that borrows from it.
  let root: Option<PathBuf> = if all { None } else { Some(current_repo_root()?) };
  let mut rows: Vec<&OpEntry> = match &root {
    Some(r) => journal.entries_for_repo(r).collect(),
    None => journal.entries().iter().collect(),
  };

  // Distinguish "the journal is empty for this view" from "the user
  // asked for zero rows" — `--limit 0` is an explicit no-op that
  // should print nothing and exit 0, not falsely claim the journal
  // is empty (PR #155 Copilot review).
  if rows.is_empty() {
    println!("no operations recorded");
    return Ok(());
  }
  if limit == 0 {
    return Ok(());
  }

  // Newest first — the user just ran an op, they expect it on top.
  rows.sort_by_key(|e| std::cmp::Reverse(e.ts));
  rows.truncate(limit);

  let now = chrono::Utc::now();
  for entry in rows {
    println!("{}", format_history_row(entry, now));
  }
  Ok(())
}

fn cmd_undo(run_bootstrap: bool, trust_mode: TrustMode) -> Result<()> {
  let path = history::default_journal_path()?;
  let mut journal = history::Journal::load(&path)?;
  let root = current_repo_root()?;

  let Some(entry) = journal.pop_last_for_repo(&root) else {
    return Err(GwmError::Other(format!(
      "nothing to undo for {} — the journal is empty for this repo",
      root.display()
    )));
  };

  let repo = worktree::discover_repo(None)?;

  // (0) Issue #338: if the caller opted into re-running bootstrap, gate
  //     it through the SAME TOFU trust prompt as create / review /
  //     bootstrap — a repo's `[[bootstrap.command]]` shell must never run
  //     unprompted on undo. Do it BEFORE any resurrection so a denied
  //     gate (untrusted config in a non-tty, `--deny-bootstrap`, or a
  //     declined prompt) leaves the journal entry and worktree untouched:
  //     the undo stays retryable instead of half-applying then exiting
  //     non-zero. Honours --allow-bootstrap / GWM_ALLOW_BOOTSTRAP /
  //     --deny-bootstrap.
  if run_bootstrap {
    let workdir = repo.workdir().ok_or(GwmError::NotInGitRepo)?.to_path_buf();
    trust_or_prompt(&workdir, Some(&repo), trust_mode)?;
  }

  // (1) Resurrect the branch at the saved OID — only if a branch was
  //     recorded AND the user opted into deletion (or the branch is
  //     missing for any other reason). Skipping the branch create
  //     when the ref already exists keeps `gwm undo` idempotent
  //     against partial recoveries.
  if let (Some(branch_name), Some(oid_hex)) = (&entry.branch, &entry.branch_oid) {
    let oid = git2::Oid::from_str(oid_hex)
      .map_err(|e| GwmError::Other(format!("journal entry has invalid branch_oid '{}': {}", oid_hex, e)))?;
    if repo.find_branch(branch_name, git2::BranchType::Local).is_err() {
      repo
        .reference(
          &format!("refs/heads/{}", branch_name),
          oid,
          false,
          "gwm undo: resurrect branch",
        )
        .map_err(|e| {
          GwmError::Other(format!(
            "failed to recreate branch {} at {}: {}",
            branch_name, oid_hex, e
          ))
        })?;
      println!(
        "✓ recreated branch {} at {}",
        branch_name,
        &oid_hex[..oid_hex.len().min(8)]
      );
    } else {
      println!("· branch {} already exists — skipping resurrection", branch_name);
    }
  }

  // (2) Re-add the worktree at the saved path. `worktree::add` refuses
  //     to clobber an existing directory, so a leftover dir from a
  //     half-failed remove will surface as an error here — the user
  //     can clean up manually before retrying undo.
  //
  //     `OpEntry.branch == None` flags a worktree that was checked out
  //     in detached-HEAD state. We don't support resurrecting those
  //     yet — the original sin is that `worktree::add` only knows how
  //     to attach a worktree to a named branch. Falling back to a
  //     literal `"HEAD"` (the pre-fix behaviour) would either fail at
  //     the libgit2 level (invalid refname) or create a real branch
  //     named "HEAD" which is a disaster all of its own. Surface a
  //     clear error so the user knows what's happening and can file
  //     a follow-up issue if detached-HEAD support matters to them
  //     (PR #155 Copilot review).
  let branch_name = entry.branch.as_deref().ok_or_else(|| {
    GwmError::Other(format!(
      "cannot undo remove of detached-HEAD worktree {} — only branch-attached worktrees are supported today",
      entry.worktree
    ))
  })?;
  // `reuse_branch: true` because the branch already exists (we just
  // created it above, or it was never deleted).
  worktree::add(&repo, &entry.worktree, &entry.path, branch_name, true)?;
  println!("✓ re-added worktree at {}", entry.path.display());

  // (3) Persist the journal AFTER the resurrection succeeds — if we
  //     dropped the entry first and then the resurrection failed, the
  //     user would lose the recovery anchor entirely.
  journal.save(&path)?;

  // (4) Optionally re-run bootstrap. Trust was already gated at step
  //     (0) before any resurrection, so by here we're cleared to run.
  if run_bootstrap {
    let workdir = repo.workdir().ok_or(GwmError::NotInGitRepo)?.to_path_buf();
    let config = Config::load_for_repo(&workdir)?;
    let ctx = BootstrapCtx {
      main_repo: &workdir,
      worktree: &entry.path,
      config: &config,
    };
    let report = bootstrap::run(&ctx)?;
    print_report(&report);
  } else {
    println!("(skipped re-bootstrap; pass --bootstrap to run it)");
  }

  Ok(())
}