worktrunk 0.42.0

A CLI for Git worktree management, designed for parallel AI agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
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
use crate::common::{
    DAY, HOUR, MINUTE, TestRepo, list_snapshots, make_snapshot_cmd,
    mock_commands::create_mock_llm_quickstart, repo, repo_with_remote,
    setup_snapshot_settings_for_paths, wt_command,
};
use insta_cmd::assert_cmd_snapshot;
use path_slash::PathExt as _;
use rstest::rstest;

/// Creates worktrees with specific timestamps for ordering tests.
/// Returns the path to feature-current (the worktree to run tests from).
///
/// Expected order: main (^), feature-current (@), then by timestamp descending:
/// feature-newest (03:00), feature-middle (02:00), feature-oldest (00:30)
fn setup_timestamped_worktrees(repo: &mut TestRepo) -> std::path::PathBuf {
    // Create main with earliest timestamp (00:00)
    repo.commit("Initial commit on main");

    // Helper to create a commit with a specific timestamp
    fn commit_at_time(
        repo: &TestRepo,
        path: &std::path::Path,
        filename: &str,
        time: &str,
        time_short: &str,
    ) {
        let file_path = path.join(filename);
        std::fs::write(
            &file_path,
            format!("{} content", filename.trim_end_matches(".txt")),
        )
        .unwrap();

        repo.git_command()
            .env("GIT_AUTHOR_DATE", time)
            .env("GIT_COMMITTER_DATE", time)
            .args(["add", "."])
            .current_dir(path)
            .run()
            .unwrap();

        repo.git_command()
            .env("GIT_AUTHOR_DATE", time)
            .env("GIT_COMMITTER_DATE", time)
            .args(["commit", "-m", &format!("Commit at {}", time_short)])
            .current_dir(path)
            .run()
            .unwrap();
    }

    // 1. Create feature-current (01:00) - we'll run test from here
    let current_path = repo.add_worktree("feature-current");
    commit_at_time(
        repo,
        &current_path,
        "current.txt",
        "2025-01-01T01:00:00Z",
        "01:00",
    );

    // 2. Create feature-newest (03:00) - most recent, should be 3rd
    let newest_path = repo.add_worktree("feature-newest");
    commit_at_time(
        repo,
        &newest_path,
        "newest.txt",
        "2025-01-01T03:00:00Z",
        "03:00",
    );

    // 3. Create feature-middle (02:00) - should be 4th
    let middle_path = repo.add_worktree("feature-middle");
    commit_at_time(
        repo,
        &middle_path,
        "middle.txt",
        "2025-01-01T02:00:00Z",
        "02:00",
    );

    // 4. Create feature-oldest (00:30) - should be 5th
    let oldest_path = repo.add_worktree("feature-oldest");
    commit_at_time(
        repo,
        &oldest_path,
        "oldest.txt",
        "2025-01-01T00:30:00Z",
        "00:30",
    );

    current_path
}

#[rstest]
fn test_list_single_worktree(repo: TestRepo) {
    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

#[rstest]
fn test_list_multiple_worktrees(mut repo: TestRepo) {
    repo.add_worktree("feature-a");
    repo.add_worktree("feature-b");

    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

///
/// Simulates realistic usage by running switch commands from the correct worktree directories.
#[rstest]
fn test_list_previous_worktree_gutter(mut repo: TestRepo) {
    repo.add_worktree("feature");

    let feature_path = repo.root_path().parent().unwrap().join(format!(
        "{}.feature",
        repo.root_path().file_name().unwrap().to_str().unwrap()
    ));

    // Step 1: From main, switch to feature (history: current=feature, previous=main)
    let mut cmd = wt_command();
    repo.configure_wt_cmd(&mut cmd);
    cmd.args(["switch", "feature"])
        .current_dir(repo.root_path());
    cmd.output().unwrap();

    // Step 2: From feature, switch back to main (history: current=main, previous=feature)
    let mut cmd = wt_command();
    repo.configure_wt_cmd(&mut cmd);
    cmd.args(["switch", "main"]).current_dir(&feature_path);
    cmd.output().unwrap();

    // List shows previous worktree with `+` (same as regular worktrees).
    // The previous worktree is the target of `wt switch -`.
    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

#[rstest]
fn test_list_detached_head(repo: TestRepo) {
    repo.detach_head();

    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

#[rstest]
fn test_list_detached_head_in_worktree(mut repo: TestRepo) {
    // Non-main worktree in detached HEAD SHOULD show path mismatch flag
    // (detached HEAD = "not at home", not on any branch)

    repo.add_worktree("feature");
    repo.detach_head_in_worktree("feature");

    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

#[rstest]
fn test_list_locked_worktree(mut repo: TestRepo) {
    repo.add_worktree("locked-feature");
    repo.lock_worktree("locked-feature", Some("Testing lock functionality"));

    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

#[rstest]
fn test_list_locked_no_reason(mut repo: TestRepo) {
    repo.add_worktree("locked-no-reason");
    repo.lock_worktree("locked-no-reason", None);

    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

// Removed: test_list_long_branch_name - covered by spacing_edge_cases.rs

#[rstest]
fn test_list_long_commit_message(mut repo: TestRepo) {
    // Create commit with very long message
    repo.commit("This is a very long commit message that should test how the message column handles truncation and word boundary detection in the list output");

    repo.add_worktree("feature-a");
    repo.commit("Short message");

    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

// Removed: test_list_unicode_branch_name - covered by spacing_edge_cases.rs

#[rstest]
fn test_list_unicode_commit_message(mut repo: TestRepo) {
    // Create commit with Unicode message
    repo.commit("Add support for 日本語 and émoji 🎉");

    repo.add_worktree("feature-test");
    repo.commit("Fix bug with café ☕ handling");

    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

#[rstest]
fn test_list_many_worktrees_with_varied_stats(mut repo: TestRepo) {
    // Create multiple worktrees with different characteristics
    repo.add_worktree("short");

    repo.add_worktree("medium-name");

    repo.add_worktree("very-long-branch-name-here");

    // Add some with files to create diff stats
    repo.add_worktree("with-changes");

    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

// Removed: test_list_json_single_worktree and test_list_json_multiple_worktrees
// Basic JSON serialization is covered by test_list_json_with_metadata

#[rstest]
fn test_list_json_with_metadata(mut repo: TestRepo) {
    // Create worktree with detached head
    repo.add_worktree("feature-detached");

    // Create locked worktree
    repo.add_worktree("locked-feature");
    repo.lock_worktree("locked-feature", Some("Testing"));

    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--format=json");
        cmd
    });
}

/// This tests the merge commit scenario where content matches main even with different commit history.
#[rstest]
fn test_list_json_tree_matches_main_after_merge(mut repo: TestRepo) {
    // Create feature branch with a worktree
    let feature_path = repo.add_worktree_with_commit(
        "feature-merged",
        "feature.txt",
        "feature content",
        "Feature commit",
    );

    // Make the same commit on main (so trees will match after merge)
    std::fs::write(repo.root_path().join("feature.txt"), "feature content").unwrap();
    repo.run_git(&["add", "."]);
    repo.run_git(&["commit", "-m", "Same content on main"]);

    // Merge main into feature (creates merge commit, but tree matches main)
    repo.run_git_in(
        &feature_path,
        &["merge", "main", "-m", "Merge main into feature"],
    );

    // Now feature-merged is ahead of main (has merge commit) but tree content matches main
    // JSON output should show branch_op_state: "TreesMatch" with ahead > 0
    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--format=json");
        cmd
    });
}

#[rstest]
fn test_list_with_branches_flag(mut repo: TestRepo) {
    // Create some branches without worktrees
    repo.create_branch("feature-without-worktree");
    repo.create_branch("another-branch");
    repo.create_branch("fix-bug");

    // Create one branch with a worktree
    repo.add_worktree("feature-with-worktree");

    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--branches");
        cmd
    });
}

#[rstest]
fn test_list_with_branches_flag_no_available(mut repo: TestRepo) {
    // All branches have worktrees (only main exists and has worktree)
    repo.add_worktree("feature-a");
    repo.add_worktree("feature-b");

    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--branches");
        cmd
    });
}

#[rstest]
fn test_list_with_branches_flag_only_branches(repo: TestRepo) {
    // Create several branches without worktrees
    repo.create_branch("branch-alpha");
    repo.create_branch("branch-beta");
    repo.create_branch("branch-gamma");

    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--branches");
        cmd
    });
}

#[rstest]
fn test_list_with_remotes_flag(#[from(repo_with_remote)] repo: TestRepo) {
    // Create feature branches in the main repo and push them
    repo.create_branch("remote-feature-1");
    repo.create_branch("remote-feature-2");
    repo.push_branch("remote-feature-1");
    repo.push_branch("remote-feature-2");

    // Delete the local branches - now they only exist as origin/remote-feature-*
    repo.run_git(&["branch", "-D", "remote-feature-1", "remote-feature-2"]);

    // Should show:
    // - main worktree (primary)
    // - origin/remote-feature-1 (remote branch without local worktree)
    // - origin/remote-feature-2 (remote branch without local worktree)
    // Should NOT show origin/main (main has a worktree)
    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--remotes");
        cmd
    });
}

#[rstest]
fn test_list_with_remotes_and_branches(#[from(repo_with_remote)] repo: TestRepo) {
    // Create local-only branches (not worktrees, not pushed)
    repo.create_branch("local-only-1");
    repo.create_branch("local-only-2");

    // Create branches, push them, then delete locally to make them remote-only
    repo.create_branch("remote-only-1");
    repo.create_branch("remote-only-2");
    repo.push_branch("remote-only-1");
    repo.push_branch("remote-only-2");
    repo.run_git(&["branch", "-D", "remote-only-1", "remote-only-2"]);

    // Should show:
    // - main worktree
    // - local-only-1 branch (local, no worktree)
    // - local-only-2 branch (local, no worktree)
    // - origin/remote-only-1 (remote, no local)
    // - origin/remote-only-2 (remote, no local)
    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.args(["--branches", "--remotes"]);
        cmd
    });
}

#[rstest]
fn test_list_with_remotes_filters_tracked_worktrees(#[from(repo_with_remote)] mut repo: TestRepo) {
    // Create a worktree and push with tracking
    repo.add_worktree("feature-with-worktree");
    let feature_path = repo.worktree_path("feature-with-worktree");
    repo.run_git_in(
        feature_path,
        &["push", "-u", "origin", "feature-with-worktree"],
    );

    // Create a branch, push it, delete it locally (remote-only)
    repo.create_branch("remote-only");
    repo.push_branch("remote-only");
    repo.run_git(&["branch", "-D", "remote-only"]);

    // Should show:
    // - main worktree
    // - feature-with-worktree worktree
    // - origin/remote-only (remote branch not tracked by any local branch)
    // Should NOT show origin/main or origin/feature-with-worktree (both tracked)
    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--remotes");
        cmd
    });
}

#[rstest]
fn test_list_with_remotes_filters_tracked_branches(#[from(repo_with_remote)] repo: TestRepo) {
    // Create a local branch (no worktree) and push with tracking
    repo.create_branch("tracked-branch");
    repo.run_git(&["push", "-u", "origin", "tracked-branch"]);

    // Create a branch, push it, then delete locally (remote-only)
    repo.create_branch("remote-only");
    repo.push_branch("remote-only");
    repo.run_git(&["branch", "-D", "remote-only"]);

    // Should show:
    // - main worktree
    // - origin/remote-only (remote branch not tracked by any local branch)
    // Should NOT show origin/main (tracked by main + has worktree)
    // Should NOT show origin/tracked-branch (tracked by local tracked-branch)
    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--remotes");
        cmd
    });
}

#[rstest]
fn test_list_with_remotes_and_full(#[from(repo_with_remote)] repo: TestRepo) {
    // Create remote-only branches (no local tracking)
    repo.create_branch("feature-remote");
    repo.push_branch("feature-remote");
    repo.run_git(&["branch", "-D", "feature-remote"]);

    // Set a GitHub-style URL AFTER pushing so platform detection works
    // This exercises the remote_hint path in platform_for_repo
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/owner/test-repo.git",
    ]);

    // Run with --full to trigger CiBranchName::from_branch_ref for remote branches
    // This exercises the is_remote=true code path even without gh/glab auth
    // (CI detection will return None, but the branch parsing is still covered)
    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.args(["--remotes", "--full"]);
        cmd
    });
}

#[rstest]
fn test_list_with_orphaned_remote_ref(#[from(repo_with_remote)] repo: TestRepo) {
    // Create a remote-tracking ref for a non-existent remote.
    // This simulates a ref that remains after a remote is deleted.
    let head_sha = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .run()
        .unwrap()
        .stdout;
    let head_sha = String::from_utf8_lossy(&head_sha);
    let head_sha = head_sha.trim();
    repo.run_git(&[
        "update-ref",
        "refs/remotes/deleted-remote/orphaned-branch",
        head_sha,
    ]);

    // Verify the ref exists but the remote doesn't
    let remotes = repo.git_command().args(["remote"]).run().unwrap().stdout;
    let remotes = String::from_utf8_lossy(&remotes);
    assert!(
        !remotes.contains("deleted-remote"),
        "deleted-remote should not exist"
    );

    // The orphaned ref should still appear — split_once('/') parses it correctly
    // even though the remote no longer exists.
    let output = repo
        .wt_command()
        .args(["list", "--remotes", "--full"])
        .output()
        .unwrap();
    assert!(output.status.success(), "command should succeed");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("deleted-remote/orphaned-branch"),
        "should show orphaned remote branch in output: {stdout}"
    );
}

#[rstest]
fn test_list_json_with_display_fields(mut repo: TestRepo) {
    repo.commit("Initial commit on main");

    // Create feature branch with commits (ahead of main)
    repo.add_worktree("feature-ahead");

    // Make commits in the feature worktree
    let feature_path = repo.worktree_path("feature-ahead");
    std::fs::write(feature_path.join("feature.txt"), "feature content").unwrap();
    repo.run_git_in(feature_path, &["add", "."]);
    repo.run_git_in(feature_path, &["commit", "-m", "Feature commit 1"]);
    repo.run_git_in(
        feature_path,
        &["commit", "--allow-empty", "-m", "Feature commit 2"],
    );

    // Add uncommitted changes to show working_diff_display
    std::fs::write(feature_path.join("uncommitted.txt"), "uncommitted").unwrap();
    std::fs::write(feature_path.join("feature.txt"), "modified content").unwrap();

    // Create another feature that will be behind after main advances
    repo.add_worktree("feature-behind");

    // Make more commits on main (so feature-behind is behind)
    repo.commit("Main commit 1");
    repo.commit("Main commit 2");

    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--format=json");
        cmd
    });
}

#[rstest]
fn test_list_ordering_rules(mut repo: TestRepo) {
    let current_path = setup_timestamped_worktrees(&mut repo);

    // Run from feature-current worktree to test "current worktree" logic
    assert_cmd_snapshot!(list_snapshots::command(&repo, &current_path));
}

#[rstest]
fn test_list_with_upstream_tracking(mut repo: TestRepo) {
    repo.commit("Initial commit on main");

    // Set up remote - this already pushes main
    repo.setup_remote("main");

    // Scenario 1: Branch in sync with remote (should show ↑0 ↓0)
    let in_sync_wt = repo.add_worktree("in-sync");
    repo.run_git_in(&in_sync_wt, &["push", "-u", "origin", "in-sync"]);

    // Scenario 2: Branch ahead of remote (should show ↑2)
    let ahead_wt = repo.add_worktree("ahead");
    repo.run_git_in(&ahead_wt, &["push", "-u", "origin", "ahead"]);

    // Make 2 commits ahead
    std::fs::write(ahead_wt.join("ahead1.txt"), "ahead 1").unwrap();
    repo.run_git_in(&ahead_wt, &["add", "."]);
    repo.run_git_in(&ahead_wt, &["commit", "-m", "Ahead commit 1"]);

    std::fs::write(ahead_wt.join("ahead2.txt"), "ahead 2").unwrap();
    repo.run_git_in(&ahead_wt, &["add", "."]);
    repo.run_git_in(&ahead_wt, &["commit", "-m", "Ahead commit 2"]);

    // Scenario 3: Branch behind remote (should show ↓1)
    let behind_wt = repo.add_worktree("behind");
    std::fs::write(behind_wt.join("behind.txt"), "behind").unwrap();
    repo.run_git_in(&behind_wt, &["add", "."]);
    repo.run_git_in(&behind_wt, &["commit", "-m", "Behind commit"]);
    repo.run_git_in(&behind_wt, &["push", "-u", "origin", "behind"]);
    // Reset local to one commit behind
    repo.run_git_in(&behind_wt, &["reset", "--hard", "HEAD~1"]);

    // Scenario 4: Branch both ahead and behind (should show ↑1 ↓1)
    let diverged_wt = repo.add_worktree("diverged");
    std::fs::write(diverged_wt.join("diverged.txt"), "diverged").unwrap();
    repo.run_git_in(&diverged_wt, &["add", "."]);
    repo.run_git_in(&diverged_wt, &["commit", "-m", "Diverged remote commit"]);
    repo.run_git_in(&diverged_wt, &["push", "-u", "origin", "diverged"]);
    // Reset and make different commit
    repo.run_git_in(&diverged_wt, &["reset", "--hard", "HEAD~1"]);
    std::fs::write(diverged_wt.join("different.txt"), "different").unwrap();
    repo.run_git_in(&diverged_wt, &["add", "."]);
    repo.run_git_in(&diverged_wt, &["commit", "-m", "Diverged local commit"]);

    // Scenario 5: Branch without upstream (should show blank)
    let no_upstream_wt = repo.add_worktree("no-upstream");

    // Run git status to ensure the worktree is fully initialized on Windows.
    // Without this, Windows CI may show 55y (Unix epoch) because the worktree
    // isn't ready when wt list tries to read commit timestamps.
    repo.run_git_in(&no_upstream_wt, &["status", "--porcelain"]);

    // Scenario 6: Upstream configured but remote ref deleted (git's [gone] state).
    // Should be treated as no upstream — blank Remote column, no error.
    let gone_wt = repo.add_worktree("gone-upstream");
    repo.run_git_in(&gone_wt, &["push", "-u", "origin", "gone-upstream"]);
    repo.run_git(&["push", "origin", "--delete", "gone-upstream"]);
    repo.run_git_in(&gone_wt, &["fetch", "--prune", "origin"]);

    // Run list --branches --full to show all columns including Remote
    assert_cmd_snapshot!("with_upstream_tracking", {
        let mut cmd = wt_command();
        repo.configure_wt_cmd(&mut cmd);
        repo.configure_mock_commands(&mut cmd);
        cmd.arg("list")
            .arg("--branches")
            .arg("--full")
            .current_dir(repo.root_path());
        cmd
    });
}

#[rstest]
fn test_list_primary_on_different_branch(mut repo: TestRepo) {
    repo.switch_primary_to("develop");
    assert_eq!(repo.current_branch(), "develop");

    repo.add_worktree("feature-a");
    repo.add_worktree("feature-b");

    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

/// NOTE: This test is used for doc generation (claude-code.md). It removes fixture
/// worktrees to produce clean output.
/// TODO: Consider extracting fixture cleanup into a helper function shared with
/// setup_readme_example_repo.
#[rstest]
fn test_list_with_user_marker(mut repo: TestRepo) {
    // Remove fixture worktrees for clean doc output (used by claude-code.md)
    for branch in &["feature-a", "feature-b", "feature-c"] {
        let worktree_path = repo
            .root_path()
            .parent()
            .unwrap()
            .join(format!("repo.{}", branch));
        if worktree_path.exists() {
            let _ = repo
                .git_command()
                .args([
                    "worktree",
                    "remove",
                    "--force",
                    worktree_path.to_str().unwrap(),
                ])
                .run();
        }
        // Delete the branch after removing the worktree
        let _ = repo.git_command().args(["branch", "-D", branch]).run();
    }

    repo.commit_with_age("Initial commit", DAY);

    // Branch ahead of main with commits and user marker 🤖
    let _feature_wt = repo.add_worktree_with_commit(
        "feature-api",
        "api.rs",
        "// API implementation",
        "Add REST API endpoints",
    );
    // Set user marker
    repo.set_marker("feature-api", "🤖");

    // Branch with uncommitted changes and user marker 💬
    let review_wt = repo.add_worktree_with_commit(
        "review-ui",
        "component.tsx",
        "// UI component",
        "Add dashboard component",
    );
    // Add uncommitted changes
    std::fs::write(review_wt.join("styles.css"), "/* pending styles */").unwrap();
    // Set user marker
    repo.set_marker("review-ui", "💬");

    // Branch with uncommitted changes only (no user marker)
    let wip_wt = repo.add_worktree("wip-docs");
    std::fs::write(wip_wt.join("README.md"), "# Documentation").unwrap();

    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

#[rstest]
fn test_list_json_with_user_marker(mut repo: TestRepo) {
    repo.commit_with_age("Initial commit", DAY);

    // Worktree with user marker (emoji only)
    repo.add_worktree("with-status");

    // Set user marker (branch-keyed)
    repo.set_marker("with-status", "🔧");

    // Worktree without user marker
    repo.add_worktree("without-status");

    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--format=json");
        cmd
    });
}

#[rstest]
fn test_list_json_with_git_operation(mut repo: TestRepo) {
    // Test JSON output includes git_operation field when worktree is in rebase state

    // Create initial commit with a file that will conflict
    std::fs::write(
        repo.root_path().join("conflict.txt"),
        "original line 1\noriginal line 2\n",
    )
    .unwrap();
    repo.commit("Initial commit");

    // Create feature worktree
    let feature = repo.add_worktree_with_commit(
        "feature",
        "conflict.txt",
        "feature line 1\nfeature line 2\n",
        "Feature changes",
    );

    // Main makes conflicting changes
    std::fs::write(
        repo.root_path().join("conflict.txt"),
        "main line 1\nmain line 2\n",
    )
    .unwrap();
    repo.run_git(&["add", "."]);
    repo.run_git(&["commit", "-m", "Main conflicting changes"]);

    // Start rebase which will create conflicts and git operation state
    let rebase_output = repo
        .git_command()
        .current_dir(&feature)
        .args(["rebase", "main"])
        .run()
        .unwrap();

    // Rebase should fail with conflicts - verify we're in rebase state
    assert!(
        !rebase_output.status.success(),
        "Rebase should fail with conflicts"
    );

    // JSON output should show git_operation: "rebase" for the feature worktree
    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--format=json");
        cmd
    });
}

#[rstest]
fn test_list_branch_only_with_status(repo: TestRepo) {
    // Test that branch-only entries (no worktree) can display branch-keyed status

    // Create a branch-only entry (no worktree)
    repo.run_git(&["branch", "branch-only"]);

    // Set branch-keyed status for the branch-only entry
    repo.set_marker("branch-only", "🌿");

    // Use --branches flag to show branch-only entries
    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--branches");
        cmd
    });
}

#[rstest]
fn test_list_user_marker_with_special_characters(mut repo: TestRepo) {
    // Test with single emoji
    repo.add_worktree("emoji");
    repo.set_marker("emoji", "🔄");

    // Test with compound emoji (multi-codepoint)
    repo.add_worktree("multi");
    repo.set_marker("multi", "👨‍💻");

    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

// =============================================================================
// Quick Start Examples
// =============================================================================
//
// These functions create minimal repos for Quick Start documentation.
// The examples show the simplest workflow: create → list → merge.

/// Remove fixture worktrees to start with a clean main-only repo.
///
/// The standard TestRepo fixture includes feature-a, feature-b, feature-c.
/// Doc examples need clean output without these.
fn remove_fixture_worktrees(repo: &mut TestRepo) {
    for branch in &["feature-a", "feature-b", "feature-c"] {
        let worktree_path = repo
            .root_path()
            .parent()
            .unwrap()
            .join(format!("repo.{}", branch));
        if worktree_path.exists() {
            let _ = repo
                .git_command()
                .args([
                    "worktree",
                    "remove",
                    "--force",
                    worktree_path.to_str().unwrap(),
                ])
                .run();
        }
        let _ = repo.git_command().args(["branch", "-D", branch]).run();
    }
}

/// Set up a minimal repo with just main branch.
///
/// Creates a simple codebase:
/// - README.md with project description
/// - lib.rs with a simple function
/// - Remote configured and pushed
///
/// Used as base for both Quick Start and full README examples.
fn setup_quickstart_base(repo: &mut TestRepo) {
    remove_fixture_worktrees(repo);

    // Suppress the "customize worktree locations" hint for clean snapshots
    repo.run_git(&["config", "worktrunk.hints.worktree-path", "true"]);

    // Simple README
    std::fs::write(
        repo.root_path().join("README.md"),
        "# My Project\n\nA Rust application.\n",
    )
    .unwrap();

    // Simple lib.rs
    std::fs::write(
        repo.root_path().join("lib.rs"),
        r#"/// Adds two numbers.
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

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

    #[test]
    fn test_add() {
        assert_eq!(add(2, 3), 5);
    }
}
"#,
    )
    .unwrap();

    repo.run_git(&["add", "README.md", "lib.rs"]);
    repo.commit_staged_with_age("Initial commit", DAY, repo.root_path());
    repo.setup_remote("main");
}

/// Set up a Quick Start example repo with main + feature-auth.
///
/// Creates a scenario with a committed feature branch plus staged WIP:
/// - main: Initial codebase (1 commit behind remote)
/// - feature-auth: 1 commit ahead of main + staged WIP changes (adds + removes)
///
/// The staged WIP extends auth.rs and restructures lib.rs, producing both
/// additions and deletions in HEAD± to showcase more of `wt list`.
///
/// Returns the feature-auth worktree path.
fn setup_quickstart_repo(repo: &mut TestRepo) -> std::path::PathBuf {
    setup_quickstart_base(repo);

    // Create feature-auth worktree
    let feature_auth = repo.add_worktree("feature-auth");

    // === Commit: Add authentication module (1 commit ahead of main) ===
    std::fs::write(
        feature_auth.join("auth.rs"),
        r#"//! Authentication module for user session management.

use std::time::{Duration, SystemTime};

/// A user session with token and expiry.
pub struct Session {
    token: String,
    expires_at: SystemTime,
}

impl Session {
    /// Creates a new session with the given token and TTL.
    pub fn new(token: String, ttl: Duration) -> Self {
        Self {
            token,
            expires_at: SystemTime::now() + ttl,
        }
    }

    /// Returns true if the session has not expired.
    pub fn is_valid(&self) -> bool {
        SystemTime::now() < self.expires_at
    }

    /// Validates the token format.
    pub fn validate_token(token: &str) -> bool {
        token.len() >= 32 && token.chars().all(|c| c.is_ascii_alphanumeric())
    }
}
"#,
    )
    .unwrap();

    let lib_content = std::fs::read_to_string(feature_auth.join("lib.rs")).unwrap();
    std::fs::write(
        feature_auth.join("lib.rs"),
        format!("mod auth;\n\n{}", lib_content),
    )
    .unwrap();

    repo.run_git_in(&feature_auth, &["add", "auth.rs", "lib.rs"]);
    repo.commit_staged_with_age("Add authentication module", 2 * HOUR, &feature_auth);

    // === Staged WIP: extend auth + restructure lib (produces both +N and -N in HEAD±) ===

    // Extend auth.rs with is_authenticated and tests
    std::fs::write(
        feature_auth.join("auth.rs"),
        r#"//! Authentication module for user session management.

use std::time::{Duration, SystemTime};

/// A user session with token and expiry.
pub struct Session {
    token: String,
    expires_at: SystemTime,
}

impl Session {
    /// Creates a new session with the given token and TTL.
    pub fn new(token: String, ttl: Duration) -> Self {
        Self {
            token,
            expires_at: SystemTime::now() + ttl,
        }
    }

    /// Returns true if the session has not expired.
    pub fn is_valid(&self) -> bool {
        SystemTime::now() < self.expires_at
    }

    /// Validates the token format.
    pub fn validate_token(token: &str) -> bool {
        token.len() >= 32 && token.chars().all(|c| c.is_ascii_alphanumeric())
    }
}

/// Checks if user is authenticated with a valid session.
pub fn is_authenticated(session: Option<&Session>) -> bool {
    session.map(|s| s.is_valid()).unwrap_or(false)
}

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

    #[test]
    fn test_session_validity() {
        let session = Session::new("a".repeat(32), Duration::from_secs(3600));
        assert!(session.is_valid());
    }

    #[test]
    fn test_validate_token() {
        assert!(!Session::validate_token("short"));
        assert!(Session::validate_token(&"x".repeat(32)));
    }
}
"#,
    )
    .unwrap();

    // Restructure lib.rs: remove test module, add pub use + init
    std::fs::write(
        feature_auth.join("lib.rs"),
        r#"mod auth;

pub use auth::Session;

/// Adds two numbers.
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

/// Initializes the application with default settings.
pub fn init() -> bool {
    true
}
"#,
    )
    .unwrap();

    repo.run_git_in(&feature_auth, &["add", "auth.rs", "lib.rs"]);

    feature_auth
}

// =============================================================================
// Full README Examples
// =============================================================================

/// Set up a repo for README examples showing realistic worktree states.
///
/// **Project context**: API modernization — migrating from legacy handlers to REST,
/// hardening auth before v2 launch.
///
/// ## Branch Narratives
///
/// **`@ feature-api`** — REST migration in progress
///   Midway through migrating from function-based handlers to a REST module.
///   Staged the new controller base class; still removing the legacy dispatcher.
///   Three commits ready to push once local tests pass.
///   - `+234 -24` main…± — Major refactoring: new Router, handlers, middleware (~250 LOC)
///   - `+` staged, `↑⇡` ahead of main and remote, `⇡3` unpushed commits
///
/// **`^ main`**
///   Teammate merged the auth hotfix while you were refactoring.
///   Need to pull and rebase feature-api before continuing.
///   - `⇣1` behind remote
///
/// **`+ fix-auth`** — Token validation hardening
///   Replaced manual token parsing with constant-time comparison and added rate limiting.
///   Pushed and CI green — waiting on security review before merge.
///   - `+25 -11` main…± — Deleted insecure validation, added proper checks
///   - `|` in sync with remote, ready for merge
///
/// **`exp`** — GraphQL spike
///   Spike branch exploring GraphQL for the subscription API. Added schema definitions
///   and proof-of-concept resolvers with Query, Mutation, and Subscription roots.
///   - `+137` main…± — Schema types, resolvers, pagination (~140 LOC)
///   - `⎇` branch without worktree
///
/// **`wip`** — REST docs (stale)
///   Started API docs last week but got pulled away. Main has since moved on
///   (fix-auth was merged). Needs rebase before continuing.
///   - `↓1` behind main — main advanced while branch was idle
///   - `+33` main…± — Doc skeleton with structure
///   - `⎇` branch without worktree
///
/// Returns feature_api_path for running commands from feature-api.
///
/// NOTE: This function is used for doc generation. It removes fixture worktrees
/// to produce clean output for README/docs. If you need the fixture worktrees,
/// use a different setup function.
fn setup_readme_example_repo(repo: &mut TestRepo) -> std::path::PathBuf {
    // Start with clean base (removes fixture worktrees)
    remove_fixture_worktrees(repo);

    // === Set up main branch with initial codebase ===
    // Main has a working API with security issues that fix-auth will harden
    std::fs::write(
        repo.root_path().join("api.rs"),
        r#"//! API module - initial implementation
pub mod auth {
    // INSECURE: Manual string comparison vulnerable to timing attacks
    pub fn check_token(token: &str) -> bool {
        if token.is_empty() { return false; }
        // Just check format, no real validation
        token.len() > 0 && token.starts_with("tk_")
    }

    // INSECURE: No rate limiting, no audit logging
    pub fn validate_request(token: &str) -> bool {
        check_token(token)
    }

    // INSECURE: Tokens stored in plain text
    pub fn store_token(user_id: u32, token: &str) {
        std::fs::write(format!("/tmp/tokens/{}", user_id), token).ok();
    }
}

pub mod handlers {
    pub fn health() -> &'static str { "ok" }
    // Legacy endpoint - needs refactoring
    pub fn get_user(id: u32) -> String { format!("user:{}", id) }
    pub fn get_post(id: u32) -> String { format!("post:{}", id) }
}
"#,
    )
    .unwrap();
    repo.run_git(&["add", "api.rs"]);
    repo.commit_staged_with_age("Initial API implementation", DAY, repo.root_path());
    repo.setup_remote("main");

    // Make main behind its remote: push a teammate's commit, then reset local
    // Story: A teammate pushed a hotfix while we were working on features
    repo.commit_with_age("Fix production timeout issue", 2 * HOUR);
    repo.run_git(&["push", "origin", "main"]);
    repo.run_git(&["reset", "--hard", "HEAD~1"]);

    // === Create fix-auth worktree ===
    // Story: Security audit found the token validation was too weak.
    // This branch fixes it by replacing the permissive check with proper validation.
    let fix_auth = repo.add_worktree("fix-auth");

    // First commit: Replace weak validation with constant-time comparison
    std::fs::write(
        fix_auth.join("api.rs"),
        r#"//! API module - auth hardened
pub mod auth {
    use constant_time_eq::constant_time_eq;

    /// Validates token with constant-time comparison (timing attack resistant)
    pub fn check_token(token: &str) -> bool {
        if token.len() < 32 { return false; }
        if !token.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { return false; }
        let prefix = token.as_bytes().get(..3).unwrap_or(&[]);
        constant_time_eq(prefix, b"tk_")
    }

    /// Rate-limited request validation with audit logging
    pub fn validate_request(token: &str, client_ip: &str) -> Result<(), AuthError> {
        if is_rate_limited(client_ip) {
            log_auth_attempt(client_ip, "rate_limited");
            return Err(AuthError::RateLimited);
        }
        if !check_token(token) {
            log_auth_attempt(client_ip, "invalid_token");
            return Err(AuthError::InvalidToken);
        }
        Ok(())
    }
}

pub mod handlers {
    pub fn health() -> &'static str { "ok" }
    // Legacy endpoint - needs refactoring
    pub fn get_user(id: u32) -> String { format!("user:{}", id) }
    pub fn get_post(id: u32) -> String { format!("post:{}", id) }
}
"#,
    )
    .unwrap();
    repo.run_git_in(&fix_auth, &["add", "api.rs"]);
    repo.commit_staged_with_age("Harden token validation", 6 * HOUR, &fix_auth);

    // Second commit: Add secure token storage
    std::fs::write(
        fix_auth.join("api.rs"),
        r#"//! API module - auth hardened
pub mod auth {
    use constant_time_eq::constant_time_eq;

    /// Validates token with constant-time comparison (timing attack resistant)
    pub fn check_token(token: &str) -> bool {
        if token.len() < 32 { return false; }
        if !token.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { return false; }
        let prefix = token.as_bytes().get(..3).unwrap_or(&[]);
        constant_time_eq(prefix, b"tk_")
    }

    /// Rate-limited request validation with audit logging
    pub fn validate_request(token: &str, client_ip: &str) -> Result<(), AuthError> {
        if is_rate_limited(client_ip) {
            log_auth_attempt(client_ip, "rate_limited");
            return Err(AuthError::RateLimited);
        }
        if !check_token(token) {
            log_auth_attempt(client_ip, "invalid_token");
            return Err(AuthError::InvalidToken);
        }
        Ok(())
    }

    /// Stores token hash with per-user salt (never stores plaintext)
    pub fn store_token(user_id: u32, token: &str) -> Result<(), AuthError> {
        let salt = generate_salt(user_id);
        let hash = argon2_hash(token, &salt);
        db::tokens().insert(user_id, hash)?;
        Ok(())
    }
}

pub mod handlers {
    pub fn health() -> &'static str { "ok" }
    // Legacy endpoint - needs refactoring
    pub fn get_user(id: u32) -> String { format!("user:{}", id) }
    pub fn get_post(id: u32) -> String { format!("post:{}", id) }
}
"#,
    )
    .unwrap();
    repo.run_git_in(&fix_auth, &["add", "api.rs"]);
    repo.commit_staged_with_age("Add secure token storage", 5 * HOUR, &fix_auth);

    // Push fix-auth and sync with remote
    repo.run_git_in(&fix_auth, &["push", "-u", "origin", "fix-auth"]);

    // === Create feature-api worktree ===
    // Story: Major API refactoring - replacing the legacy handlers with a proper
    // REST structure. This involves deleting the old inline handlers and building
    // a modular system with middleware, validation, and caching.
    let feature_api = repo.add_worktree("feature-api");

    // First commit: Refactor api.rs - remove legacy handlers, add module structure
    // This replaces main's monolithic api.rs with a cleaner module layout
    std::fs::write(
        feature_api.join("api.rs"),
        r#"//! API module - refactored for REST architecture
//!
//! This module provides the public interface for the REST API.
//! All handlers have been moved to dedicated route modules.

pub mod routes;
pub mod middleware;
pub mod errors;

// Re-export commonly used types
pub use routes::{Router, Route, Handler};
pub use middleware::{RequestContext, ResponseBuilder};
pub use errors::{ApiError, ApiResult};
"#,
    )
    .unwrap();
    std::fs::write(
        feature_api.join("routes.rs"),
        r#"//! REST route definitions and handler implementations
use crate::middleware::{RequestContext, ResponseBuilder};
use crate::errors::{ApiError, ApiResult};

pub struct Router {
    routes: Vec<Route>,
}

pub struct Route {
    method: Method,
    path: String,
    handler: Box<dyn Handler>,
}

pub trait Handler: Send + Sync {
    fn handle(&self, ctx: &RequestContext) -> ApiResult<ResponseBuilder>;
}

impl Router {
    pub fn new() -> Self {
        Self { routes: Vec::new() }
    }

    pub fn get<H: Handler + 'static>(&mut self, path: &str, handler: H) -> &mut Self {
        self.routes.push(Route {
            method: Method::Get,
            path: path.to_string(),
            handler: Box::new(handler),
        });
        self
    }

    pub fn post<H: Handler + 'static>(&mut self, path: &str, handler: H) -> &mut Self {
        self.routes.push(Route {
            method: Method::Post,
            path: path.to_string(),
            handler: Box::new(handler),
        });
        self
    }

    pub fn route(&self, method: Method, path: &str) -> Option<&dyn Handler> {
        self.routes.iter()
            .find(|r| r.method == method && r.path == path)
            .map(|r| r.handler.as_ref())
    }
}

// Health check endpoint
pub struct HealthHandler;
impl Handler for HealthHandler {
    fn handle(&self, _ctx: &RequestContext) -> ApiResult<ResponseBuilder> {
        Ok(ResponseBuilder::new().status(200).body("ok"))
    }
}

// User endpoints
pub struct GetUserHandler;
impl Handler for GetUserHandler {
    fn handle(&self, ctx: &RequestContext) -> ApiResult<ResponseBuilder> {
        let user_id = ctx.param("id").ok_or(ApiError::BadRequest)?;
        // Fetch user from database
        Ok(ResponseBuilder::new().status(200).json(&user_id))
    }
}

pub struct ListUsersHandler;
impl Handler for ListUsersHandler {
    fn handle(&self, ctx: &RequestContext) -> ApiResult<ResponseBuilder> {
        let limit = ctx.query("limit").unwrap_or(20);
        let offset = ctx.query("offset").unwrap_or(0);
        // Paginated user list
        Ok(ResponseBuilder::new().status(200).json(&(limit, offset)))
    }
}

// Post endpoints
pub struct GetPostHandler;
impl Handler for GetPostHandler {
    fn handle(&self, ctx: &RequestContext) -> ApiResult<ResponseBuilder> {
        let post_id = ctx.param("id").ok_or(ApiError::BadRequest)?;
        Ok(ResponseBuilder::new().status(200).json(&post_id))
    }
}

pub struct CreatePostHandler;
impl Handler for CreatePostHandler {
    fn handle(&self, ctx: &RequestContext) -> ApiResult<ResponseBuilder> {
        let body = ctx.body().ok_or(ApiError::BadRequest)?;
        // Validate and create post
        Ok(ResponseBuilder::new().status(201).json(&body))
    }
}

#[derive(Clone, Copy, PartialEq)]
pub enum Method { Get, Post, Put, Delete }
"#,
    )
    .unwrap();
    repo.run_git_in(&feature_api, &["add", "api.rs", "routes.rs"]);
    repo.commit_staged_with_age("Refactor API to REST modules", 4 * HOUR, &feature_api);
    repo.run_git_in(&feature_api, &["push", "-u", "origin", "feature-api"]);

    // More commits (ahead of remote - unpushed local work)
    std::fs::write(
        feature_api.join("middleware.rs"),
        r#"//! Middleware stack for request processing
use std::time::Instant;
use std::collections::HashMap;

/// Context passed through the middleware chain
pub struct RequestContext {
    pub user_id: Option<u32>,
    pub started_at: Instant,
    pub headers: HashMap<String, String>,
    pub params: HashMap<String, String>,
    pub query: HashMap<String, String>,
    body: Option<Vec<u8>>,
}

impl RequestContext {
    pub fn new() -> Self {
        Self {
            user_id: None,
            started_at: Instant::now(),
            headers: HashMap::new(),
            params: HashMap::new(),
            query: HashMap::new(),
            body: None,
        }
    }

    pub fn param(&self, key: &str) -> Option<&str> {
        self.params.get(key).map(|s| s.as_str())
    }

    pub fn query<T: std::str::FromStr>(&self, key: &str) -> Option<T> {
        self.query.get(key).and_then(|s| s.parse().ok())
    }

    pub fn body(&self) -> Option<&[u8]> {
        self.body.as_deref()
    }

    pub fn header(&self, key: &str) -> Option<&str> {
        self.headers.get(key).map(|s| s.as_str())
    }
}

/// Builder for HTTP responses
pub struct ResponseBuilder {
    status: u16,
    headers: HashMap<String, String>,
    body: Option<Vec<u8>>,
}

impl ResponseBuilder {
    pub fn new() -> Self {
        Self {
            status: 200,
            headers: HashMap::new(),
            body: None,
        }
    }

    pub fn status(mut self, code: u16) -> Self {
        self.status = code;
        self
    }

    pub fn header(mut self, key: &str, value: &str) -> Self {
        self.headers.insert(key.to_string(), value.to_string());
        self
    }

    pub fn body(mut self, content: &str) -> Self {
        self.body = Some(content.as_bytes().to_vec());
        self
    }

    pub fn json<T: serde::Serialize>(mut self, value: &T) -> Self {
        self.headers.insert("Content-Type".into(), "application/json".into());
        self.body = serde_json::to_vec(value).ok();
        self
    }
}

/// Timing middleware for performance monitoring
pub fn timing<F, R>(name: &str, f: F) -> R where F: FnOnce() -> R {
    let start = Instant::now();
    let result = f();
    log::debug!("{} completed in {:?}", name, start.elapsed());
    result
}

/// Authentication middleware
pub fn authenticate(ctx: &mut RequestContext) -> Result<(), AuthError> {
    let token = ctx.header("Authorization")
        .and_then(|h| h.strip_prefix("Bearer "))
        .ok_or(AuthError::MissingToken)?;

    let user_id = validate_token(token)?;
    ctx.user_id = Some(user_id);
    Ok(())
}

fn validate_token(token: &str) -> Result<u32, AuthError> {
    // Token validation logic
    if token.len() < 32 { return Err(AuthError::InvalidToken); }
    Ok(1) // Placeholder
}

pub enum AuthError { MissingToken, InvalidToken }
"#,
    )
    .unwrap();
    repo.run_git_in(&feature_api, &["add", "middleware.rs"]);
    repo.commit_staged_with_age("Add request middleware", 3 * HOUR, &feature_api);

    std::fs::write(
        feature_api.join("validation.rs"),
        r#"//! Request validation
pub fn validate(body: &[u8], headers: &Headers) -> Result<(), Error> {
    if body.is_empty() { return Err(Error::EmptyBody); }
    if body.len() > MAX_SIZE { return Err(Error::TooLarge); }
    if !headers.contains_key("Authorization") { return Err(Error::Unauthorized); }
    Ok(())
}
"#,
    )
    .unwrap();
    repo.run_git_in(&feature_api, &["add", "validation.rs"]);
    repo.commit_staged_with_age("Add request validation", 2 * HOUR, &feature_api);

    std::fs::write(
        feature_api.join("tests.rs"),
        r#"//! API tests
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_health() { assert_eq!(routes::health(), "ok"); }

    #[test]
    fn test_validation_empty() {
        assert!(validation::validate(&[], &headers()).is_err());
    }
}
"#,
    )
    .unwrap();
    repo.run_git_in(&feature_api, &["add", "tests.rs"]);
    repo.commit_staged_with_age("Add API tests", 30 * MINUTE, &feature_api);

    // Staged changes: new files + refactor existing (creates mixed +/- for HEAD±)
    // Adding caching and rate limiting, plus refactoring validation
    std::fs::write(
        feature_api.join("cache.rs"),
        r#"//! Caching layer
use std::collections::HashMap;
use std::time::{Duration, Instant};

pub struct Cache<T> {
    store: HashMap<String, (T, Instant)>,
    ttl: Duration,
}

impl<T: Clone> Cache<T> {
    pub fn new(ttl_secs: u64) -> Self {
        Self { store: HashMap::new(), ttl: Duration::from_secs(ttl_secs) }
    }
    pub fn get(&self, key: &str) -> Option<T> {
        self.store.get(key).and_then(|(v, t)| {
            if t.elapsed() < self.ttl { Some(v.clone()) } else { None }
        })
    }
}
"#,
    )
    .unwrap();
    std::fs::write(
        feature_api.join("rate_limit.rs"),
        r#"//! Rate limiting
use std::collections::HashMap;
use std::time::{Duration, Instant};

pub struct RateLimiter {
    requests: HashMap<String, Vec<Instant>>,
    window: Duration,
    limit: u32,
}

impl RateLimiter {
    pub fn check(&mut self, key: &str) -> bool {
        let now = Instant::now();
        let reqs = self.requests.entry(key.to_string()).or_default();
        reqs.retain(|t| now.duration_since(*t) < self.window);
        reqs.len() < self.limit as usize
    }
}
"#,
    )
    .unwrap();
    // Refactor validation.rs to use the new error types
    std::fs::write(
        feature_api.join("validation.rs"),
        r#"//! Request validation (refactored)
use crate::error::ValidationError;

pub fn validate(body: &[u8], headers: &Headers) -> Result<(), ValidationError> {
    validate_body(body)?;
    validate_headers(headers)?;
    Ok(())
}

fn validate_body(body: &[u8]) -> Result<(), ValidationError> {
    if body.is_empty() { return Err(ValidationError::Empty); }
    if body.len() > MAX_SIZE { return Err(ValidationError::TooLarge); }
    Ok(())
}

fn validate_headers(h: &Headers) -> Result<(), ValidationError> {
    h.get("Authorization").ok_or(ValidationError::Unauthorized)?;
    Ok(())
}
"#,
    )
    .unwrap();
    repo.run_git_in(
        &feature_api,
        &["add", "cache.rs", "rate_limit.rs", "validation.rs"],
    );

    // === Create branches without worktrees ===
    // These demonstrate the --branches flag showing branch-only entries

    // Create 'exp' branch with commits (experimental GraphQL work)
    // Narrative: Someone explored GraphQL as an alternative to REST, got pretty far with
    // schema design and resolvers, but the team decided to stick with REST for now.
    let exp_wt = repo.root_path().parent().unwrap().join("temp-exp");
    repo.run_git(&["worktree", "add", "-b", "exp", exp_wt.to_str().unwrap()]);

    std::fs::write(
        exp_wt.join("graphql.rs"),
        r#"//! GraphQL schema exploration - evaluating GraphQL for real-time subscriptions
//!
//! This spike branch explores whether GraphQL could replace REST for the subscription
//! API. Key evaluation criteria:
//! - Real-time updates via subscriptions
//! - Efficient data fetching (avoid over-fetching)
//! - Type safety with code generation

use async_graphql::*;

/// Core user type with all fields exposed via GraphQL
#[derive(SimpleObject, Clone)]
pub struct User {
    pub id: ID,
    pub name: String,
    pub email: String,
    pub avatar_url: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// Blog post with author relationship
#[derive(SimpleObject, Clone)]
pub struct Post {
    pub id: ID,
    pub title: String,
    pub body: String,
    pub author: User,
    pub published_at: Option<DateTime<Utc>>,
    pub tags: Vec<String>,
}

/// Comment on a post
#[derive(SimpleObject, Clone)]
pub struct Comment {
    pub id: ID,
    pub body: String,
    pub author: User,
    pub post_id: ID,
    pub created_at: DateTime<Utc>,
}

/// Subscription events for real-time updates
#[derive(Clone)]
pub enum SubscriptionEvent {
    PostCreated(Post),
    PostUpdated(Post),
    CommentAdded { post_id: ID, comment: Comment },
}

/// Pagination support
#[derive(InputObject)]
pub struct PaginationInput {
    pub limit: Option<i32>,
    pub offset: Option<i32>,
    pub cursor: Option<String>,
}

#[derive(SimpleObject)]
pub struct PageInfo {
    pub has_next_page: bool,
    pub has_previous_page: bool,
    pub start_cursor: Option<String>,
    pub end_cursor: Option<String>,
}
"#,
    )
    .unwrap();
    repo.run_git_in(&exp_wt, &["add", "graphql.rs"]);
    repo.commit_staged_with_age("Explore GraphQL schema design", 2 * DAY, &exp_wt);

    std::fs::write(
        exp_wt.join("resolvers.rs"),
        r#"//! GraphQL resolvers - Query, Mutation, and Subscription roots
use crate::graphql::*;
use async_graphql::*;

pub struct QueryRoot;

#[Object]
impl QueryRoot {
    /// Fetch a single user by ID
    async fn user(&self, ctx: &Context<'_>, id: ID) -> Result<Option<User>> {
        let db = ctx.data::<Database>()?;
        Ok(db.get_user(&id).await?)
    }

    /// List users with pagination
    async fn users(&self, ctx: &Context<'_>, pagination: Option<PaginationInput>) -> Result<Vec<User>> {
        let db = ctx.data::<Database>()?;
        let page = pagination.unwrap_or_default();
        Ok(db.list_users(page.limit.unwrap_or(20), page.offset.unwrap_or(0)).await?)
    }

    /// Fetch a single post by ID
    async fn post(&self, ctx: &Context<'_>, id: ID) -> Result<Option<Post>> {
        let db = ctx.data::<Database>()?;
        Ok(db.get_post(&id).await?)
    }

    /// List posts with optional author filter
    async fn posts(&self, ctx: &Context<'_>, author_id: Option<ID>) -> Result<Vec<Post>> {
        let db = ctx.data::<Database>()?;
        match author_id {
            Some(id) => Ok(db.posts_by_author(&id).await?),
            None => Ok(db.list_posts().await?),
        }
    }
}

pub struct MutationRoot;

#[Object]
impl MutationRoot {
    /// Create a new post
    async fn create_post(&self, ctx: &Context<'_>, title: String, body: String) -> Result<Post> {
        let db = ctx.data::<Database>()?;
        let user = ctx.data::<AuthenticatedUser>()?;
        let post = db.create_post(user.id.clone(), title, body).await?;
        Ok(post)
    }

    /// Add a comment to a post
    async fn add_comment(&self, ctx: &Context<'_>, post_id: ID, body: String) -> Result<Comment> {
        let db = ctx.data::<Database>()?;
        let user = ctx.data::<AuthenticatedUser>()?;
        let comment = db.add_comment(user.id.clone(), post_id, body).await?;
        Ok(comment)
    }
}

pub struct SubscriptionRoot;

#[Subscription]
impl SubscriptionRoot {
    /// Subscribe to new comments on a post
    async fn comment_added(&self, post_id: ID) -> impl Stream<Item = Comment> {
        todo!("Implement subscription stream")
    }

    /// Subscribe to all post updates
    async fn post_updates(&self) -> impl Stream<Item = Post> {
        todo!("Implement subscription stream")
    }
}
"#,
    )
    .unwrap();
    repo.run_git_in(&exp_wt, &["add", "resolvers.rs"]);
    repo.commit_staged_with_age("Add GraphQL resolvers scaffold", 2 * DAY, &exp_wt);

    // Remove the worktree but keep the branch
    repo.run_git(&["worktree", "remove", exp_wt.to_str().unwrap()]);

    // Create 'wip' branch with commits (work-in-progress docs)
    // Narrative: Someone started API docs last week. Main has since advanced
    // (fix-auth was merged), so wip is now behind and needs a rebase.

    // Save current main commit, then add a commit to main (simulating fix-auth merge)
    let wip_base = {
        let output = repo
            .git_command()
            .args(["rev-parse", "HEAD"])
            .run()
            .unwrap();
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    };

    // Add commit to main (simulating fix-auth being merged while wip was idle)
    repo.commit_with_age("Merge fix-auth: hardened token validation", 4 * DAY);

    // Create wip from the earlier commit (before main advanced)
    let wip_wt = repo.root_path().parent().unwrap().join("temp-wip");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "wip",
        wip_wt.to_str().unwrap(),
        &wip_base,
    ]);

    std::fs::write(
        wip_wt.join("API.md"),
        r#"# API Documentation

## Overview

This document describes the REST API endpoints for the application.

## Authentication

All endpoints require a valid Bearer token in the `Authorization` header.

```
Authorization: Bearer <token>
```

## Endpoints

### Users

- `GET /users` - List all users (paginated)
- `GET /users/:id` - Get user by ID
- `POST /users` - Create new user

### Posts

- `GET /posts` - List all posts
- `GET /posts/:id` - Get post by ID
- `POST /posts` - Create new post

## Error Responses

All errors return JSON with `error` and `message` fields.

TODO: Add request/response examples for each endpoint
"#,
    )
    .unwrap();
    repo.run_git_in(&wip_wt, &["add", "API.md"]);
    repo.commit_staged_with_age("Start API documentation", 3 * DAY, &wip_wt);

    // Remove the worktree but keep the branch
    repo.run_git(&["worktree", "remove", wip_wt.to_str().unwrap()]);

    // === Create fix-typos worktree (already merged — shows dimmed as removable) ===
    // Story: A quick typo fix that was already squash-merged into main.
    // The worktree is still around and can be removed. Shows dimmed in list output.
    let fix_typos = repo.add_worktree("fix-typos");
    repo.run_git_in(&fix_typos, &["push", "-u", "origin", "fix-typos"]);
    mock_ci_status(repo, "fix-typos", "passed", "pull-request", false);

    // === Mock CI status ===
    // CI requires --full flag, but we mock it so examples show realistic output
    // Note: main's CI is mocked AFTER the merge commit so the hash matches
    mock_ci_status(repo, "main", "passed", "pull-request", false);
    mock_ci_status(repo, "fix-auth", "passed", "pull-request", false);
    // feature-api has unpushed commits, so CI is stale (shows dimmed)
    mock_ci_status(repo, "feature-api", "running", "pull-request", true);

    // === Mock LLM summaries ===
    // Summary requires --full + [list] summary = true + [commit.generation] command
    // Pre-populate the cache so tests don't need a real LLM
    repo.write_test_config(
        r#"
[list]
summary = true

[commit.generation]
command = "echo unused"
"#,
    );
    mock_summary_cache(
        repo,
        "fix-auth",
        Some(&fix_auth),
        "Harden auth with constant-time token validation",
    );
    mock_summary_cache(
        repo,
        "feature-api",
        Some(&feature_api),
        "Refactor API to REST architecture with middleware",
    );
    mock_summary_cache(repo, "exp", None, "Explore GraphQL schema and resolvers");
    mock_summary_cache(repo, "wip", None, "Start API documentation");

    feature_api
}

/// Mock CI status by writing to file-based cache
fn mock_ci_status(repo: &TestRepo, branch: &str, status: &str, source: &str, is_stale: bool) {
    // Get HEAD commit for the branch
    let output = repo
        .git_command()
        .args(["rev-parse", branch])
        .run()
        .unwrap();
    let head = String::from_utf8_lossy(&output.stdout).trim().to_string();

    // Build the cache JSON (matches CachedCiStatus struct)
    let cache_json = format!(
        r#"{{"status":{{"ci_status":"{}","source":"{}","is_stale":{}}},"checked_at":{},"head":"{}","branch":"{}"}}"#,
        status,
        source,
        is_stale,
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs(),
        head,
        branch
    );

    // Get git common dir for cache location
    let output = repo
        .git_command()
        .args(["rev-parse", "--git-common-dir"])
        .run()
        .unwrap();
    let git_dir = String::from_utf8_lossy(&output.stdout).trim().to_string();

    // Resolve relative path if needed
    let git_path = if std::path::Path::new(&git_dir).is_absolute() {
        std::path::PathBuf::from(&git_dir)
    } else {
        repo.root_path().join(&git_dir)
    };

    // Create cache directory and write file
    let cache_dir = git_path.join("wt").join("cache").join("ci-status");
    std::fs::create_dir_all(&cache_dir).unwrap();

    // Use the same sanitization as production code for cache filenames
    let safe_branch = worktrunk::path::sanitize_for_filename(branch);
    let cache_file = cache_dir.join(format!("{safe_branch}.json"));
    std::fs::write(&cache_file, &cache_json).unwrap();
}

/// Mock summary cache by computing the real diff hash and writing a cache entry.
///
/// Mirrors `summary::generate_summary_core` — computes the combined diff
/// (branch + working tree), hashes it, and writes a CachedSummary JSON file.
fn mock_summary_cache(
    repo: &TestRepo,
    branch: &str,
    worktree_path: Option<&std::path::Path>,
    summary: &str,
) {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    // Compute combined diff (matching compute_combined_diff in summary.rs)
    let mut diff = String::new();

    // Branch diff: main...<branch>
    let head_output = repo
        .git_command()
        .args(["rev-parse", branch])
        .run()
        .unwrap();
    let head = String::from_utf8_lossy(&head_output.stdout)
        .trim()
        .to_string();
    let merge_base = format!("main...{}", head);
    if let Ok(output) = repo.git_command().args(["diff", &merge_base]).run() {
        let branch_diff = String::from_utf8_lossy(&output.stdout);
        diff.push_str(&branch_diff);
    }

    // Working tree diff (only if worktree exists)
    if let Some(wt_path) = worktree_path {
        let wt_str = wt_path.display().to_string();
        if let Ok(output) = repo
            .git_command()
            .args(["-C", &wt_str, "diff", "HEAD"])
            .run()
        {
            let wt_diff = String::from_utf8_lossy(&output.stdout);
            if !wt_diff.trim().is_empty() {
                diff.push_str(&wt_diff);
            }
        }
    }

    // Hash the diff (matches summary::hash_diff)
    let mut hasher = DefaultHasher::new();
    diff.hash(&mut hasher);
    let diff_hash = hasher.finish();

    // Write cache file
    let cache_json = format!(
        r#"{{"summary":"{}","diff_hash":{},"branch":"{}"}}"#,
        summary, diff_hash, branch
    );

    let output = repo
        .git_command()
        .args(["rev-parse", "--git-common-dir"])
        .run()
        .unwrap();
    let git_dir = String::from_utf8_lossy(&output.stdout).trim().to_string();
    let git_path = if std::path::Path::new(&git_dir).is_absolute() {
        std::path::PathBuf::from(&git_dir)
    } else {
        repo.root_path().join(&git_dir)
    };

    let cache_dir = git_path.join("wt").join("cache").join("summaries");
    std::fs::create_dir_all(&cache_dir).unwrap();
    let safe_branch = worktrunk::path::sanitize_for_filename(branch);
    let cache_file = cache_dir.join(format!("{safe_branch}.json"));
    std::fs::write(&cache_file, &cache_json).unwrap();
}

// =============================================================================
// Quick Start Snapshot Tests
// =============================================================================

/// Generate Quick Start example: `wt switch --create feature-auth` output
///
/// Shows the switch output when creating a new worktree from main.
/// Sets WORKTRUNK_DIRECTIVE_CD_FILE to simulate shell integration being active,
/// which suppresses the "Cannot change directory" warning.
/// Output: tests/snapshots/integration__integration_tests__list__quickstart_switch.snap
#[rstest]
fn test_quickstart_switch(mut repo: TestRepo) {
    setup_quickstart_base(&mut repo);
    // Create a temp file for the directive outside the repo to avoid making main dirty
    let directive_file = repo
        .root_path()
        .parent()
        .unwrap()
        .join(".wt-directive-temp");
    std::fs::write(&directive_file, "").unwrap();
    assert_cmd_snapshot!("quickstart_switch", {
        let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "feature-auth"], None);
        cmd.env("WORKTRUNK_DIRECTIVE_CD_FILE", &directive_file);
        cmd
    });
}

/// Generate Quick Start example: Simple `wt list` output
///
/// Shows minimal 2-worktree scenario: main + feature-auth.
/// Output: tests/snapshots/integration__integration_tests__list__quickstart_list.snap
#[rstest]
fn test_quickstart_list(mut repo: TestRepo) {
    let feature_auth = setup_quickstart_repo(&mut repo);
    assert_cmd_snapshot!(
        "quickstart_list",
        list_snapshots::command_readme(&repo, &feature_auth)
    );
}

/// Generate Quick Start example: `wt merge` output
///
/// Shows merge output when merging feature-auth into main.
/// Sets WORKTRUNK_DIRECTIVE_CD_FILE to simulate shell integration being active,
/// which suppresses the "Cannot change directory" warning.
/// Output: tests/snapshots/integration__integration_tests__list__quickstart_merge.snap
#[rstest]
fn test_quickstart_merge(mut repo: TestRepo) {
    setup_quickstart_base(&mut repo);

    // Ensure main worktree is completely clean (no staged or unstaged changes)
    repo.run_git(&["checkout", "--", "."]);
    repo.run_git(&["clean", "-fd"]);

    // Create feature-auth worktree with one commit
    let feature_auth = repo.add_worktree("feature-auth");

    // Add authentication module (full WIP version — all staged, no commit, for wt merge)
    std::fs::write(
        feature_auth.join("auth.rs"),
        r#"//! Authentication module for user session management.

use std::time::{Duration, SystemTime};

/// A user session with token and expiry.
pub struct Session {
    token: String,
    expires_at: SystemTime,
}

impl Session {
    /// Creates a new session with the given token and TTL.
    pub fn new(token: String, ttl: Duration) -> Self {
        Self {
            token,
            expires_at: SystemTime::now() + ttl,
        }
    }

    /// Returns true if the session has not expired.
    pub fn is_valid(&self) -> bool {
        SystemTime::now() < self.expires_at
    }

    /// Validates the token format.
    pub fn validate_token(token: &str) -> bool {
        token.len() >= 32 && token.chars().all(|c| c.is_ascii_alphanumeric())
    }
}

/// Checks if user is authenticated with a valid session.
pub fn is_authenticated(session: Option<&Session>) -> bool {
    session.map(|s| s.is_valid()).unwrap_or(false)
}

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

    #[test]
    fn test_session_validity() {
        let session = Session::new("a".repeat(32), Duration::from_secs(3600));
        assert!(session.is_valid());
    }

    #[test]
    fn test_validate_token() {
        assert!(!Session::validate_token("short"));
        assert!(Session::validate_token(&"x".repeat(32)));
    }
}
"#,
    )
    .unwrap();

    // Update lib.rs to include the new module
    let lib_content = std::fs::read_to_string(feature_auth.join("lib.rs")).unwrap();
    std::fs::write(
        feature_auth.join("lib.rs"),
        format!("mod auth;\n\n{}", lib_content),
    )
    .unwrap();

    // Stage files but don't commit - let wt merge do the committing
    repo.run_git_in(&feature_auth, &["add", "auth.rs", "lib.rs"]);

    // Create a temp file for the directive outside the repo to avoid making main dirty
    let directive_file = repo
        .root_path()
        .parent()
        .unwrap()
        .join(".wt-directive-temp");
    std::fs::write(&directive_file, "").unwrap();

    // Create a cross-platform mock LLM command (uses mock-stub binary system)
    // The mock-bin directory is already created by setup_mock_gh() via the repo fixture
    let mock_bin_dir = repo.root_path().parent().unwrap().join("mock-bin");
    create_mock_llm_quickstart(&mock_bin_dir);

    // Configure the LLM path (Windows needs .exe extension)
    let llm_name = if cfg!(windows) { "llm.exe" } else { "llm" };
    let llm_path = mock_bin_dir.join(llm_name);

    // Merge feature-auth into main
    assert_cmd_snapshot!("quickstart_merge", {
        let mut cmd = make_snapshot_cmd(&repo, "merge", &["main"], Some(&feature_auth));
        cmd.env("WORKTRUNK_DIRECTIVE_CD_FILE", &directive_file);
        // Set MOCK_CONFIG_DIR so mock-stub can find llm.json
        cmd.env("MOCK_CONFIG_DIR", &mock_bin_dir);
        // Use to_slash_lossy() for Windows compatibility - bash can't handle backslash paths
        cmd.env(
            "WORKTRUNK_COMMIT__GENERATION__COMMAND",
            llm_path.to_slash_lossy().as_ref(),
        );
        cmd
    });
}

// =============================================================================
// Full README Snapshot Tests
// =============================================================================

/// Generate README example: Basic `wt list` output
///
/// Shows worktree states with status symbols, divergence, and remote tracking.
/// Uses narrower width (100 cols) to fit in doc site code blocks.
/// Output: tests/snapshots/integration__integration_tests__list__readme_example_list.snap
#[rstest]
fn test_readme_example_list(mut repo: TestRepo) {
    let feature_api = setup_readme_example_repo(&mut repo);
    assert_cmd_snapshot!(
        "readme_example_list",
        list_snapshots::command_readme(&repo, &feature_api)
    );
}

/// Generate README example: `wt list --full` output
///
/// Shows additional columns: main…± (line diffs), CI status, and LLM summaries.
/// Uses wider terminal (130 cols) than the base example to fit the Summary column.
/// Output: tests/snapshots/integration__integration_tests__list__readme_example_list_full.snap
#[rstest]
fn test_readme_example_list_full(mut repo: TestRepo) {
    let feature_api = setup_readme_example_repo(&mut repo);
    assert_cmd_snapshot!("readme_example_list_full", {
        let mut cmd = list_snapshots::command_readme(&repo, &feature_api);
        cmd.arg("--full");
        cmd.env("COLUMNS", "130");
        cmd
    });
}

/// Generate README example: `wt list --branches --full` output
///
/// Shows branches without worktrees (⎇ symbol) alongside worktrees, plus CI status.
/// Uses wider terminal (130 cols) than the base example to fit the Summary column.
/// Output: tests/snapshots/integration__integration_tests__list__readme_example_list_branches.snap
#[rstest]
fn test_readme_example_list_branches(mut repo: TestRepo) {
    let feature_api = setup_readme_example_repo(&mut repo);
    assert_cmd_snapshot!("readme_example_list_branches", {
        let mut cmd = list_snapshots::command_readme(&repo, &feature_api);
        cmd.args(["--branches", "--full"]);
        cmd.env("COLUMNS", "130");
        cmd
    });
}

/// Generate config state marker example: `wt list` with user markers
///
/// Shows how user markers appear in the Status column alongside git symbols.
/// Used by `wt config state marker --help` and docs via placeholder expansion.
/// Output: tests/snapshots/integration__integration_tests__list__readme_example_list_marker.snap
#[rstest]
fn test_readme_example_list_marker(mut repo: TestRepo) {
    remove_fixture_worktrees(&mut repo);

    repo.commit_with_age("Initial commit", DAY);

    // Branch ahead of main with commits and user marker 🤖
    let _feature_wt = repo.add_worktree_with_commit(
        "feature-api",
        "api.rs",
        "// API implementation",
        "Add REST API endpoints",
    );
    repo.set_marker("feature-api", "🤖");

    // Branch with uncommitted changes and user marker 💬
    let review_wt = repo.add_worktree_with_commit(
        "review-ui",
        "component.tsx",
        "// UI component",
        "Add dashboard component",
    );
    std::fs::write(review_wt.join("styles.css"), "/* pending styles */").unwrap();
    repo.set_marker("review-ui", "💬");

    // Branch with uncommitted changes only (no user marker)
    let wip_wt = repo.add_worktree("wip-docs");
    std::fs::write(wip_wt.join("README.md"), "# Documentation").unwrap();

    assert_cmd_snapshot!(
        "readme_example_list_marker",
        list_snapshots::command_readme(&repo, repo.root_path())
    );
}

/// Generate tips-patterns.md example: dev server per worktree workflow
///
/// Uses the realistic README example repo and adds URL config.
/// URLs appear dimmed (no servers running) - realistic for documentation.
#[rstest]
fn test_tips_dev_server_workflow(mut repo: TestRepo) {
    // Set up the realistic README example repo
    let _feature_api = setup_readme_example_repo(&mut repo);

    // Add project config with URL template for dev servers
    repo.write_project_config(
        r#"[post-start]
server = "npm run dev -- --port {{ branch | hash_port }} &"

[list]
url = "http://localhost:{{ branch | hash_port }}"
"#,
    );

    // Run from main worktree (URLs dim since no servers running)
    assert_cmd_snapshot!(
        "tips_dev_server_workflow",
        list_snapshots::command_readme(&repo, repo.root_path())
    );
}

#[rstest]
fn test_list_progressive_flag(mut repo: TestRepo) {
    repo.add_worktree("feature-a");
    repo.add_worktree("feature-b");

    // Force progressive mode even in non-TTY test environment
    // Output should be identical to buffered mode (only process differs)
    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--progressive");
        cmd
    });
}

#[rstest]
fn test_list_no_progressive_flag(mut repo: TestRepo) {
    repo.add_worktree("feature");

    // Explicitly force buffered mode
    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--no-progressive");
        cmd
    });
}

#[rstest]
fn test_list_progressive_with_branches(mut repo: TestRepo) {
    // Create worktrees
    repo.add_worktree("feature-a");

    // Create branches without worktrees
    repo.create_branch("orphan-1");
    repo.create_branch("orphan-2");

    // Critical: test that --branches works with --progressive
    // This ensures progressive mode supports the --branches flag
    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.args(["--progressive", "--branches"]);
        cmd
    });
}

// ============================================================================
// Task DAG Mode Tests
// ============================================================================

#[rstest]
fn test_list_task_dag_single_worktree(repo: TestRepo) {
    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--progressive");
        cmd
    });
}

#[rstest]
fn test_list_task_dag_multiple_worktrees(mut repo: TestRepo) {
    repo.add_worktree("feature-a");
    repo.add_worktree("feature-b");
    repo.add_worktree("feature-c");

    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--progressive");
        cmd
    });
}

#[rstest]
fn test_list_task_dag_full_with_diffs(mut repo: TestRepo) {
    // Create worktree with changes
    let feature_a = repo.add_worktree("feature-a");
    std::fs::write(feature_a.join("new.txt"), "content").unwrap();

    // Create another worktree with commits
    let _feature_b = repo.add_worktree_with_commit("feature-b", "file.txt", "test", "Test commit");

    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.args(["--progressive", "--full"]);
        cmd
    });
}

#[rstest]
fn test_list_task_dag_with_upstream(mut repo: TestRepo) {
    repo.commit("Initial commit on main");
    repo.setup_remote("main");

    // Branch in sync
    let in_sync = repo.add_worktree("in-sync");
    repo.run_git_in(&in_sync, &["push", "-u", "origin", "in-sync"]);

    // Branch ahead
    let ahead = repo.add_worktree("ahead");
    repo.run_git_in(&ahead, &["push", "-u", "origin", "ahead"]);
    std::fs::write(ahead.join("ahead.txt"), "ahead").unwrap();
    repo.run_git_in(&ahead, &["add", "."]);
    repo.run_git_in(&ahead, &["commit", "-m", "Ahead commit"]);

    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.args(["--progressive", "--full"]);
        cmd
    });
}

#[rstest]
fn test_list_task_dag_many_worktrees(mut repo: TestRepo) {
    // Create 10 worktrees to test parallel processing
    for i in 1..=10 {
        repo.add_worktree(&format!("feature-{}", i));
    }

    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--progressive");
        cmd
    });
}

#[rstest]
fn test_list_task_dag_with_locked_worktree(mut repo: TestRepo) {
    repo.add_worktree("normal");
    repo.add_worktree("locked");
    repo.lock_worktree("locked", Some("Testing task DAG with locked worktree"));

    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--progressive");
        cmd
    });
}

#[rstest]
fn test_list_task_dag_detached_head(repo: TestRepo) {
    repo.detach_head();

    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--progressive");
        cmd
    });
}

#[rstest]
fn test_list_task_dag_ordering_stability(mut repo: TestRepo) {
    // Test that task_dag mode produces same ordering as buffered mode
    // Regression test for progressive rendering order instability
    let current_path = setup_timestamped_worktrees(&mut repo);

    // Run from feature-current worktree
    // Expected order: main, feature-current, then by timestamp: feature-newest, feature-middle, feature-oldest
    assert_cmd_snapshot!("task_dag_ordering_stability", {
        let mut cmd = list_snapshots::command(&repo, &current_path);
        cmd.arg("--progressive");
        cmd
    });
}

#[rstest]
fn test_list_progressive_vs_buffered_identical_data(mut repo: TestRepo) {
    // Critical test: Verify that progressive and buffered modes collect identical data
    // despite using different rendering strategies (real-time UI vs collect-then-print).
    // This ensures consolidation on task DAG data collection works correctly.
    //
    // Note: We compare JSON output, not table output, because:
    // - Progressive mode renders headers before knowing final column widths (uses estimates)
    // - Buffered mode renders headers after data collection (uses actual widths)
    // - The DATA must be identical, but table formatting may differ slightly

    // Create varied worktrees to test multiple data points
    repo.add_worktree("feature-a");
    repo.add_worktree("feature-b");

    // Modify a worktree to have uncommitted changes
    let feature_a_path = repo.worktree_path("feature-a");
    std::fs::write(feature_a_path.join("changes.txt"), "test").unwrap();

    // Run both modes with JSON output to compare data (not formatting)
    let progressive_output = {
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.args(["--progressive", "--format=json"]);
        cmd.output().unwrap()
    };

    let buffered_output = {
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.args(["--no-progressive", "--format=json"]);
        cmd.output().unwrap()
    };

    // Both should succeed
    assert!(
        progressive_output.status.success(),
        "Progressive mode failed: {}",
        String::from_utf8_lossy(&progressive_output.stderr)
    );
    assert!(
        buffered_output.status.success(),
        "Buffered mode failed: {}",
        String::from_utf8_lossy(&buffered_output.stderr)
    );

    // Parse JSON outputs
    let progressive_json: serde_json::Value =
        serde_json::from_slice(&progressive_output.stdout).unwrap();
    let buffered_json: serde_json::Value = serde_json::from_slice(&buffered_output.stdout).unwrap();

    // The JSON data should be identical (ignoring display fields which may have formatting differences)
    // Compare the structured data to ensure both modes collect the same information
    assert_eq!(
        progressive_json,
        buffered_json,
        "Progressive and buffered modes produced different data!\n\nProgressive:\n{}\n\nBuffered:\n{}",
        serde_json::to_string_pretty(&progressive_json).unwrap(),
        serde_json::to_string_pretty(&buffered_json).unwrap()
    );
}

#[rstest]
fn test_list_with_c_flag(mut repo: TestRepo) {
    // Create some worktrees
    repo.add_worktree("feature-a");
    repo.add_worktree("feature-b");

    // Run wt -C <repo_path> list from a completely different directory
    assert_cmd_snapshot!("list_with_c_flag", {
        let mut cmd = wt_command();
        cmd.args(["-C", repo.root_path().to_str().unwrap(), "list"]);
        // Run from system temp dir to ensure -C is actually being used
        cmd.current_dir(std::env::temp_dir());
        cmd
    });
}

#[rstest]
fn test_list_large_diffs_alignment(mut repo: TestRepo) {
    // Worktree with large uncommitted changes and ahead commits
    // Use a longer branch name similar to user's "wli-sequence" to trigger column width
    let large_wt = repo.add_worktree("feature-changes");

    // Create a file with many lines for large diff
    let large_content = (1..=100)
        .map(|i| format!("line {}", i))
        .collect::<Vec<_>>()
        .join("\n");
    std::fs::write(large_wt.join("large.txt"), &large_content).unwrap();

    // Commit it
    repo.run_git_in(&large_wt, &["add", "."]);
    repo.run_git_in(&large_wt, &["commit", "-m", "Add 100 lines"]);

    // Add large uncommitted changes (both added and deleted lines)
    // Add a new file with many lines
    std::fs::write(large_wt.join("uncommitted.txt"), &large_content).unwrap();

    // Modify the existing file to create deletions
    let modified_content = (1..=50)
        .map(|i| format!("modified line {}", i))
        .collect::<Vec<_>>()
        .join("\n");
    std::fs::write(large_wt.join("large.txt"), &modified_content).unwrap();

    // Add another new file with many lines
    let another_large = (1..=80)
        .map(|i| format!("another line {}", i))
        .collect::<Vec<_>>()
        .join("\n");
    std::fs::write(large_wt.join("another.txt"), &another_large).unwrap();

    // Set user marker
    repo.set_marker("feature-changes", "🤖");

    // Worktree with short name to show gap before Status column
    let short_wt = repo.add_worktree("fix");
    std::fs::write(short_wt.join("quick.txt"), "quick fix").unwrap();

    // Set user marker for short branch
    repo.set_marker("fix", "💬");

    // Worktree with diverged status and working tree changes
    let diverged_wt = repo.add_worktree("diverged");

    // Commit some changes
    let diverged_content = (1..=60)
        .map(|i| format!("diverged line {}", i))
        .collect::<Vec<_>>()
        .join("\n");
    std::fs::write(diverged_wt.join("test.txt"), &diverged_content).unwrap();
    repo.run_git_in(&diverged_wt, &["add", "."]);
    repo.run_git_in(&diverged_wt, &["commit", "-m", "Diverged commit"]);

    // Add uncommitted changes
    let modified_diverged = (1..=40)
        .map(|i| format!("modified diverged line {}", i))
        .collect::<Vec<_>>()
        .join("\n");
    std::fs::write(diverged_wt.join("test.txt"), &modified_diverged).unwrap();

    // Set user marker
    repo.set_marker("diverged", "💬");

    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

#[rstest]
fn test_list_status_column_padding_with_emoji(mut repo: TestRepo) {
    // Create worktree matching user's exact scenario: "wli-sequence"
    let wli_seq = repo.add_worktree("wli-sequence");

    // Create large working tree changes: +164, -111
    // Need ~164 added lines and ~111 deleted lines
    let initial_content = (1..=200)
        .map(|i| format!("original line {}", i))
        .collect::<Vec<_>>()
        .join("\n");
    std::fs::write(wli_seq.join("main.txt"), &initial_content).unwrap();

    repo.run_git_in(&wli_seq, &["add", "."]);
    repo.run_git_in(&wli_seq, &["commit", "-m", "Initial content"]);

    // Modify to create desired diff: remove ~111 lines, add different content
    let modified_content = (1..=89)
        .map(|i| format!("original line {}", i))
        .collect::<Vec<_>>()
        .join("\n");
    std::fs::write(wli_seq.join("main.txt"), &modified_content).unwrap();

    // Add new file with ~164 lines to get +164
    let new_content = (1..=164)
        .map(|i| format!("new line {}", i))
        .collect::<Vec<_>>()
        .join("\n");
    std::fs::write(wli_seq.join("new.txt"), &new_content).unwrap();

    // Set user marker emoji 🤖
    repo.set_marker("wli-sequence", "🤖");

    // Create "pr-link" worktree with different status (fewer symbols, same emoji type)
    let pr_link = repo.add_worktree("pr-link");

    // Commit to make it ahead
    std::fs::write(pr_link.join("pr.txt"), "pr content").unwrap();
    repo.run_git_in(&pr_link, &["add", "."]);
    repo.run_git_in(&pr_link, &["commit", "-m", "PR commit"]);

    // Set same emoji type
    repo.set_marker("pr-link", "🤖");

    // Create "main-symbol" with different emoji
    let main_sym = repo.add_worktree("main-symbol");
    std::fs::write(main_sym.join("sym.txt"), "symbol").unwrap();
    repo.run_git_in(&main_sym, &["add", "."]);
    repo.run_git_in(&main_sym, &["commit", "-m", "Symbol commit"]);

    repo.set_marker("main-symbol", "💬");

    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

#[rstest]
fn test_list_maximum_working_tree_symbols(mut repo: TestRepo) {
    // Test that all 5 working tree symbols can appear simultaneously:
    // ? (untracked), ! (modified), + (staged), » (renamed), ✘ (deleted)
    // This verifies the maximum width of the working_tree position (5 chars)

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

    // Create initial files to manipulate
    std::fs::write(feature.join("file-a.txt"), "original a").unwrap();
    std::fs::write(feature.join("file-b.txt"), "original b").unwrap();
    std::fs::write(feature.join("file-c.txt"), "original c").unwrap();
    std::fs::write(feature.join("file-d.txt"), "original d").unwrap();

    repo.run_git_in(&feature, &["add", "."]);
    repo.run_git_in(&feature, &["commit", "-m", "Add files"]);

    // 1. Create untracked file (?)
    std::fs::write(feature.join("untracked.txt"), "new file").unwrap();

    // 2. Modify tracked file without staging (!)
    std::fs::write(feature.join("file-a.txt"), "modified content").unwrap();

    // 3. Stage some changes (+)
    std::fs::write(feature.join("file-b.txt"), "staged changes").unwrap();
    repo.run_git_in(&feature, &["add", "file-b.txt"]);

    // 4. Rename a file and stage it (»)
    repo.run_git_in(&feature, &["mv", "file-c.txt", "renamed-c.txt"]);

    // 5. Delete a file in index (✘)
    repo.run_git_in(&feature, &["rm", "file-d.txt"]);

    // Result should show: ?!+»✘
    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

#[rstest]
fn test_list_maximum_status_with_git_operation(mut repo: TestRepo) {
    // Test maximum status symbols including git operation (rebase/merge):
    // ?!+ (working_tree) + = (conflicts) + ↻ (rebase) + ↕ (diverged) + ⊠ (locked) + 🤖 (user marker)
    // This pushes the Status column to ~10-11 chars of actual content

    // Create initial commit with a file that will conflict
    std::fs::write(
        repo.root_path().join("conflict.txt"),
        "original line 1\noriginal line 2\n",
    )
    .unwrap();
    std::fs::write(repo.root_path().join("shared.txt"), "shared content").unwrap();
    repo.commit("Initial commit");

    // Create feature worktree
    let feature = repo.add_worktree("feature");

    // Feature makes changes
    std::fs::write(
        feature.join("conflict.txt"),
        "feature line 1\nfeature line 2\n",
    )
    .unwrap();
    std::fs::write(feature.join("feature.txt"), "feature-specific content").unwrap();
    repo.run_git_in(&feature, &["add", "."]);
    repo.run_git_in(&feature, &["commit", "-m", "Feature changes"]);

    // Main makes conflicting changes
    std::fs::write(
        repo.root_path().join("conflict.txt"),
        "main line 1\nmain line 2\n",
    )
    .unwrap();
    std::fs::write(repo.root_path().join("main-only.txt"), "main content").unwrap();
    repo.run_git(&["add", "."]);
    repo.run_git(&["commit", "-m", "Main conflicting changes"]);

    // Start rebase which will create conflicts and git operation state
    let rebase_output = repo
        .git_command()
        .args(["rebase", "main"])
        .current_dir(&feature)
        .run()
        .unwrap();

    // Rebase should fail with conflicts - verify we're in rebase state
    assert!(
        !rebase_output.status.success(),
        "Rebase should fail with conflicts"
    );

    // Now add working tree symbols while in rebase state
    // 1. Untracked file (?)
    std::fs::write(feature.join("untracked.txt"), "untracked during rebase").unwrap();

    // 2. Modified file (!) - modify a non-conflicting file
    std::fs::write(feature.join("feature.txt"), "modified during rebase").unwrap();

    // 3. Staged file (+) - stage the conflict resolution
    std::fs::write(feature.join("new-staged.txt"), "staged during rebase").unwrap();
    repo.run_git_in(&feature, &["add", "new-staged.txt"]);

    // Lock the worktree (⊠)
    repo.run_git(&["worktree", "lock", feature.to_str().unwrap()]);

    // Set user marker emoji (🤖)
    repo.set_marker("feature", "🤖");

    // Result should show: ?!+ (working_tree) + = (conflicts) + ↻ (rebase) + ↕ (diverged) + ⊠ (locked) + 🤖 (user marker)
    // Use --full to enable conflict detection
    assert_cmd_snapshot!("maximum_status_with_git_operation", {
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--full");
        cmd
    });
}

#[rstest]
fn test_list_maximum_status_symbols(mut repo: TestRepo) {
    // Test the maximum status symbols possible:
    // ?!+»✘ (5) + ⚠ (1) + ⊠ (1) + ↕ (1) + ⇅ (1) + 🤖 (2) = 11 chars
    // Missing: ✖ (actual conflicts), ↻ (git operation - can't have with divergence), ◇ (bare), ⚠ (prunable)

    // Create initial commit on main with shared files
    std::fs::write(repo.root_path().join("shared.txt"), "original").unwrap();
    std::fs::write(repo.root_path().join("file-a.txt"), "a").unwrap();
    std::fs::write(repo.root_path().join("file-b.txt"), "b").unwrap();
    std::fs::write(repo.root_path().join("file-c.txt"), "c").unwrap();
    std::fs::write(repo.root_path().join("file-d.txt"), "d").unwrap();
    repo.commit("Initial commit");

    // Create feature worktree
    let feature = repo.add_worktree("feature");

    // Make feature diverge from main (ahead) with conflicting change
    std::fs::write(feature.join("shared.txt"), "feature version").unwrap();
    std::fs::write(feature.join("feature.txt"), "feature content").unwrap();
    repo.run_git_in(&feature, &["add", "."]);
    repo.run_git_in(&feature, &["commit", "-m", "Feature work"]);

    // Create a real bare remote so upstream exists, but keep all graph crafting local for determinism
    repo.setup_remote("main");

    // Remember the shared base (Feature work)
    let base_sha = {
        let output = repo
            .git_command()
            .args(["rev-parse", "HEAD"])
            .current_dir(&feature)
            .run()
            .unwrap();
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    };

    // Remote-only commit
    std::fs::write(feature.join("remote-file.txt"), "remote content").unwrap();
    repo.git_command()
        .args(["add", "remote-file.txt"])
        .current_dir(&feature)
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Remote commit"])
        .current_dir(&feature)
        .run()
        .unwrap();
    let remote_sha = {
        let output = repo
            .git_command()
            .args(["rev-parse", "HEAD"])
            .current_dir(&feature)
            .run()
            .unwrap();
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    };

    // Reset back to base so the remote commit is not in the local branch history
    repo.git_command()
        .args(["reset", "--hard", &base_sha])
        .current_dir(&feature)
        .run()
        .unwrap();

    // Local-only commit (divergence on the local side)
    std::fs::write(feature.join("local-file.txt"), "local content").unwrap();
    repo.git_command()
        .args(["add", "local-file.txt"])
        .current_dir(&feature)
        .run()
        .unwrap();
    repo.git_command()
        .args(["commit", "-m", "Local commit"])
        .current_dir(&feature)
        .run()
        .unwrap();

    // Wire up upstream tracking deterministically: point origin/feature at the remote-only commit
    repo.git_command()
        .args(["update-ref", "refs/remotes/origin/feature", &remote_sha])
        .current_dir(&feature)
        .run()
        .unwrap();
    repo.git_command()
        .args(["branch", "--set-upstream-to=origin/feature", "feature"])
        .current_dir(&feature)
        .run()
        .unwrap();

    // Make main advance with conflicting change (so feature is behind with conflicts)
    std::fs::write(repo.root_path().join("shared.txt"), "main version").unwrap();
    std::fs::write(repo.root_path().join("main2.txt"), "more main").unwrap();
    repo.run_git(&["add", "."]);
    repo.run_git(&["commit", "-m", "Main advances"]);

    // Add all 5 working tree symbol types (without rebase, so we keep divergence)
    // 1. Untracked (?)
    std::fs::write(feature.join("untracked.txt"), "untracked").unwrap();

    // 2. Modified (!)
    std::fs::write(feature.join("feature.txt"), "modified").unwrap();

    // 3. Staged (+)
    std::fs::write(feature.join("new-staged.txt"), "staged content").unwrap();
    repo.run_git_in(&feature, &["add", "new-staged.txt"]);

    // 4. Renamed (»)
    repo.run_git_in(&feature, &["mv", "file-c.txt", "renamed-c.txt"]);

    // 5. Deleted (✘)
    repo.run_git_in(&feature, &["rm", "file-d.txt"]);

    // Lock the worktree (⊠)
    repo.run_git(&["worktree", "lock", feature.to_str().unwrap()]);

    // Set user marker emoji (🤖)
    repo.set_marker("feature", "🤖");

    // Result should show 11 chars: ?!+»✘=⊠↕⇅🤖
    assert_cmd_snapshot!("maximum_status_symbols", {
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--full");
        cmd
    });
}

///
/// This specifically tests the WorkingTreeConflicts task which:
/// 1. Uses `git write-tree` to snapshot the index (with temp index for unstaged/untracked)
/// 2. Runs merge-tree against the default branch to detect conflicts
///
/// Both kinds of conflicts are checked in both `wt list` and `wt list --full`:
/// - Commit-level: HEAD conflicts with main
/// - Working tree: uncommitted changes conflict with main
#[rstest]
fn test_list_working_tree_conflicts(mut repo: TestRepo) {
    // Create initial commit with a shared file
    std::fs::write(repo.root_path().join("shared.txt"), "original content").unwrap();
    repo.commit("Initial commit");

    // Create feature worktree - at this point feature and main are identical
    let feature = repo.add_worktree("feature");

    // Advance main with a change to the shared file
    std::fs::write(repo.root_path().join("shared.txt"), "main's version").unwrap();
    repo.commit("Main changes shared.txt");

    // Feature's HEAD is still at the original commit - no commit-level conflict
    // because feature hasn't committed anything that conflicts

    // Now add uncommitted changes to feature that would conflict with main
    std::fs::write(feature.join("shared.txt"), "feature's uncommitted version").unwrap();

    // Without --full: WorkingTreeConflicts runs and detects the uncommitted conflict.
    assert_cmd_snapshot!(
        "working_tree_conflicts_without_full",
        list_snapshots::command(&repo, repo.root_path())
    );

    // With --full: same conflict detection, plus the wide status column and extra
    // post-skeleton tasks that non-full mode skips.
    assert_cmd_snapshot!("working_tree_conflicts_with_full", {
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--full");
        cmd
    });
}

///
/// Even with --full, if the working tree is clean, we skip the working-tree check
/// and just use the commit-level conflict detection.
#[rstest]
fn test_list_full_clean_working_tree_uses_commit_conflicts(mut repo: TestRepo) {
    // Create initial commit with a shared file
    std::fs::write(repo.root_path().join("shared.txt"), "original content").unwrap();
    repo.commit("Initial commit");

    // Create feature worktree
    let feature = repo.add_worktree("feature");

    // Make a conflicting commit on feature (different change to shared.txt)
    std::fs::write(feature.join("shared.txt"), "feature's committed version").unwrap();
    repo.run_git_in(&feature, &["add", "."]);
    repo.run_git_in(&feature, &["commit", "-m", "Feature changes shared.txt"]);

    // Advance main with a different change to the shared file
    std::fs::write(repo.root_path().join("shared.txt"), "main's version").unwrap();
    repo.commit("Main changes shared.txt");

    // Feature has a committed conflict, working tree is clean
    // Both with and without --full should show the conflict symbol
    assert_cmd_snapshot!(
        "commit_conflicts_without_full",
        list_snapshots::command(&repo, repo.root_path())
    );
    assert_cmd_snapshot!("commit_conflicts_with_full", {
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--full");
        cmd
    });
}

#[rstest]
fn test_list_warns_when_default_branch_missing_worktree(repo: TestRepo) {
    // Move primary worktree off the default branch so no worktree holds it
    repo.switch_primary_to("develop");

    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

///
/// Corrupts a branch ref to point to a non-existent commit, which causes
/// ahead_behind and other git operations to fail. Verifies the warning
/// message appears after the table.
#[rstest]
fn test_list_shows_warning_on_git_error(mut repo: TestRepo) {
    repo.add_worktree("feature");

    // Corrupt the feature branch ref to point to a non-existent commit.
    // Branch refs are stored in the main repo's .git/refs/heads, not the worktree.
    let git_dir = repo.root_path().join(".git");
    let ref_path = git_dir.join("refs/heads/feature");

    // Write an invalid SHA that doesn't exist in the repo
    std::fs::write(&ref_path, "0000000000000000000000000000000000000000\n").unwrap();

    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

///
/// Creates a true orphan branch using `git checkout --orphan` which has no merge base
/// with main. Verifies no error warning appears and the branch shows as unmerged.
#[rstest]
fn test_list_handles_orphan_branch(repo: TestRepo) {
    // Create an orphan branch (no common ancestor with main)
    repo.git_command()
        .args(["checkout", "--orphan", "assets"])
        .run()
        .unwrap();

    // Clear working tree and create new content
    repo.git_command().args(["rm", "-rf", "."]).run().unwrap();
    std::fs::write(repo.root_path().join("asset.txt"), "asset content\n").unwrap();
    repo.git_command().args(["add", "."]).run().unwrap();
    repo.git_command()
        .args(["commit", "-m", "Add asset"])
        .run()
        .unwrap();

    // Go back to main
    repo.git_command().args(["checkout", "main"]).run().unwrap();

    // Verify no merge base exists (this confirms we have a true orphan branch)
    let output = repo
        .git_command()
        .args(["merge-base", "main", "assets"])
        .run()
        .unwrap();
    assert!(
        !output.status.success(),
        "Expected no merge base for orphan branch"
    );

    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--branches");
        cmd
    });
}

///
/// When a worktree directory is deleted but git still knows about it, the worktree
/// is marked as "prunable". We should skip git operations for these worktrees
/// rather than showing confusing "Failed to execute" errors.
#[rstest]
fn test_list_skips_operations_for_prunable_worktrees(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature");

    // Delete the worktree directory (making it prunable)
    std::fs::remove_dir_all(&worktree_path).unwrap();

    // Verify git sees it as prunable
    let output = repo
        .git_command()
        .args(["worktree", "list", "--porcelain"])
        .run()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("prunable"),
        "Expected worktree to be prunable after deleting directory"
    );

    // wt list should show the prunable worktree with ⊟ symbol but NO error warnings
    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

/// Tests that wt list works correctly when the configured default branch doesn't exist.
///
/// When a user sets `wt config state default-branch set develop` but the `develop`
/// branch doesn't exist locally, `wt list` degrades gracefully — columns needing
/// default branch show empty cells rather than failing with git errors.
///
/// With `--branches`, the opportunistic stale-default check surfaces a
/// warning using the already-enumerated branch set (no extra fork). Plain
/// `wt list` (worktrees only) does not have the full branch set and so does
/// not emit the warning — the user sees a clearer `StaleDefaultBranch`
/// error the moment they run a default-branch-consuming command.
#[rstest]
fn test_list_with_nonexistent_default_branch(repo: TestRepo) {
    // Set default branch to a non-existent branch
    repo.run_git(&["config", "worktrunk.default-branch", "nonexistent"]);

    // wt list should degrade gracefully (empty columns for main-related data)
    // when configured default branch doesn't exist locally
    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

/// Tests that wt list --full works correctly when the configured default branch doesn't exist.
///
/// The --full flag enables expensive tasks like BranchDiff.
/// These should also degrade gracefully when default_branch is None.
#[rstest]
fn test_list_full_with_nonexistent_default_branch(repo: TestRepo) {
    // Set default branch to a non-existent branch
    repo.run_git(&["config", "worktrunk.default-branch", "nonexistent"]);

    // wt list --full should also work, with expensive tasks returning defaults
    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--full");
        cmd
    });
}

/// With `--branches`, `wt list` emits the stale-default-branch warning via
/// the already-enumerated branch set — no extra fork.
#[rstest]
fn test_list_branches_with_nonexistent_default_branch(repo: TestRepo) {
    repo.run_git(&["config", "worktrunk.default-branch", "nonexistent"]);

    assert_cmd_snapshot!({
        let mut cmd = list_snapshots::command(&repo, repo.root_path());
        cmd.arg("--branches");
        cmd
    });
}

/// Tests that the current worktree indicator (@) is correct for nested worktrees.
///
/// When worktrees are placed inside other worktrees (e.g., `.worktrees/` layout),
/// the current detection must use git rev-parse --show-toplevel to correctly identify
/// which worktree contains the cwd, rather than prefix matching which would match
/// the parent worktree first.
///
/// Regression test for: prefix matching with starts_with would incorrectly match
/// the main worktree when running from a nested worktree.
#[rstest]
fn test_list_nested_worktree_current_indicator(mut repo: TestRepo) {
    // Create a worktree nested inside the main repo (like .worktrees/ layout)
    let nested_path = repo.root_path().join(".worktrees").join("feature");
    let nested_worktree = repo.add_worktree_at_path("feature", &nested_path);

    // Run wt list from inside the nested worktree
    // The @ indicator should appear on "feature", not on "main"
    assert_cmd_snapshot!(list_snapshots::command(&repo, &nested_worktree));
}

/// Tests JSON output for nested worktrees shows is_current on the correct worktree.
#[rstest]
fn test_list_nested_worktree_json_is_current(mut repo: TestRepo) {
    // Create a worktree nested inside the main repo
    let nested_path = repo.root_path().join(".worktrees").join("feature");
    let nested_worktree = repo.add_worktree_at_path("feature", &nested_path);

    // Run wt list --format=json from inside the nested worktree
    let output = repo
        .wt_command()
        .current_dir(&nested_worktree)
        .args(["list", "--format=json"])
        .output()
        .unwrap();

    let json: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();

    // Find the worktree entries
    let main_wt = json.iter().find(|w| w["branch"] == "main").unwrap();
    let feature_wt = json.iter().find(|w| w["branch"] == "feature").unwrap();

    // feature should be current, main should not
    assert_eq!(
        feature_wt["is_current"], true,
        "Nested worktree 'feature' should be marked as current"
    );
    assert_eq!(
        main_wt["is_current"], false,
        "Parent worktree 'main' should NOT be marked as current"
    );
}

/// Tests that `wt list` handles a freshly `git init`-ed repo with no commits.
///
/// Empty repos have the null OID for HEAD and no branches. Without proper handling,
/// this causes task failures (git operations on null OID), garbage data (00000000, 56y),
/// and spurious "default branch does not exist locally" warnings.
#[test]
fn test_list_empty_repo() {
    let repo = TestRepo::empty();
    let guard =
        setup_snapshot_settings_for_paths(repo.root_path(), &repo.worktrees).bind_to_scope();
    std::mem::forget(guard);
    // Pre-set default branch so the unborn-HEAD case has something to resolve to
    repo.run_git(&["config", "worktrunk.default-branch", "main"]);
    // Should show the branch with empty commit columns and no errors
    assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}

/// Tests JSON output for an empty repo (no commits).
#[test]
fn test_list_empty_repo_json() {
    let repo = TestRepo::empty();
    let output = repo
        .wt_command()
        .args(["list", "--format=json"])
        .current_dir(repo.root_path())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "wt list --format=json should succeed"
    );
    let json: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json.len(), 1, "Should have one worktree entry");

    let item = &json[0];
    assert_eq!(item["branch"], "main");
    assert_eq!(item["commit"]["sha"], "");
    assert_eq!(item["commit"]["short_sha"], "");
}