worktrunk 0.37.1

A CLI for Git worktree management, designed for parallel AI agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
use super::*;
use crate::config::HooksConfig;
use crate::git::HookType;
use crate::testing::TestRepo;

fn test_repo() -> TestRepo {
    TestRepo::new()
}

#[test]
fn test_default_config_path_returns_platform_path() {
    // default_config_path() returns the platform-specific path without
    // CLI or env var overrides. Verify it returns a valid path.
    let path = default_config_path();
    assert!(path.is_some(), "default_config_path should return Some");
    let path = path.unwrap();
    assert!(
        path.ends_with("worktrunk/config.toml") || path.ends_with(r"worktrunk\config.toml"),
        "Expected path ending in worktrunk/config.toml, got: {path:?}"
    );
}

#[test]
fn test_config_path_falls_through_to_default() {
    // When no CLI override or WORKTRUNK_CONFIG_PATH env var is set,
    // config_path() should fall through to default_config_path().
    // This also verifies both functions return the same path.
    let default = default_config_path().unwrap();
    let resolved = config_path().unwrap();
    assert_eq!(
        resolved, default,
        "config_path() should match default_config_path() when no overrides are set"
    );
}

#[test]
fn test_compute_unknown_tree_empty() {
    // Valid config with no unknown keys
    let content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch }}"
"#;
    let tree = crate::config::compute_unknown_tree::<UserConfig>(content)
        .warn_tree()
        .cloned()
        .unwrap();
    assert!(tree.is_empty(), "expected no unknowns, got {tree:?}");
}

#[test]
fn test_compute_unknown_tree_with_unknown() {
    // Config with unknown top-level keys
    let content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch }}"
unknown-key = "value"
another-unknown = 42
"#;
    let tree = crate::config::compute_unknown_tree::<UserConfig>(content)
        .warn_tree()
        .cloned()
        .unwrap();
    assert!(tree.keys.contains("unknown-key"));
    assert!(tree.keys.contains("another-unknown"));
}

#[test]
fn test_compute_unknown_tree_known_sections() {
    // All known sections should not be reported
    let content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch }}"

[list]
full = true

[commit]
stage = "all"

[commit.generation]
command = "llm"

[merge]
squash = true

[step.copy-ignored]
exclude = [".conductor/"]

[post-create]
run = "npm install"

[post-start]
run = "npm run build"

[post-switch]
rename-tab = "echo 'switched'"
"#;
    let tree = crate::config::compute_unknown_tree::<UserConfig>(content)
        .warn_tree()
        .cloned()
        .unwrap();
    assert!(tree.is_empty());
}

#[test]
fn test_commit_generation_config_is_configured_empty() {
    let config = CommitGenerationConfig::default();
    assert!(!config.is_configured());
}

#[test]
fn test_commit_generation_config_is_configured_with_command() {
    let config = CommitGenerationConfig {
        command: Some("llm".to_string()),
        ..Default::default()
    };
    assert!(config.is_configured());
}

#[test]
fn test_commit_generation_config_is_configured_with_whitespace_only() {
    let config = CommitGenerationConfig {
        command: Some("   ".to_string()),
        ..Default::default()
    };
    assert!(!config.is_configured());
}

#[test]
fn test_commit_generation_config_is_configured_with_empty_string() {
    let config = CommitGenerationConfig {
        command: Some("".to_string()),
        ..Default::default()
    };
    assert!(!config.is_configured());
}

#[test]
fn test_stage_mode_default() {
    assert_eq!(StageMode::default(), StageMode::All);
}

#[test]
fn test_stage_mode_serde() {
    // Test serialization
    let all_json = serde_json::to_string(&StageMode::All).unwrap();
    assert_eq!(all_json, "\"all\"");

    let tracked_json = serde_json::to_string(&StageMode::Tracked).unwrap();
    assert_eq!(tracked_json, "\"tracked\"");

    let none_json = serde_json::to_string(&StageMode::None).unwrap();
    assert_eq!(none_json, "\"none\"");

    // Test deserialization
    let all: StageMode = serde_json::from_str("\"all\"").unwrap();
    assert_eq!(all, StageMode::All);

    let tracked: StageMode = serde_json::from_str("\"tracked\"").unwrap();
    assert_eq!(tracked, StageMode::Tracked);

    let none: StageMode = serde_json::from_str("\"none\"").unwrap();
    assert_eq!(none, StageMode::None);
}

#[test]
fn test_user_project_config_default() {
    let config = UserProjectOverrides::default();
    assert!(config.worktree_path.is_none());
    assert!(config.approved_commands.is_empty());
}

#[test]
fn test_user_project_config_with_worktree_path_serde() {
    let config = UserProjectOverrides {
        worktree_path: Some(".worktrees/{{ branch | sanitize }}".to_string()),
        approved_commands: vec!["npm install".to_string()],
        ..Default::default()
    };
    let toml = toml::to_string(&config).unwrap();
    insta::assert_snapshot!(toml, @r#"
    approved-commands = ["npm install"]
    worktree-path = ".worktrees/{{ branch | sanitize }}"
    "#);

    let parsed: UserProjectOverrides = toml::from_str(&toml).unwrap();
    assert_eq!(
        parsed.worktree_path,
        Some(".worktrees/{{ branch | sanitize }}".to_string())
    );
    assert_eq!(parsed.approved_commands, vec!["npm install".to_string()]);
}

#[test]
fn test_worktree_path_for_project_uses_project_specific() {
    let mut config = UserConfig::default();
    config.projects.insert(
        "github.com/user/repo".to_string(),
        UserProjectOverrides {
            worktree_path: Some(".worktrees/{{ branch | sanitize }}".to_string()),
            ..Default::default()
        },
    );

    // Project-specific path should be used
    assert_eq!(
        config.worktree_path_for_project("github.com/user/repo"),
        ".worktrees/{{ branch | sanitize }}"
    );
}

#[test]
fn test_worktree_path_for_project_falls_back_to_global() {
    let mut config = UserConfig {
        worktree_path: Some("../{{ repo }}-{{ branch | sanitize }}".to_string()),
        ..Default::default()
    };
    config.projects.insert(
        "github.com/user/repo".to_string(),
        UserProjectOverrides {
            worktree_path: None, // No project-specific path
            approved_commands: vec!["npm install".to_string()],
            ..Default::default()
        },
    );

    // Should fall back to global worktree-path
    assert_eq!(
        config.worktree_path_for_project("github.com/user/repo"),
        "../{{ repo }}-{{ branch | sanitize }}"
    );
}

#[test]
fn test_worktree_path_for_project_falls_back_to_default() {
    let config = UserConfig::default();

    // Unknown project should fall back to default template
    assert_eq!(
        config.worktree_path_for_project("github.com/unknown/project"),
        "{{ repo_path }}/../{{ repo }}.{{ branch | sanitize }}"
    );
}

#[test]
fn test_format_path_with_project_override() {
    let test = test_repo();
    let mut config = UserConfig {
        worktree_path: Some("../{{ repo }}.{{ branch | sanitize }}".to_string()),
        ..Default::default()
    };
    config.projects.insert(
        "github.com/user/repo".to_string(),
        UserProjectOverrides {
            worktree_path: Some(".worktrees/{{ branch | sanitize }}".to_string()),
            ..Default::default()
        },
    );

    // With project identifier, should use project-specific template
    let path = config
        .format_path(
            "myrepo",
            "feature/branch",
            &test.repo,
            Some("github.com/user/repo"),
        )
        .unwrap();
    assert_eq!(path, ".worktrees/feature-branch");

    // Without project identifier, should use global template
    let path = config
        .format_path("myrepo", "feature/branch", &test.repo, None)
        .unwrap();
    assert_eq!(path, "../myrepo.feature-branch");
}

#[test]
fn test_list_config_serde() {
    let config = ListConfig {
        full: Some(true),
        branches: Some(false),
        remotes: None,
        summary: None,
        task_timeout_ms: Some(500),
        timeout_ms: None,
    };
    let json = serde_json::to_string(&config).unwrap();
    let parsed: ListConfig = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed.full, Some(true));
    assert_eq!(parsed.branches, Some(false));
    assert_eq!(parsed.remotes, None);
    assert_eq!(parsed.summary, None);
    assert_eq!(parsed.task_timeout_ms, Some(500));
    assert_eq!(parsed.timeout_ms, None);
}

#[test]
fn test_commit_config_default() {
    let config = CommitConfig::default();
    assert!(config.stage.is_none());
}

#[test]
fn test_worktrunk_config_default() {
    let config = UserConfig::default();
    // worktree_path is None by default, but the getter returns the default
    assert!(config.worktree_path.is_none());
    assert_eq!(
        config.worktree_path(),
        "{{ repo_path }}/../{{ repo }}.{{ branch | sanitize }}"
    );
    assert!(config.projects.is_empty());
    assert_eq!(config.list, ListConfig::default());
    assert_eq!(config.commit, CommitConfig::default());
    assert_eq!(config.merge, MergeConfig::default());
    assert!(!config.skip_shell_integration_prompt);
}

#[test]
fn test_worktrunk_config_format_path() {
    let test = test_repo();
    let config = UserConfig::default();
    let path = config
        .format_path("myrepo", "feature/branch", &test.repo, None)
        .unwrap();
    // Default path is now absolute: {{ repo_path }}/../{{ repo }}.{{ branch | sanitize }}
    // The template uses forward slashes which work on all platforms
    // Check that the path contains the expected components
    assert!(
        path.contains("myrepo.feature-branch"),
        "Expected path containing 'myrepo.feature-branch', got: {path}"
    );
    // Verify it contains parent directory navigation
    assert!(
        path.contains("/..") || path.contains(r"\.."),
        "Expected path containing parent navigation, got: {path}"
    );
    // The path should start with the repo path (absolute)
    let repo_path = test.repo.repo_path().unwrap().to_string_lossy();
    assert!(
        path.starts_with(repo_path.as_ref()),
        "Expected path starting with repo path '{repo_path}', got: {path}"
    );
}

#[test]
fn test_worktrunk_config_format_path_custom_template() {
    let test = test_repo();
    let config = UserConfig {
        worktree_path: Some(".worktrees/{{ branch }}".to_string()),
        ..Default::default()
    };
    let path = config
        .format_path("myrepo", "feature", &test.repo, None)
        .unwrap();
    assert_eq!(path, ".worktrees/feature");
}

#[test]
fn test_worktrunk_config_format_path_repo_path_variable() {
    let test = test_repo();
    let config = UserConfig {
        // Use forward slashes in template (works on all platforms)
        worktree_path: Some("{{ repo_path }}/worktrees/{{ branch | sanitize }}".to_string()),
        ..Default::default()
    };
    let path = config
        .format_path("myrepo", "feature/branch", &test.repo, None)
        .unwrap();
    // Path should contain the expected components
    assert!(
        path.contains("worktrees") && path.contains("feature-branch"),
        "Expected path containing 'worktrees' and 'feature-branch', got: {path}"
    );
    // The path should start with the repo path
    let repo_path = test.repo.repo_path().unwrap().to_string_lossy();
    assert!(
        path.starts_with(repo_path.as_ref()),
        "Expected path starting with repo path '{repo_path}', got: {path}"
    );
    // The path should be absolute since repo_path is absolute
    assert!(
        std::path::Path::new(&path).is_absolute() || path.starts_with('/'),
        "Expected absolute path, got: {path}"
    );
}

#[test]
fn test_worktrunk_config_format_path_tilde_expansion() {
    let test = test_repo();
    let config = UserConfig {
        worktree_path: Some("~/worktrees/{{ repo }}/{{ branch | sanitize }}".to_string()),
        ..Default::default()
    };
    let path = config
        .format_path("myrepo", "feature/branch", &test.repo, None)
        .unwrap();
    // Tilde should be expanded to home directory
    assert!(
        !path.starts_with('~'),
        "Tilde should be expanded, got: {path}"
    );
    // Path should contain expected components
    assert!(
        path.contains("worktrees") && path.contains("myrepo") && path.contains("feature-branch"),
        "Expected path containing 'worktrees/myrepo/feature-branch', got: {path}"
    );
    // Path should be absolute after tilde expansion
    assert!(
        std::path::Path::new(&path).is_absolute(),
        "Expected absolute path after tilde expansion, got: {path}"
    );
}

#[test]
fn test_worktrunk_config_format_path_owner_variable() {
    let mut test = TestRepo::with_initial_commit();
    test.setup_remote("main");
    test.run_git(&[
        "remote",
        "set-url",
        "origin",
        "git@github.com:max-sixty/worktrunk.git",
    ]);

    let config = UserConfig {
        worktree_path: Some("{{ owner }}/{{ repo }}/{{ branch }}".to_string()),
        ..Default::default()
    };

    let path = config
        .format_path("myrepo", "feature/branch", &test.repo, None)
        .unwrap();

    assert_eq!(path, "max-sixty/myrepo/feature/branch");
}

#[test]
fn test_worktrunk_config_format_path_owner_uses_full_namespace() {
    let mut test = TestRepo::with_initial_commit();
    test.setup_remote("main");
    test.run_git(&[
        "remote",
        "set-url",
        "origin",
        "git@gitlab.com:group/subgroup/project.git",
    ]);

    let config = UserConfig {
        worktree_path: Some("{{ owner }}/{{ repo }}/{{ branch }}".to_string()),
        ..Default::default()
    };

    let path = config
        .format_path("myrepo", "feature/branch", &test.repo, None)
        .unwrap();

    assert_eq!(path, "group/subgroup/myrepo/feature/branch");
}

#[test]
fn test_merge_config_serde() {
    let config = MergeConfig {
        squash: Some(true),
        commit: Some(true),
        rebase: Some(false),
        remove: Some(true),
        verify: Some(true),
        ff: None,
    };
    let json = serde_json::to_string(&config).unwrap();
    let parsed: MergeConfig = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed.squash, Some(true));
    assert_eq!(parsed.rebase, Some(false));
}

#[test]
fn test_skip_shell_integration_prompt_default_false() {
    let config = UserConfig::default();
    assert!(!config.skip_shell_integration_prompt);
}

#[test]
fn test_skip_shell_integration_prompt_serde_roundtrip() {
    // Test serialization when true
    let config = UserConfig {
        skip_shell_integration_prompt: true,
        ..UserConfig::default()
    };
    let toml = toml::to_string(&config).unwrap();
    assert!(toml.contains("skip-shell-integration-prompt = true"));

    // Test deserialization
    let parsed: UserConfig = toml::from_str(&toml).unwrap();
    assert!(parsed.skip_shell_integration_prompt);
}

#[test]
fn test_skip_shell_integration_prompt_skipped_when_false() {
    // When false, the field should not appear in serialized output
    let config = UserConfig::default();
    let toml = toml::to_string(&config).unwrap();
    assert!(!toml.contains("skip-shell-integration-prompt"));
}

#[test]
fn test_skip_shell_integration_prompt_parsed_from_toml() {
    let content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch }}"
skip-shell-integration-prompt = true
"#;
    let config: UserConfig = toml::from_str(content).unwrap();
    assert!(config.skip_shell_integration_prompt);
}

#[test]
fn test_skip_shell_integration_prompt_defaults_when_missing() {
    let content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch }}"
"#;
    let config: UserConfig = toml::from_str(content).unwrap();
    assert!(!config.skip_shell_integration_prompt);
}

#[test]
fn test_set_project_worktree_path() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(&config_path, "# empty config\n").unwrap();

    let mut config = UserConfig::default();
    config
        .set_project_worktree_path(
            "github.com/user/repo",
            "../{{ branch | sanitize }}".to_string(),
            Some(&config_path),
        )
        .unwrap();

    assert_eq!(
        config.worktree_path_for_project("github.com/user/repo"),
        "../{{ branch | sanitize }}"
    );

    // Verify it was saved to disk
    let content = std::fs::read_to_string(&config_path).unwrap();
    assert!(content.contains("[projects.\"github.com/user/repo\"]"));
    assert!(content.contains("worktree-path"));
}

// =========================================================================
// Merge trait tests
// =========================================================================

#[test]
fn test_merge_list_config() {
    let base = ListConfig {
        full: Some(true),
        branches: Some(false),
        remotes: None,
        summary: Some(true),
        task_timeout_ms: Some(1000),
        timeout_ms: Some(2000),
    };
    let override_config = ListConfig {
        full: None,            // Should fall back to base
        branches: Some(true),  // Should override
        remotes: Some(true),   // Should override (base was None)
        summary: None,         // Should fall back to base
        task_timeout_ms: None, // Should fall back to base
        timeout_ms: None,      // Should fall back to base
    };

    let merged = base.merge_with(&override_config);
    assert_eq!(merged.full, Some(true)); // From base
    assert_eq!(merged.branches, Some(true)); // From override
    assert_eq!(merged.remotes, Some(true)); // From override
    assert_eq!(merged.summary, Some(true)); // From base
    assert_eq!(merged.task_timeout_ms, Some(1000)); // From base
    assert_eq!(merged.timeout_ms, Some(2000)); // From base
}

#[test]
fn test_merge_commit_config() {
    let base = CommitConfig {
        stage: Some(StageMode::All),
        generation: None,
    };
    let override_config = CommitConfig {
        stage: Some(StageMode::Tracked),
        generation: None,
    };

    let merged = base.merge_with(&override_config);
    assert_eq!(merged.stage, Some(StageMode::Tracked));
}

#[test]
fn test_merge_commit_config_generation_base_only() {
    // Base has generation, override doesn't - use base
    let base = CommitConfig {
        stage: None,
        generation: Some(CommitGenerationConfig {
            command: Some("base-llm".to_string()),
            ..Default::default()
        }),
    };
    let override_config = CommitConfig {
        stage: None,
        generation: None,
    };

    let merged = base.merge_with(&override_config);
    assert_eq!(
        merged.generation.as_ref().unwrap().command,
        Some("base-llm".to_string())
    );
}

#[test]
fn test_merge_commit_config_generation_override_only() {
    // Override has generation, base doesn't - use override
    let base = CommitConfig {
        stage: None,
        generation: None,
    };
    let override_config = CommitConfig {
        stage: None,
        generation: Some(CommitGenerationConfig {
            command: Some("override-llm".to_string()),
            ..Default::default()
        }),
    };

    let merged = base.merge_with(&override_config);
    assert_eq!(
        merged.generation.as_ref().unwrap().command,
        Some("override-llm".to_string())
    );
}

#[test]
fn test_merge_commit_config_generation_both() {
    // Both have generation - merge them
    let base = CommitConfig {
        stage: Some(StageMode::All),
        generation: Some(CommitGenerationConfig {
            command: Some("base-llm".to_string()),
            template: Some("base-template".to_string()),
            ..Default::default()
        }),
    };
    let override_config = CommitConfig {
        stage: None, // Will use base's stage
        generation: Some(CommitGenerationConfig {
            command: Some("override-llm".to_string()), // Override command
            template: None,                            // Use base's template
            ..Default::default()
        }),
    };

    let merged = base.merge_with(&override_config);
    assert_eq!(merged.stage, Some(StageMode::All));
    let generation = merged.generation.as_ref().unwrap();
    assert_eq!(generation.command, Some("override-llm".to_string()));
    assert_eq!(generation.template, Some("base-template".to_string()));
}

#[test]
fn test_merge_merge_config() {
    let base = MergeConfig {
        squash: Some(true),
        commit: Some(true),
        rebase: Some(true),
        remove: Some(true),
        verify: Some(true),
        ff: Some(true),
    };
    let override_config = MergeConfig {
        squash: Some(false), // Override
        commit: None,        // Fall back to base
        rebase: None,        // Fall back to base
        remove: Some(false), // Override
        verify: None,        // Fall back to base
        ff: Some(false),     // Override
    };

    let merged = base.merge_with(&override_config);
    assert_eq!(merged.squash, Some(false));
    assert_eq!(merged.commit, Some(true));
    assert_eq!(merged.rebase, Some(true));
    assert_eq!(merged.remove, Some(false));
    assert_eq!(merged.verify, Some(true));
    assert_eq!(merged.ff, Some(false));
}

#[test]
fn test_merge_commit_generation_config() {
    let base = CommitGenerationConfig {
        command: Some("llm -m claude-haiku-4.5".to_string()),
        template: None,
        template_file: Some("~/.config/template.txt".to_string()),
        squash_template: None,
        squash_template_file: None,
    };
    let override_config = CommitGenerationConfig {
        command: Some("claude -p --model=haiku".to_string()), // Override
        template: Some("custom".to_string()),                 // Override (was None)
        template_file: None,                                  // Fall back to base
        squash_template: None,
        squash_template_file: None,
    };

    let merged = base.merge_with(&override_config);
    assert_eq!(merged.command, Some("claude -p --model=haiku".to_string()));
    assert_eq!(merged.template, Some("custom".to_string()));
    // When project sets template, template_file is cleared to maintain mutual exclusivity
    assert_eq!(merged.template_file, None);
}

#[test]
fn test_commit_generation_merge_mutual_exclusivity() {
    // Global has template_file, project has template
    // Merged result should only have template (project wins, clears template_file)
    let global = CommitGenerationConfig {
        template_file: Some("~/.config/template.txt".to_string()),
        ..Default::default()
    };
    let project = CommitGenerationConfig {
        template: Some("inline template".to_string()),
        ..Default::default()
    };

    let merged = global.merge_with(&project);
    assert_eq!(merged.template, Some("inline template".to_string()));
    assert_eq!(merged.template_file, None); // Cleared because project set template

    // Reverse: global has template, project has template_file
    let global = CommitGenerationConfig {
        template: Some("global template".to_string()),
        ..Default::default()
    };
    let project = CommitGenerationConfig {
        template_file: Some("project-file.txt".to_string()),
        ..Default::default()
    };

    let merged = global.merge_with(&project);
    assert_eq!(merged.template, None); // Cleared because project set template_file
    assert_eq!(merged.template_file, Some("project-file.txt".to_string()));

    // Neither set in project: inherit both from global
    let global = CommitGenerationConfig {
        template: Some("global template".to_string()),
        ..Default::default()
    };
    let project = CommitGenerationConfig::default();

    let merged = global.merge_with(&project);
    assert_eq!(merged.template, Some("global template".to_string()));
    assert_eq!(merged.template_file, None);
}

#[test]
fn test_commit_generation_merge_squash_template_mutual_exclusivity() {
    // Global has squash_template_file, project has squash_template
    // Merged result should only have squash_template (project wins)
    let global = CommitGenerationConfig {
        squash_template_file: Some("~/.config/squash.txt".to_string()),
        ..Default::default()
    };
    let project = CommitGenerationConfig {
        squash_template: Some("inline squash".to_string()),
        ..Default::default()
    };

    let merged = global.merge_with(&project);
    assert_eq!(merged.squash_template, Some("inline squash".to_string()));
    assert_eq!(merged.squash_template_file, None);

    // Reverse: global has squash_template, project has squash_template_file
    let global = CommitGenerationConfig {
        squash_template: Some("global squash".to_string()),
        ..Default::default()
    };
    let project = CommitGenerationConfig {
        squash_template_file: Some("project-squash.txt".to_string()),
        ..Default::default()
    };

    let merged = global.merge_with(&project);
    assert_eq!(merged.squash_template, None);
    assert_eq!(
        merged.squash_template_file,
        Some("project-squash.txt".to_string())
    );
}

// =========================================================================
// Effective config methods tests
// =========================================================================

#[test]
fn test_effective_commit_generation_no_project() {
    let config = UserConfig {
        commit: CommitConfig {
            stage: None,
            generation: Some(CommitGenerationConfig {
                command: Some("global-llm".to_string()),
                ..Default::default()
            }),
        },
        ..Default::default()
    };

    let effective = config.commit_generation(None);
    assert_eq!(effective.command, Some("global-llm".to_string()));
}

#[test]
fn test_effective_commit_generation_with_project_override() {
    let mut config = UserConfig {
        commit: CommitConfig {
            stage: None,
            generation: Some(CommitGenerationConfig {
                command: Some("global-llm".to_string()),
                ..Default::default()
            }),
        },
        ..Default::default()
    };

    config.projects.insert(
        "github.com/user/repo".to_string(),
        UserProjectOverrides {
            commit: CommitConfig {
                stage: None,
                generation: Some(CommitGenerationConfig {
                    command: Some("project-llm".to_string()),
                    ..Default::default()
                }),
            },
            ..Default::default()
        },
    );

    // With project identifier, should merge project config
    let effective = config.commit_generation(Some("github.com/user/repo"));
    assert_eq!(effective.command, Some("project-llm".to_string()));

    // Without project or unknown project, should use global
    let effective = config.commit_generation(None);
    assert_eq!(effective.command, Some("global-llm".to_string()));

    let effective = config.commit_generation(Some("github.com/other/repo"));
    assert_eq!(effective.command, Some("global-llm".to_string()));
}

#[test]
fn test_effective_merge_with_partial_override() {
    let mut config = UserConfig {
        merge: MergeConfig {
            squash: Some(true),
            commit: Some(true),
            rebase: Some(true),
            remove: Some(true),
            verify: Some(true),
            ff: Some(true),
        },
        ..Default::default()
    };

    config.projects.insert(
        "github.com/user/repo".to_string(),
        UserProjectOverrides {
            merge: MergeConfig {
                squash: Some(false), // Only override squash
                commit: None,
                rebase: None,
                remove: None,
                verify: None,
                ff: None,
            },
            ..Default::default()
        },
    );

    let effective = config.merge(Some("github.com/user/repo"));
    assert_eq!(effective.squash, Some(false)); // From project
    assert_eq!(effective.commit, Some(true)); // From global
    assert_eq!(effective.rebase, Some(true)); // From global
}

#[test]
fn test_effective_list_project_only() {
    // No global list config, only project config
    let mut config = UserConfig::default();
    assert_eq!(config.list, ListConfig::default());

    config.projects.insert(
        "github.com/user/repo".to_string(),
        UserProjectOverrides {
            list: ListConfig {
                full: Some(true),
                ..Default::default()
            },
            ..Default::default()
        },
    );

    let effective = config.list(Some("github.com/user/repo"));
    assert_eq!(effective.full, Some(true));
    assert!(effective.branches.is_none());

    // No global, no matching project falls back to default
    assert_eq!(
        config.list(Some("github.com/other/repo")),
        ListConfig::default()
    );
}

#[test]
fn test_effective_commit_global_only() {
    // Only global config, no project config
    let config = UserConfig {
        commit: CommitConfig {
            stage: Some(StageMode::Tracked),
            generation: None,
        },
        ..Default::default()
    };

    let effective = config.commit(Some("github.com/any/project"));
    assert_eq!(effective.stage, Some(StageMode::Tracked));
}

// =========================================================================
// Config accessor methods and ResolvedConfig tests
// =========================================================================

#[test]
fn test_list_config_accessor_methods_defaults() {
    let config = ListConfig::default();
    assert!(!config.full());
    assert!(!config.branches());
    assert!(!config.remotes());
    assert!(config.task_timeout().is_none());
    assert!(config.timeout().is_none());
}

#[test]
fn test_list_config_accessor_methods_with_values() {
    let config = ListConfig {
        full: Some(true),
        branches: Some(true),
        remotes: Some(false),
        summary: Some(true),
        task_timeout_ms: Some(5000),
        timeout_ms: Some(3000),
    };
    assert!(config.full());
    assert!(config.branches());
    assert!(!config.remotes());
    assert!(config.summary());
    assert_eq!(
        config.task_timeout(),
        Some(std::time::Duration::from_millis(5000))
    );
    assert_eq!(
        config.timeout(),
        Some(std::time::Duration::from_millis(3000))
    );
}

#[test]
fn test_merge_config_accessor_methods_defaults() {
    let config = MergeConfig::default();
    // MergeConfig defaults are all true (including ff)
    assert!(config.squash());
    assert!(config.commit());
    assert!(config.rebase());
    assert!(config.remove());
    assert!(config.verify());
    assert!(config.ff());
}

#[test]
fn test_merge_config_accessor_methods_with_values() {
    let config = MergeConfig {
        squash: Some(false),
        commit: Some(false),
        rebase: Some(false),
        remove: Some(false),
        verify: Some(false),
        ff: Some(false),
    };
    assert!(!config.squash());
    assert!(!config.commit());
    assert!(!config.rebase());
    assert!(!config.remove());
    assert!(!config.verify());
    assert!(!config.ff());
}

#[test]
fn test_deprecated_no_ff_migrated_to_ff() {
    let config = UserConfig::load_from_str("[merge]\nno-ff = true\n").unwrap();
    assert!(!config.merge.ff());
}

#[test]
fn test_deprecated_no_ff_does_not_override_explicit_ff() {
    // If both `ff` and `no-ff` are set, `ff` wins (no-ff is ignored)
    let config = UserConfig::load_from_str("[merge]\nff = true\nno-ff = true\n").unwrap();
    assert!(config.merge.ff());
}

#[test]
fn test_commit_config_accessor_methods() {
    let config = CommitConfig::default();
    assert_eq!(config.stage(), StageMode::All);

    let config = CommitConfig {
        stage: Some(StageMode::Tracked),
        generation: None,
    };
    assert_eq!(config.stage(), StageMode::Tracked);
}

// =========================================================================
// SwitchPickerConfig tests
// =========================================================================

#[test]
fn test_switch_picker_config_accessor_methods() {
    use crate::config::user::SwitchPickerConfig;

    let config = SwitchPickerConfig::default();
    assert!(config.pager().is_none());
    // Default wall-clock budget is 500ms
    assert_eq!(
        config.timeout(),
        Some(std::time::Duration::from_millis(500))
    );

    let config = SwitchPickerConfig {
        pager: Some("delta --paging=never".to_string()),
        timeout_ms: Some(1000),
    };
    assert_eq!(config.pager(), Some("delta --paging=never"));
    assert_eq!(
        config.timeout(),
        Some(std::time::Duration::from_millis(1000))
    );
}

#[test]
fn test_switch_picker_timeout_zero_disables() {
    use crate::config::user::SwitchPickerConfig;

    let config = SwitchPickerConfig {
        timeout_ms: Some(0),
        ..Default::default()
    };
    assert!(config.timeout().is_none());
}

#[test]
fn test_switch_picker_timeout_none_uses_default() {
    use crate::config::user::SwitchPickerConfig;

    let config = SwitchPickerConfig::default();
    assert_eq!(
        config.timeout(),
        Some(std::time::Duration::from_millis(500))
    );
}

#[test]
fn test_switch_picker_config_parse_toml() {
    let content = r#"
[switch.picker]
pager = "delta --paging=never"
timeout-ms = 300
"#;
    let config: UserConfig = toml::from_str(content).unwrap();
    let picker = config.switch.picker.as_ref().unwrap();
    assert_eq!(picker.pager.as_deref(), Some("delta --paging=never"));
    assert_eq!(picker.timeout_ms, Some(300));
}

#[test]
fn test_switch_picker_merge() {
    use crate::config::user::{Merge, SwitchPickerConfig};

    let base = SwitchPickerConfig {
        pager: Some("delta".to_string()),
        timeout_ms: Some(500),
    };
    let override_config = SwitchPickerConfig {
        pager: None,         // Fall back to base
        timeout_ms: Some(0), // Override: disable timeout
    };

    let merged = base.merge_with(&override_config);
    assert_eq!(merged.pager.as_deref(), Some("delta"));
    assert_eq!(merged.timeout_ms, Some(0));
}

#[test]
fn test_switch_config_merge() {
    use crate::config::user::{Merge, SwitchConfig, SwitchPickerConfig};

    // Both have picker
    let base = SwitchConfig {
        picker: Some(SwitchPickerConfig {
            pager: Some("delta".to_string()),
            timeout_ms: None,
        }),
        ..Default::default()
    };
    let other = SwitchConfig {
        picker: Some(SwitchPickerConfig {
            pager: None,
            timeout_ms: Some(300),
        }),
        ..Default::default()
    };
    let merged = base.merge_with(&other);
    assert_eq!(
        merged.picker.as_ref().unwrap().pager.as_deref(),
        Some("delta")
    );
    assert_eq!(merged.picker.as_ref().unwrap().timeout_ms, Some(300));

    // Base has picker, other doesn't
    let other_none = SwitchConfig::default();
    let merged = base.merge_with(&other_none);
    assert_eq!(
        merged.picker.as_ref().unwrap().pager.as_deref(),
        Some("delta")
    );

    // Neither has picker
    let merged = SwitchConfig::default().merge_with(&other_none);
    assert!(merged.picker.is_none());
}

#[test]
fn test_switch_config_cd_accessor() {
    use crate::config::user::SwitchConfig;

    // Default is true
    let config = SwitchConfig::default();
    assert!(config.cd());

    // Explicit true
    let config = SwitchConfig {
        cd: Some(true),
        ..Default::default()
    };
    assert!(config.cd());

    // Explicit false
    let config = SwitchConfig {
        cd: Some(false),
        ..Default::default()
    };
    assert!(!config.cd());
}

#[test]
fn test_switch_config_cd_merge() {
    use crate::config::user::{Merge, SwitchConfig};

    // Other overrides base
    let base = SwitchConfig {
        cd: Some(true),
        ..Default::default()
    };
    let other = SwitchConfig {
        cd: Some(false),
        ..Default::default()
    };
    let merged = base.merge_with(&other);
    assert!(!merged.cd());

    // Base preserved when other is None
    let base = SwitchConfig {
        cd: Some(false),
        ..Default::default()
    };
    let merged = base.merge_with(&SwitchConfig::default());
    assert!(!merged.cd());

    // Neither set
    let merged = SwitchConfig::default().merge_with(&SwitchConfig::default());
    assert!(merged.cd()); // default true
}

#[test]
fn test_switch_config_cd_from_toml() {
    let toml = r#"
[switch]
cd = false
"#;
    let config = UserConfig::load_from_str(toml).unwrap();
    let switch = config.switch(None);
    assert!(!switch.cd());
}

#[test]
fn test_switch_config_cd_resolved() {
    let toml = r#"
[switch]
cd = false
"#;
    let config = UserConfig::load_from_str(toml).unwrap();
    let resolved = config.resolved(None);
    assert!(!resolved.switch.cd());
}

#[test]
fn test_deprecated_no_cd_migrated_to_cd() {
    let config = UserConfig::load_from_str("[switch]\nno-cd = true\n").unwrap();
    assert!(!config.switch.cd());
}

#[test]
fn test_deprecated_no_cd_does_not_override_explicit_cd() {
    let config = UserConfig::load_from_str("[switch]\ncd = true\nno-cd = true\n").unwrap();
    assert!(config.switch.cd());
}

#[test]
fn test_switch_picker_fallback_from_select() {
    let config = UserConfig::load_from_str(
        r#"
[select]
pager = "bat"
"#,
    )
    .unwrap();

    let picker = config.switch_picker(None);
    assert_eq!(picker.pager.as_deref(), Some("bat"));
    // [select] is migrated to [switch.picker] at the TOML level before parsing
    assert_eq!(
        config
            .switch
            .picker
            .as_ref()
            .and_then(|picker| picker.pager.as_deref()),
        Some("bat")
    );
    // timeout_ms not available from select, so default applies
    assert_eq!(picker.timeout_ms, None);
    assert_eq!(
        picker.timeout(),
        Some(std::time::Duration::from_millis(500))
    );
}

#[test]
fn test_switch_picker_prefers_new_over_select() {
    let config = UserConfig::load_from_str(
        r#"
[switch.picker]
pager = "delta"
timeout-ms = 100

[select]
pager = "bat"
"#,
    )
    .unwrap();

    let picker = config.switch_picker(None);
    assert_eq!(picker.pager.as_deref(), Some("delta"));
    assert_eq!(picker.timeout_ms, Some(100));
}

#[test]
fn test_switch_picker_project_override() {
    use crate::config::user::{SwitchConfig, SwitchPickerConfig};

    let mut config = UserConfig {
        switch: SwitchConfig {
            picker: Some(SwitchPickerConfig {
                pager: Some("delta".to_string()),
                timeout_ms: Some(200),
            }),
            ..Default::default()
        },
        ..Default::default()
    };

    config.projects.insert(
        "github.com/user/repo".to_string(),
        UserProjectOverrides {
            switch: SwitchConfig {
                picker: Some(SwitchPickerConfig {
                    pager: Some("bat".to_string()),
                    timeout_ms: None, // Fall back to global
                }),
                ..Default::default()
            },
            ..Default::default()
        },
    );

    let picker = config.switch_picker(Some("github.com/user/repo"));
    assert_eq!(picker.pager.as_deref(), Some("bat")); // From project
    assert_eq!(picker.timeout_ms, Some(200)); // From global
}

#[test]
fn test_switch_picker_project_fallback_from_select() {
    let config = UserConfig::load_from_str(
        r#"
[switch.picker]
pager = "delta"
timeout-ms = 300

[projects."github.com/user/repo".select]
pager = "bat"
"#,
    )
    .unwrap();

    let picker = config.switch_picker(Some("github.com/user/repo"));
    assert_eq!(picker.pager.as_deref(), Some("bat"));
    assert_eq!(picker.timeout_ms, Some(300));
    // [select] is migrated to [switch.picker] at the TOML level before parsing,
    // so it ends up in the switch.picker field, not select
    assert!(
        config
            .projects
            .get("github.com/user/repo")
            .unwrap()
            .switch
            .picker
            .as_ref()
            .and_then(|p| p.pager.as_deref())
            == Some("bat")
    );
}

#[test]
fn test_resolved_config_for_project() {
    use crate::config::user::SwitchConfig;
    use crate::config::user::SwitchPickerConfig;

    let config = UserConfig {
        list: ListConfig {
            full: Some(true),
            ..Default::default()
        },
        merge: MergeConfig {
            squash: Some(false),
            ..Default::default()
        },
        commit: CommitConfig {
            stage: Some(StageMode::None),
            ..Default::default()
        },
        switch: SwitchConfig {
            picker: Some(SwitchPickerConfig {
                pager: Some("less".to_string()),
                timeout_ms: Some(300),
            }),
            ..Default::default()
        },
        ..Default::default()
    };

    let resolved = config.resolved(None);

    // Test that accessor methods work through ResolvedConfig
    assert!(resolved.list.full());
    assert!(!resolved.list.branches()); // Default
    assert!(!resolved.merge.squash()); // Overridden to false
    assert!(resolved.merge.commit()); // Default true
    assert_eq!(resolved.commit.stage(), StageMode::None);
    assert_eq!(resolved.switch_picker.pager(), Some("less"));
    assert_eq!(resolved.switch_picker.timeout_ms, Some(300));
    assert!(resolved.switch.cd()); // Default true
}

// =========================================================================
// Per-project config serde tests
// =========================================================================

#[test]
fn test_user_project_config_with_nested_configs_serde() {
    let config = UserProjectOverrides {
        approved_commands: vec!["npm install".to_string()],
        worktree_path: Some(".worktrees/{{ branch }}".to_string()),
        list: ListConfig {
            full: Some(true),
            ..Default::default()
        },
        commit: CommitConfig {
            stage: Some(StageMode::Tracked),
            generation: Some(CommitGenerationConfig {
                command: Some("llm -m gpt-4".to_string()),
                ..Default::default()
            }),
        },
        merge: MergeConfig {
            squash: Some(false),
            ..Default::default()
        },
        ..Default::default()
    };

    let toml = toml::to_string(&config).unwrap();
    let parsed: UserProjectOverrides = toml::from_str(&toml).unwrap();

    assert_eq!(
        parsed.worktree_path,
        Some(".worktrees/{{ branch }}".to_string())
    );
    assert_eq!(
        parsed.commit.generation.as_ref().unwrap().command,
        Some("llm -m gpt-4".to_string())
    );
    assert_eq!(parsed.list.full, Some(true));
    assert_eq!(parsed.commit.stage, Some(StageMode::Tracked));
    assert_eq!(parsed.merge.squash, Some(false));
}

#[test]
fn test_full_config_with_per_project_sections_serde() {
    // Test new format: [commit.generation] instead of [commit-generation]
    let content = r#"
worktree-path = "../{{ repo }}.{{ branch | sanitize }}"

[commit.generation]
command = "llm -m claude-haiku-4.5"

[projects."github.com/user/repo"]
worktree-path = ".worktrees/{{ branch | sanitize }}"
approved-commands = ["npm install"]

[projects."github.com/user/repo".commit.generation]
command = "claude -p --model opus"

[projects."github.com/user/repo".list]
full = true

[projects."github.com/user/repo".merge]
squash = false
"#;

    let config: UserConfig = toml::from_str(content).unwrap();

    // Global config
    assert_eq!(
        config.worktree_path,
        Some("../{{ repo }}.{{ branch | sanitize }}".to_string())
    );
    assert_eq!(
        config.commit.generation.as_ref().unwrap().command,
        Some("llm -m claude-haiku-4.5".to_string())
    );

    // Project config
    let project = config.projects.get("github.com/user/repo").unwrap();
    assert_eq!(
        project.worktree_path,
        Some(".worktrees/{{ branch | sanitize }}".to_string())
    );
    assert_eq!(
        project.commit.generation.as_ref().unwrap().command,
        Some("claude -p --model opus".to_string())
    );
    assert_eq!(project.list.full, Some(true));
    assert_eq!(project.merge.squash, Some(false));

    // Effective config for project
    let effective_cg = config.commit_generation(Some("github.com/user/repo"));
    assert_eq!(
        effective_cg.command,
        Some("claude -p --model opus".to_string())
    );

    let effective_merge = config.merge(Some("github.com/user/repo"));
    assert_eq!(effective_merge.squash, Some(false));
}

#[test]
fn test_copy_ignored_config_merges_global_and_project() {
    let project_id = "github.com/user/repo";
    let config = UserConfig::load_from_str(
        r#"
[step.copy-ignored]
exclude = [".conductor/", ".entire/"]

[projects."github.com/user/repo".step.copy-ignored]
exclude = [".repo-local/", ".entire/"]
"#,
    )
    .unwrap();

    let expected_global = vec![".conductor/".to_string(), ".entire/".to_string()];
    let expected_merged = vec![
        ".conductor/".to_string(),
        ".entire/".to_string(),
        ".repo-local/".to_string(),
    ];

    assert_eq!(config.copy_ignored(None).exclude, expected_global);
    assert_eq!(
        config.copy_ignored(Some(project_id)).exclude,
        expected_merged.clone()
    );
    assert_eq!(
        config
            .resolved(Some(project_id))
            .step
            .copy_ignored()
            .exclude,
        expected_merged
    );
}

#[test]
fn test_deprecated_commit_generation_migrated_on_load() {
    // [commit-generation] is migrated to [commit.generation] at the TOML level
    // before serde parsing, so it lands in configs.commit.generation
    let content = r#"
[commit-generation]
command = "llm -m claude-haiku-4.5"

[projects."github.com/user/repo".commit-generation]
command = "claude -p --model opus"
"#;

    let config = UserConfig::load_from_str(content).unwrap();

    assert_eq!(
        config
            .commit
            .generation
            .as_ref()
            .and_then(|generation| generation.command.as_deref()),
        Some("llm -m claude-haiku-4.5")
    );

    let project = config.projects.get("github.com/user/repo").unwrap();
    assert_eq!(
        project
            .commit
            .generation
            .as_ref()
            .and_then(|generation| generation.command.as_deref()),
        Some("claude -p --model opus")
    );

    let effective_cg = config.commit_generation(Some("github.com/user/repo"));
    assert_eq!(
        effective_cg.command,
        Some("claude -p --model opus".to_string())
    );
}

#[test]
fn test_deprecated_commit_generation_with_args_field() {
    // Test that old format with args field is migrated: args merged into command
    let content = r#"
[commit-generation]
command = "llm"
args = ["-m", "claude-haiku-4.5"]
"#;

    let config = UserConfig::load_from_str(content).unwrap();
    // Migration merges args into command and renames section
    assert_eq!(
        config
            .commit
            .generation
            .as_ref()
            .and_then(|g| g.command.as_deref()),
        Some("llm -m claude-haiku-4.5")
    );
}

// Validation tests

#[test]
fn test_validation_empty_worktree_path() {
    let content = r#"worktree-path = """#;
    let result = UserConfig::load_from_str(content);
    let err = result.unwrap_err().to_string();
    insta::assert_snapshot!(err, @"worktree-path cannot be empty");
}

#[test]
fn test_validation_absolute_worktree_path_allowed() {
    // Absolute paths should be allowed for worktree-path
    let content = if cfg!(windows) {
        r#"worktree-path = "C:\\worktrees\\{{ branch | sanitize }}""#
    } else {
        r#"worktree-path = "/worktrees/{{ branch | sanitize }}""#
    };
    let result = UserConfig::load_from_str(content);
    assert!(
        result.is_ok(),
        "Absolute paths should be allowed: {:?}",
        result.err()
    );
}

#[test]
fn test_validation_project_empty_worktree_path() {
    let content = r#"
[projects."github.com/user/repo"]
worktree-path = ""
"#;
    let result = UserConfig::load_from_str(content);
    let err = result.unwrap_err().to_string();
    insta::assert_snapshot!(err, @"projects.github.com/user/repo.worktree-path cannot be empty");
}

#[test]
fn test_validation_project_absolute_worktree_path_allowed() {
    // Absolute paths should be allowed for per-project worktree-path
    let content = if cfg!(windows) {
        r#"
[projects."github.com/user/repo"]
worktree-path = "C:\\worktrees\\{{ branch | sanitize }}"
"#
    } else {
        r#"
[projects."github.com/user/repo"]
worktree-path = "/worktrees/{{ branch | sanitize }}"
"#
    };
    let result = UserConfig::load_from_str(content);
    assert!(
        result.is_ok(),
        "Absolute paths should be allowed: {:?}",
        result.err()
    );
}

#[test]
fn test_validation_template_mutual_exclusivity() {
    let cases = [
        ("[commit-generation]\ntemplate = \"inline\"\ntemplate-file = \"path\""),
        ("[commit-generation]\nsquash-template = \"inline\"\nsquash-template-file = \"path\""),
        ("[projects.\"github.com/user/repo\".commit-generation]\ntemplate = \"inline\"\ntemplate-file = \"path\""),
        ("[projects.\"github.com/user/repo\".commit-generation]\nsquash-template = \"inline\"\nsquash-template-file = \"path\""),
        ("[commit.generation]\ntemplate = \"inline\"\ntemplate-file = \"path\""),
        ("[commit.generation]\nsquash-template = \"inline\"\nsquash-template-file = \"path\""),
        ("[projects.\"github.com/user/repo\".commit.generation]\ntemplate = \"inline\"\ntemplate-file = \"path\""),
        ("[projects.\"github.com/user/repo\".commit.generation]\nsquash-template = \"inline\"\nsquash-template-file = \"path\""),
    ];
    for content in cases {
        let err = UserConfig::load_from_str(content).unwrap_err().to_string();
        assert!(
            err.contains("mutually exclusive"),
            "{content}: expected 'mutually exclusive', got: {err}"
        );
    }
}

// =========================================================================
// save_to() tests
// =========================================================================

#[test]
fn test_save_to_new_file_with_commit_generation() {
    // Test that save_to() creates a new file with commit.generation section
    // This exercises the "create from scratch" branch when no existing file exists
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");

    let config = UserConfig {
        commit: CommitConfig {
            stage: None,
            generation: Some(CommitGenerationConfig {
                command: Some("llm -m haiku".to_string()),
                ..Default::default()
            }),
        },
        ..Default::default()
    };

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        saved.contains("[commit.generation]"),
        "Should use new format: {saved}"
    );
    assert!(
        saved.contains("command = \"llm -m haiku\""),
        "Should contain command: {saved}"
    );
    // When only generation is set (no stage), [commit] header should be implicit
    assert!(
        !saved.contains("[commit]\n"),
        "Should not have standalone [commit] header when only generation is set: {saved}"
    );
}

#[test]
fn test_save_to_new_file_commit_with_stage_and_generation() {
    // Test that when both stage and generation are set, [commit] header is explicit
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");

    let config = UserConfig {
        commit: CommitConfig {
            stage: Some(StageMode::Tracked),
            generation: Some(CommitGenerationConfig {
                command: Some("llm -m haiku".to_string()),
                ..Default::default()
            }),
        },
        ..Default::default()
    };

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        saved.contains("[commit]\n"),
        "Should have [commit] header when stage is set: {saved}"
    );
    assert!(
        saved.contains("stage = \"tracked\""),
        "Should contain stage: {saved}"
    );
    assert!(
        saved.contains("[commit.generation]"),
        "Should have generation section: {saved}"
    );
}

#[test]
fn test_save_to_new_file_with_skip_shell_integration() {
    // Test skip-shell-integration-prompt is only written when true
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");

    let config = UserConfig {
        skip_shell_integration_prompt: true,
        ..Default::default()
    };

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        saved.contains("skip-shell-integration-prompt = true"),
        "Should contain flag: {saved}"
    );
}

#[test]
fn test_save_to_new_file_with_worktree_path() {
    // Test worktree-path is written when set
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");

    let config = UserConfig {
        worktree_path: Some("../{{ repo }}.{{ branch }}".to_string()),
        ..Default::default()
    };

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        saved.contains("worktree-path = \"../{{ repo }}.{{ branch }}\""),
        "Should contain worktree-path: {saved}"
    );
}

#[test]
fn test_save_to_preserves_project_section_configs() {
    // Exercises sync_serialized_section through the surgical-update save path
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");

    // Create initial file with a project
    let initial = r#"
[projects."github.com/user/repo"]
worktree-path = ".wt/{{ branch | sanitize }}"
"#;
    std::fs::write(&config_path, initial).unwrap();

    // Build config with project section overrides
    let mut config = UserConfig::default();
    config.projects.insert(
        "github.com/user/repo".to_string(),
        UserProjectOverrides {
            worktree_path: Some(".wt/{{ branch | sanitize }}".to_string()),
            merge: MergeConfig {
                squash: Some(false),
                ..Default::default()
            },
            list: ListConfig {
                full: Some(true),
                ..Default::default()
            },
            ..Default::default()
        },
    );

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        saved.contains("squash = false"),
        "Should serialize merge config: {saved}"
    );
    assert!(
        saved.contains("full = true"),
        "Should serialize list config: {saved}"
    );

    // Default sections should not appear
    assert!(
        !saved.contains("[projects.\"github.com/user/repo\".commit]"),
        "Default commit section should not appear: {saved}"
    );
    assert!(
        !saved.contains("[projects.\"github.com/user/repo\".switch]"),
        "Default switch section should not appear: {saved}"
    );
}

#[test]
fn test_save_to_removes_default_project_section() {
    // Exercises the is_default → remove branch in sync_serialized_section
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(
        &config_path,
        "[projects.\"github.com/u/r\".list]\nfull = true\n",
    )
    .unwrap();

    let mut config =
        UserConfig::load_from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
    config.projects.get_mut("github.com/u/r").unwrap().list = ListConfig::default();
    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        !saved.contains("[projects.\"github.com/u/r\".list]"),
        "Default section should be removed: {saved}"
    );
}

// =========================================================================
// Per-project hooks tests (append semantics)
// =========================================================================

/// Helper to parse hooks from TOML
fn parse_hooks(toml_str: &str) -> HooksConfig {
    toml::from_str(toml_str).unwrap()
}

#[test]
fn test_hooks_merge_append_semantics() {
    // Global has post-start, per-project has post-start
    // Both should run (global first, then per-project)
    let mut config = UserConfig {
        hooks: parse_hooks("post-start = \"echo global\""),
        ..Default::default()
    };

    config.projects.insert(
        "github.com/user/repo".to_string(),
        UserProjectOverrides {
            hooks: parse_hooks("post-start = \"echo project\""),
            ..Default::default()
        },
    );

    let effective = config.hooks(Some("github.com/user/repo"));
    let post_start = effective.post_start.unwrap();
    let commands: Vec<_> = post_start.commands().collect();
    assert_eq!(commands.len(), 2);
    assert_eq!(commands[0].template, "echo global");
    assert_eq!(commands[1].template, "echo project");
}

#[test]
fn test_hooks_no_project_override_uses_global() {
    // Global has hooks, project doesn't - global hooks used
    let config = UserConfig {
        hooks: parse_hooks("post-start = \"echo global\""),
        ..Default::default()
    };

    let effective = config.hooks(Some("github.com/other/repo"));
    let post_start = effective.post_start.unwrap();
    let commands: Vec<_> = post_start.commands().collect();
    assert_eq!(commands.len(), 1);
    assert_eq!(commands[0].template, "echo global");
}

#[test]
fn test_hooks_project_only_no_global() {
    // Project has hooks, global doesn't - project hooks used
    let mut config = UserConfig::default();

    config.projects.insert(
        "github.com/user/repo".to_string(),
        UserProjectOverrides {
            hooks: parse_hooks("post-start = \"echo project\""),
            ..Default::default()
        },
    );

    let effective = config.hooks(Some("github.com/user/repo"));
    let post_start = effective.post_start.unwrap();
    let commands: Vec<_> = post_start.commands().collect();
    assert_eq!(commands.len(), 1);
    assert_eq!(commands[0].template, "echo project");
}

#[test]
fn test_hooks_different_hook_types_not_merged() {
    // Global has post-start, per-project has pre-commit
    // These should remain separate (different hook types)
    let mut config = UserConfig {
        hooks: parse_hooks("post-start = \"echo global-start\""),
        ..Default::default()
    };

    config.projects.insert(
        "github.com/user/repo".to_string(),
        UserProjectOverrides {
            hooks: parse_hooks("pre-commit = \"echo project-commit\""),
            ..Default::default()
        },
    );

    let effective = config.hooks(Some("github.com/user/repo"));

    // post-start: only global
    let post_start = effective.post_start.unwrap();
    let start_commands: Vec<_> = post_start.commands().collect();
    assert_eq!(start_commands.len(), 1);
    assert_eq!(start_commands[0].template, "echo global-start");

    // pre-commit: only project
    let pre_commit = effective.pre_commit.unwrap();
    let commit_commands: Vec<_> = pre_commit.commands().collect();
    assert_eq!(commit_commands.len(), 1);
    assert_eq!(commit_commands[0].template, "echo project-commit");
}

#[test]
fn test_hooks_none_project_uses_global() {
    // When no project is provided, only global hooks are used
    let config = UserConfig {
        hooks: parse_hooks("post-start = \"echo global\""),
        ..Default::default()
    };

    let effective = config.hooks(None);
    let post_start = effective.post_start.unwrap();
    let commands: Vec<_> = post_start.commands().collect();
    assert_eq!(commands.len(), 1);
    assert_eq!(commands[0].template, "echo global");
}

/// Validates that valid_user_config_keys() includes all hook types from HookType enum.
///
/// The JsonSchema derivation should include all HooksConfig fields, which correspond
/// to HookType variants. HookType uses strum's Display with kebab-case serialization,
/// which matches the serde field names.
#[test]
fn test_valid_user_config_keys_includes_all_hook_types() {
    use strum::IntoEnumIterator;

    let valid_keys = valid_user_config_keys();

    for hook_type in HookType::iter() {
        let key = hook_type.to_string(); // e.g., "post-create", "pre-merge"
        assert!(
            valid_keys.contains(&key),
            "HookType::{hook_type:?} ({key}) is missing from valid_user_config_keys()"
        );
    }
}

/// Validates that all keys from valid_user_config_keys() are accepted by serde.
///
/// Creates a TOML config with each key set to a valid value and verifies
/// deserialization succeeds. This ensures the JsonSchema matches serde's expectations.
#[test]
fn test_valid_user_config_keys_all_deserialize() {
    let valid_keys = valid_user_config_keys();

    // Build a TOML string with all keys
    // Top-level scalar values must come before table sections
    let mut scalar_lines = Vec::new();
    let mut table_lines = Vec::new();

    for key in &valid_keys {
        match key.as_str() {
            "projects" => continue, // Skip - table type tested separately
            "skip-shell-integration-prompt" | "skip-commit-generation-prompt" => {
                scalar_lines.push(format!("{key} = true"));
            }
            "worktree-path" => {
                scalar_lines.push(format!("{key} = \"test-value\""));
            }
            "list" | "commit" | "merge" | "switch" | "step" | "select" | "commit-generation"
            | "aliases" => {
                // Table sections with minimal content
                table_lines.push(format!("[{key}]"));
            }
            // Hook keys take string values
            _ => {
                scalar_lines.push(format!("{key} = \"test-value\""));
            }
        };
    }

    // Scalars first, then tables
    scalar_lines.extend(table_lines);
    let toml_content = scalar_lines.join("\n");

    // Should deserialize without error
    let result: Result<UserConfig, _> = toml::from_str(&toml_content);
    assert!(
        result.is_ok(),
        "Failed to deserialize config with all valid keys:\n{toml_content}\nError: {:?}",
        result.err()
    );
}

// =========================================================================
// Hooks Merge Behavior Tests
// =========================================================================
//
// Note: Merged configs are only used for execution, never serialized in
// production. These tests verify merge semantics for execution order.

/// Merging string-format global hooks with table-format per-project hooks
/// preserves both and maintains correct execution order.
#[test]
fn test_hooks_merge_mixed_formats_preserves_order() {
    // Global uses string format (unnamed command)
    let global_hooks = parse_hooks(r#"post-start = "npm install""#);

    // Per-project uses table format (named commands)
    let project_hooks = parse_hooks(
        r#"
[post-start]
setup = "echo setup"
"#,
    );

    let mut config = UserConfig {
        hooks: global_hooks,
        ..Default::default()
    };

    config.projects.insert(
        "github.com/user/repo".to_string(),
        UserProjectOverrides {
            hooks: project_hooks,
            ..Default::default()
        },
    );

    // Verify merge preserves order: global first, then project
    let effective = config.hooks(Some("github.com/user/repo"));
    let commands: Vec<_> = effective.post_start.as_ref().unwrap().commands().collect();
    assert_eq!(commands.len(), 2);
    assert_eq!(commands[0].template, "npm install"); // Global first
    assert_eq!(commands[1].template, "echo setup"); // Project second
}

/// When global and per-project both define same hook type, both run in order.
#[test]
fn test_hooks_merge_same_names_both_run() {
    // Both define "test" command - both should execute
    let global_hooks = parse_hooks(
        r#"
[post-start]
test = "cargo test"
"#,
    );

    let project_hooks = parse_hooks(
        r#"
[post-start]
test = "npm test"
"#,
    );

    let mut config = UserConfig {
        hooks: global_hooks,
        ..Default::default()
    };

    config.projects.insert(
        "github.com/user/repo".to_string(),
        UserProjectOverrides {
            hooks: project_hooks,
            ..Default::default()
        },
    );

    // Both commands present, global first
    let effective = config.hooks(Some("github.com/user/repo"));
    let commands: Vec<_> = effective.post_start.as_ref().unwrap().commands().collect();
    assert_eq!(commands.len(), 2);
    assert_eq!(commands[0].template, "cargo test");
    assert_eq!(commands[1].template, "npm test");
}

// =========================================================================
// reload_from error path tests
// =========================================================================

/// Test that reload_from returns a parse error with formatted path
/// when the config file contains invalid TOML.
#[test]
fn test_reload_from_invalid_toml() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");

    // Create initial valid config so file exists
    std::fs::write(&config_path, "# Valid config\n").unwrap();

    // Now corrupt it with invalid TOML
    std::fs::write(&config_path, "this is not valid toml [[[").unwrap();

    // Try to reload via a mutation — should fail with parse error
    let mut config = UserConfig::default();
    let result = config.set_skip_shell_integration_prompt(Some(&config_path));

    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("Failed to parse config file"),
        "Expected parse error, got: {err}"
    );
    // Verify path is included in error (format_path_for_display would format it)
    assert!(
        err.contains("config.toml"),
        "Expected path in error, got: {err}"
    );
}

// =========================================================================
// System config loading and merge tests
// =========================================================================

#[test]
fn test_system_config_merged_with_user_config() {
    // System config provides base defaults
    let system_toml = r#"
[merge]
squash = false
rebase = false

[list]
full = true
"#;

    // User config overrides some settings
    let user_toml = r#"
[merge]
squash = true
"#;

    // Parse both configs separately
    let system_config = UserConfig::load_from_str(system_toml).unwrap();
    let user_config = UserConfig::load_from_str(user_toml).unwrap();

    // Verify system config values
    assert_eq!(system_config.merge.squash, Some(false));
    assert_eq!(system_config.merge.rebase, Some(false));
    assert_eq!(system_config.list.full, Some(true));

    // Verify user config values
    assert_eq!(user_config.merge.squash, Some(true));

    // Simulate the merge that happens via the config crate's builder:
    // When both system and user configs define [merge], the config crate
    // performs a deep merge where user values override system values.
    // This is tested end-to-end via integration tests; here we verify
    // the Merge trait works correctly for the layering.
    let merged = system_config.merge.merge_with(&user_config.merge);

    assert_eq!(merged.squash, Some(true)); // User overrides
    assert_eq!(merged.rebase, Some(false)); // System default preserved
}

#[test]
fn test_system_config_worktree_path_overridden_by_user() {
    let system_toml = r#"worktree-path = "/company/worktrees/{{ repo }}/{{ branch | sanitize }}""#;
    let user_toml = r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}""#;

    let system_config = UserConfig::load_from_str(system_toml).unwrap();
    let user_config = UserConfig::load_from_str(user_toml).unwrap();

    assert_eq!(
        system_config.worktree_path(),
        "/company/worktrees/{{ repo }}/{{ branch | sanitize }}"
    );
    assert_eq!(
        user_config.worktree_path(),
        "../{{ repo }}.{{ branch | sanitize }}"
    );
}

#[test]
fn test_system_config_commit_generation_merged() {
    let system_toml = r#"
[commit.generation]
command = "company-llm-tool"
template = "Company standard template: {{ git_diff }}"
"#;
    let user_toml = r#"
[commit.generation]
command = "my-preferred-llm"
"#;

    let system_config = UserConfig::load_from_str(system_toml).unwrap();
    let user_config = UserConfig::load_from_str(user_toml).unwrap();

    let system_gen = system_config.commit_generation(None);
    assert_eq!(system_gen.command, Some("company-llm-tool".to_string()));
    assert_eq!(
        system_gen.template,
        Some("Company standard template: {{ git_diff }}".to_string())
    );

    let user_gen = user_config.commit_generation(None);
    assert_eq!(user_gen.command, Some("my-preferred-llm".to_string()));
    // User didn't set template, so in a merged scenario the system template
    // would be preserved via the config crate's deep merge
}

#[test]
fn test_hooks_merge_trait_appends_for_global_project_merge() {
    // The Merge trait uses append semantics — used for global→per-project merging
    // (in accessors.rs). NOT used for system→user config merging, which goes
    // through the config crate's replacement semantics instead.
    let global_hooks = parse_hooks("pre-merge = \"global-lint\"");
    let project_hooks = parse_hooks("pre-merge = \"project-lint\"");

    let merged = global_hooks.merge_with(&project_hooks);
    let pre_merge = merged.pre_merge.unwrap();
    let commands: Vec<_> = pre_merge.commands().collect();
    assert_eq!(commands.len(), 2);
    assert_eq!(commands[0].template, "global-lint"); // Global first
    assert_eq!(commands[1].template, "project-lint"); // Project second
}

#[test]
fn test_hooks_merge_folds_post_create_into_pre_start() {
    // User config uses deprecated `post-create`, project uses `pre-start`.
    // merge_with should combine them so the user's hook isn't silently dropped.
    let user_hooks = parse_hooks("post-create = \"npm install\"");
    let project_hooks = parse_hooks("pre-start = \"cargo test\"");

    let merged = user_hooks.merge_with(&project_hooks);
    let pre_start = merged
        .get(HookType::PreStart)
        .expect("should have pre-start");
    let commands: Vec<_> = pre_start.commands().collect();
    assert_eq!(commands.len(), 2, "Both hooks should be present");
    assert_eq!(commands[0].template, "npm install"); // User's post-create first
    assert_eq!(commands[1].template, "cargo test"); // Project's pre-start second
}

#[test]
fn test_hooks_merge_same_source_both_pre_start_and_post_create() {
    // Single config with both fields — merge_with folds post_create into pre_start.
    // This is an unusual config (user wrote both), but if it goes through merge
    // both commands should run rather than silently dropping one.
    let both = parse_hooks("pre-start = \"npm install\"\npost-create = \"cargo build\"");
    let empty = HooksConfig::default();

    let merged = both.merge_with(&empty);
    let pre_start = merged
        .get(HookType::PreStart)
        .expect("should have pre-start");
    let commands: Vec<_> = pre_start.commands().collect();
    assert_eq!(
        commands.len(),
        2,
        "Both commands from same source should be present"
    );
    assert_eq!(commands[0].template, "npm install"); // pre-start first
    assert_eq!(commands[1].template, "cargo build"); // post-create second
}

#[test]
fn test_hooks_merge_post_create_both_sides() {
    // Both configs use deprecated `post-create` — should still combine
    let global = parse_hooks("post-create = \"npm install\"");
    let project = parse_hooks("post-create = \"cargo build\"");

    let merged = global.merge_with(&project);
    let pre_start = merged
        .get(HookType::PreStart)
        .expect("should have pre-start");
    let commands: Vec<_> = pre_start.commands().collect();
    assert_eq!(commands.len(), 2);
    assert_eq!(commands[0].template, "npm install");
    assert_eq!(commands[1].template, "cargo build");
}

#[test]
fn test_aliases_accessor_appends_on_collision() {
    let toml_str = r#"
[aliases]
shared = "global-cmd"
global-only = "only-global"

[projects."test-project".aliases]
shared = "project-cmd"
project-only = "only-project"
"#;
    let config: UserConfig = toml::from_str(toml_str).unwrap();

    let aliases = config.aliases(Some("test-project"));

    // Non-colliding aliases are present
    assert_eq!(aliases["global-only"].commands().count(), 1);
    assert_eq!(
        aliases["global-only"].commands().next().unwrap().template,
        "only-global"
    );
    assert_eq!(aliases["project-only"].commands().count(), 1);
    assert_eq!(
        aliases["project-only"].commands().next().unwrap().template,
        "only-project"
    );

    // Colliding alias: both commands run (global first, then per-project)
    let shared: Vec<_> = aliases["shared"].commands().collect();
    assert_eq!(shared.len(), 2);
    assert_eq!(shared[0].template, "global-cmd");
    assert_eq!(shared[1].template, "project-cmd");

    // Without project: only global aliases
    let global_only = config.aliases(None);
    assert_eq!(global_only["shared"].commands().count(), 1);
    assert_eq!(
        global_only["shared"].commands().next().unwrap().template,
        "global-cmd"
    );
}

/// Test that reload_from handles permission errors
/// when the config file exists but cannot be read.
#[cfg(unix)]
#[test]
fn test_reload_from_permission_error() {
    use std::os::unix::fs::PermissionsExt;

    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");

    // Create a valid config file
    std::fs::write(&config_path, "[projects]\n").unwrap();

    // Remove read permissions
    let mut perms = std::fs::metadata(&config_path).unwrap().permissions();
    perms.set_mode(0o000); // No permissions
    std::fs::set_permissions(&config_path, perms).unwrap();

    // Restore permissions on drop to allow cleanup
    struct RestorePerms<'a>(&'a std::path::Path);
    impl Drop for RestorePerms<'_> {
        fn drop(&mut self) {
            let mut perms = std::fs::metadata(self.0).unwrap().permissions();
            perms.set_mode(0o644);
            let _ = std::fs::set_permissions(self.0, perms);
        }
    }
    let _guard = RestorePerms(&config_path);

    // Skip this test when running as root (common in CI containers)
    if std::env::var("USER").as_deref() == Ok("root") {
        return;
    }

    // Try to reload via a mutation — should fail with read error
    let mut config = UserConfig::default();
    let result = config.set_skip_shell_integration_prompt(Some(&config_path));

    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("Failed to read config file"),
        "Expected read error, got: {err}"
    );
    // Verify path is included in error
    assert!(
        err.contains("config.toml"),
        "Expected path in error, got: {err}"
    );
}

#[test]
fn test_load_error_display_file() {
    let toml_err = toml::from_str::<UserConfig>("[list]\nbranches = \"bad\"\n").unwrap_err();
    let err = LoadError::File {
        path: std::path::PathBuf::from("/tmp/config.toml"),
        label: "User config",
        err: Box::new(toml_err),
    };
    let msg = err.to_string();
    assert!(msg.contains("User config at"), "{msg}");
    assert!(msg.contains("failed to parse"), "{msg}");
    assert!(msg.contains("line 2"), "{msg}");
}

#[test]
fn test_load_error_display_env() {
    let err = LoadError::Env {
        err: "invalid type".into(),
        vars: vec![("WORKTRUNK__LIST__BRANCHES".into(), "not-a-bool".into())],
    };
    assert_eq!(err.to_string(), "invalid type");
}

#[test]
fn test_load_error_display_validation() {
    let err = LoadError::Validation("bad".into());
    assert_eq!(err.to_string(), "bad");
}

#[test]
fn test_try_parse_value() {
    use super::try_parse_value;

    assert_eq!(try_parse_value("true"), toml::Value::Boolean(true));
    assert_eq!(try_parse_value("TRUE"), toml::Value::Boolean(true));
    assert_eq!(try_parse_value("false"), toml::Value::Boolean(false));
    assert_eq!(try_parse_value("42"), toml::Value::Integer(42));
    assert_eq!(try_parse_value("0"), toml::Value::Integer(0));
    assert_eq!(try_parse_value("1.5"), toml::Value::Float(1.5));
    assert_eq!(
        try_parse_value("hello"),
        toml::Value::String("hello".into())
    );
}

// =========================================================================
// finalize() — defensive fallback
// =========================================================================

#[test]
fn test_finalize_with_undeserializable_table() {
    // finalize() falls back to defaults when the table can't deserialize.
    // This shouldn't happen in practice (files are individually validated),
    // but the fallback exists for safety.
    let mut table = toml::Table::new();
    table.insert("list".into(), toml::Value::String("not-a-table".into()));

    let (config, warnings) = UserConfig::finalize(table, Vec::new());
    assert_eq!(config.worktree_path, None); // defaults
    assert_eq!(warnings.len(), 1);
    assert!(matches!(&warnings[0], LoadError::Validation(_)));
}

// =========================================================================
// save_to() tests — existing-file branch
// =========================================================================

#[test]
fn test_save_to_existing_file_writes_project_sections() {
    // An existing file is updated with a project that has list, commit,
    // merge, and switch sections populated via diff-based merge.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");

    // Start with a minimal file so save_to takes the "existing file" path
    std::fs::write(&config_path, "# user config\n").unwrap();

    let mut config = UserConfig::default();
    config.projects.insert(
        "github.com/user/repo".to_string(),
        UserProjectOverrides {
            worktree_path: Some("../{{ branch | sanitize }}".to_string()),
            list: ListConfig {
                full: Some(true),
                ..Default::default()
            },
            commit: CommitConfig {
                stage: Some(StageMode::Tracked),
                generation: None,
            },
            merge: MergeConfig {
                squash: Some(false),
                ..Default::default()
            },
            switch: SwitchConfig {
                cd: Some(false),
                picker: None,
            },
            ..Default::default()
        },
    );

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    // Comment should be preserved
    assert!(saved.contains("# user config"), "comment lost: {saved}");
    // All four per-project sections should be present
    assert!(
        saved.contains("[projects.\"github.com/user/repo\".list]"),
        "missing list section: {saved}"
    );
    assert!(saved.contains("full = true"), "missing list.full: {saved}");
    assert!(
        saved.contains("[projects.\"github.com/user/repo\".commit]"),
        "missing commit section: {saved}"
    );
    assert!(
        saved.contains("stage = \"tracked\""),
        "missing commit.stage: {saved}"
    );
    assert!(
        saved.contains("[projects.\"github.com/user/repo\".merge]"),
        "missing merge section: {saved}"
    );
    assert!(
        saved.contains("squash = false"),
        "missing merge.squash: {saved}"
    );
    assert!(
        saved.contains("[projects.\"github.com/user/repo\".switch]"),
        "missing switch section: {saved}"
    );
    assert!(saved.contains("cd = false"), "missing switch.cd: {saved}");

    // Round-trip: file parses back into an equivalent config
    let reparsed = UserConfig::load_from_str(&saved).unwrap();
    let reloaded = reparsed.projects.get("github.com/user/repo").unwrap();
    assert_eq!(
        reloaded.worktree_path.as_deref(),
        Some("../{{ branch | sanitize }}")
    );
    assert_eq!(reloaded.list.full, Some(true));
    assert_eq!(reloaded.commit.stage, Some(StageMode::Tracked));
    assert_eq!(reloaded.merge.squash, Some(false));
    assert_eq!(reloaded.switch.cd, Some(false));
}

#[test]
fn test_save_to_existing_file_removes_stale_projects_and_sections() {
    // The diff-based merge removes projects not in the in-memory config
    // and removes sections whose in-memory value is now None.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");

    // Existing file has two projects and a list section on the one we keep.
    std::fs::write(
        &config_path,
        r#"# keep me
[projects."keep"]
worktree-path = "keep-path"

[projects."keep".list]
full = true

[projects."drop"]
worktree-path = "drop-path"
"#,
    )
    .unwrap();

    let mut config = UserConfig::default();
    config.projects.insert(
        "keep".to_string(),
        UserProjectOverrides {
            worktree_path: Some("keep-path".to_string()),
            list: ListConfig::default(), // was non-default on disk, now default — should be removed
            ..Default::default()
        },
    );

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(saved.contains("# keep me"), "comment lost: {saved}");
    assert!(
        saved.contains("[projects.\"keep\"]") || saved.contains("\"keep\""),
        "keep project lost: {saved}"
    );
    assert!(
        !saved.contains("\"drop\""),
        "stale project not removed: {saved}"
    );
    assert!(
        !saved.contains("[projects.\"keep\".list]"),
        "stale list section not removed: {saved}"
    );
}

#[test]
fn test_save_to_existing_file_updates_commit_generation_command() {
    // The file already has a [commit.generation] table — the diff-based merge
    // updates the changed command in place while preserving unchanged keys.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(
        &config_path,
        r#"# keep this comment
[commit.generation]
command = "old-llm"
template = "stays: {{ diff }}"
"#,
    )
    .unwrap();

    let config = UserConfig {
        commit: CommitConfig {
            stage: None,
            generation: Some(CommitGenerationConfig {
                command: Some("new-llm".to_string()),
                template: Some("stays: {{ diff }}".to_string()),
                ..Default::default()
            }),
        },
        ..Default::default()
    };

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        saved.contains("# keep this comment"),
        "comment lost: {saved}"
    );
    assert!(
        saved.contains("command = \"new-llm\""),
        "command not updated: {saved}"
    );
    assert!(
        !saved.contains("old-llm"),
        "old command not removed: {saved}"
    );
    assert!(
        saved.contains("template = \"stays: {{ diff }}\""),
        "template not preserved: {saved}"
    );
}

#[test]
fn test_save_to_existing_file_adds_commit_generation_to_plain_commit_table() {
    // Existing file has a [commit] table (e.g., with `stage`) but no
    // [commit.generation] subtable yet. The diff-based merge inserts the
    // new subtable while preserving existing keys.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(
        &config_path,
        r#"[commit]
stage = "all"
"#,
    )
    .unwrap();

    let config = UserConfig {
        commit: CommitConfig {
            stage: Some(StageMode::All),
            generation: Some(CommitGenerationConfig {
                command: Some("llm".to_string()),
                ..Default::default()
            }),
        },
        ..Default::default()
    };

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        saved.contains("[commit.generation]"),
        "generation subtable missing: {saved}"
    );
    assert!(
        saved.contains("command = \"llm\""),
        "command missing: {saved}"
    );
    assert!(saved.contains("stage = \"all\""), "stage lost: {saved}");
}

#[test]
fn test_save_to_existing_file_replaces_non_table_project_entry() {
    // When an existing file has a non-table value at projects."<id>",
    // the diff-based merge replaces it with the correct table structure
    // from the in-memory config. Only reachable via raw file edits.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(
        &config_path,
        r#"[projects]
bogus = "not-a-table"

[projects."real"]
worktree-path = "old"
"#,
    )
    .unwrap();

    let mut config = UserConfig::default();
    config
        .projects
        .insert("bogus".to_string(), UserProjectOverrides::default());
    config.projects.insert(
        "real".to_string(),
        UserProjectOverrides {
            worktree_path: Some("new".to_string()),
            ..Default::default()
        },
    );

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    // The "real" project should be updated
    assert!(
        saved.contains("worktree-path = \"new\""),
        "real project not updated: {saved}"
    );
    // The bogus string entry is replaced with a proper (empty) table
    assert!(
        !saved.contains("bogus = \"not-a-table\""),
        "malformed entry should be replaced: {saved}"
    );
}

#[test]
fn test_save_to_existing_file_where_commit_is_scalar() {
    // When the existing file has `commit` as a scalar (user-edited mistake),
    // the diff-based merge replaces it with the correct table structure.
    // Only reachable via raw file edits.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(&config_path, "commit = \"hand-edited-mistake\"\n").unwrap();

    let config = UserConfig {
        commit: CommitConfig {
            stage: None,
            generation: Some(CommitGenerationConfig {
                command: Some("llm".to_string()),
                ..Default::default()
            }),
        },
        ..Default::default()
    };

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    // The scalar is replaced with a proper table
    assert!(
        !saved.contains("\"hand-edited-mistake\""),
        "malformed entry should be replaced: {saved}"
    );
    assert!(
        saved.contains("command = \"llm\""),
        "commit generation should be written: {saved}"
    );
}

#[test]
fn test_save_to_existing_file_where_commit_generation_is_scalar() {
    // When `[commit]` is a valid table but `generation` is a scalar
    // (raw-edit mistake), the diff-based merge replaces the scalar with
    // the correct table. Only reachable via raw file edits.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(
        &config_path,
        "[commit]\nstage = \"tracked\"\ngeneration = \"oops\"\n",
    )
    .unwrap();

    let config = UserConfig {
        commit: CommitConfig {
            stage: Some(StageMode::Tracked),
            generation: Some(CommitGenerationConfig {
                command: Some("llm".to_string()),
                ..Default::default()
            }),
        },
        ..Default::default()
    };

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    // The scalar generation is replaced with a proper table
    assert!(
        !saved.contains("generation = \"oops\""),
        "malformed generation should be replaced: {saved}"
    );
    assert!(
        saved.contains("command = \"llm\""),
        "generation command should be written: {saved}"
    );
    // The unrelated stage value is preserved
    assert!(saved.contains("stage = \"tracked\""), "stage lost: {saved}");
}

#[test]
fn test_save_to_existing_file_where_projects_is_scalar() {
    // When the existing file has `projects` as a scalar (raw-edit mistake),
    // the diff-based merge replaces it with the correct table structure.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(&config_path, "projects = \"oops\"\n").unwrap();

    let mut config = UserConfig::default();
    config.projects.insert(
        "repo".to_string(),
        UserProjectOverrides {
            worktree_path: Some("../x".to_string()),
            ..Default::default()
        },
    );

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    // The scalar is replaced with a proper table
    assert!(
        !saved.contains("projects = \"oops\""),
        "malformed projects should be replaced: {saved}"
    );
    assert!(
        saved.contains("worktree-path = \"../x\""),
        "project worktree-path should be written: {saved}"
    );
}

#[test]
fn test_save_to_existing_file_with_invalid_toml_returns_parse_error() {
    // Covers the `parse().map_err(...)` closure in save_to's existing-file
    // branch: the file exists (so we take the "surgical update" path) but
    // its contents don't parse as TOML.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(&config_path, "this is not [[[ valid toml").unwrap();

    let config = UserConfig::default();
    let err = config.save_to(&config_path).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("Failed to parse config file"),
        "expected parse error, got: {msg}"
    );
}

#[cfg(unix)]
#[test]
fn test_save_to_existing_file_with_unreadable_file_returns_read_error() {
    // Covers the `read_to_string.map_err(...)` closure in save_to: the file
    // exists but we can't read it. Matches the pattern of the mutation-side
    // test_reload_from_permission_error.
    use std::os::unix::fs::PermissionsExt;

    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(&config_path, "# valid\n").unwrap();

    let mut perms = std::fs::metadata(&config_path).unwrap().permissions();
    perms.set_mode(0o000);
    std::fs::set_permissions(&config_path, perms).unwrap();

    struct RestorePerms<'a>(&'a std::path::Path);
    impl Drop for RestorePerms<'_> {
        fn drop(&mut self) {
            let mut perms = std::fs::metadata(self.0).unwrap().permissions();
            perms.set_mode(0o644);
            let _ = std::fs::set_permissions(self.0, perms);
        }
    }
    let _guard = RestorePerms(&config_path);

    // Skip when running as root (common in CI containers)
    if std::env::var("USER").as_deref() == Ok("root") {
        return;
    }

    let config = UserConfig::default();
    let err = config.save_to(&config_path).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("Failed to read config file"),
        "expected read error, got: {msg}"
    );
}

#[test]
fn test_save_to_root_path_skips_parent_creation() {
    // Covers the else branch of `if let Some(parent) = config_path.parent()`
    // in save_to: when the config path is the filesystem root (`/`), parent()
    // returns None and we skip create_dir_all. The downstream write will
    // fail because `/` is a directory, but we should reach that point
    // without panicking — proving the None branch executes cleanly.
    let config = UserConfig::default();
    let err = config.save_to(std::path::Path::new("/")).unwrap_err();
    let msg = err.to_string();
    // We expect to fail at the read/write step, not at create_dir_all.
    // The specific error depends on the platform (read error since "/"
    // exists, or write error). We just verify it wasn't the create_dir
    // path (which would mean line 216's else branch wasn't taken).
    assert!(
        !msg.contains("Failed to create config directory"),
        "should skip create_dir when parent is None, got: {msg}"
    );
}

#[test]
fn test_save_to_fails_when_parent_is_a_file() {
    // Covers the create_dir_all error branch: if config_path's parent
    // already exists as a regular file, create_dir_all fails and save_to
    // returns a "Failed to create config directory" error.
    let dir = tempfile::tempdir().unwrap();
    let blocker = dir.path().join("blocker");
    std::fs::write(&blocker, "i am a file").unwrap();

    // config_path's parent is "blocker", which is a file
    let config_path = blocker.join("config.toml");

    let config = UserConfig::default();
    let err = config.save_to(&config_path).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("Failed to create config directory"),
        "expected create_dir error, got: {msg}"
    );
}

#[test]
fn test_save_to_new_file_expands_nested_project_inline_tables() {
    // Covers expand_inline_tables recursion: a per-project config with nested
    // sections forces to_document to emit inline tables that must be expanded
    // into standard [projects."id".list] etc. subtables for readability.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");

    let mut config = UserConfig::default();
    config.projects.insert(
        "repo".to_string(),
        UserProjectOverrides {
            list: ListConfig {
                full: Some(true),
                branches: Some(true),
                ..Default::default()
            },
            switch: SwitchConfig {
                cd: Some(false),
                picker: None,
            },
            ..Default::default()
        },
    );

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    // Should be expanded into standard subtables, not inline tables
    assert!(
        saved.contains("[projects.repo.list]"),
        "list should be expanded to standard subtable: {saved}"
    );
    assert!(
        saved.contains("[projects.repo.switch]"),
        "switch should be expanded to standard subtable: {saved}"
    );
    // Inline syntax should not appear for these sections
    assert!(
        !saved.contains("list = {"),
        "list should not be inline: {saved}"
    );
    assert!(
        !saved.contains("switch = {"),
        "switch should not be inline: {saved}"
    );
    // And it should round-trip cleanly
    let reparsed = UserConfig::load_from_str(&saved).unwrap();
    assert_eq!(
        reparsed.projects.get("repo").unwrap().list.branches,
        Some(true)
    );
}

#[test]
fn test_save_to_existing_file_preserves_integer_and_array_values() {
    // Exercises values_equal for Integer (timeout-ms) and Array
    // (approved-commands) — types beyond String and Boolean.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(
        &config_path,
        r#"# keep comment
[list]
timeout-ms = 5000
full = true

[projects."repo"]
approved-commands = ["cargo test", "cargo build"]
"#,
    )
    .unwrap();

    let config =
        UserConfig::load_from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(saved.contains("# keep comment"), "comment lost: {saved}");
    assert!(
        saved.contains("timeout-ms = 5000"),
        "integer value should be preserved: {saved}"
    );
    assert!(
        saved.contains("full = true"),
        "boolean value should be preserved: {saved}"
    );
    assert!(
        saved.contains("cargo test") && saved.contains("cargo build"),
        "array values should be preserved: {saved}"
    );
}

#[test]
fn test_save_to_existing_file_replaces_changed_inline_table() {
    // When an inline table's contents actually changed, the diff-based merge
    // replaces it (even though this changes formatting from inline to standard).
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(&config_path, "post-start = { build = \"cargo build\" }\n").unwrap();

    // Load, modify the hook, then save
    let mut config =
        UserConfig::load_from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
    config.hooks = toml::from_str("post-start = { build = \"cargo test\" }").unwrap();
    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        saved.contains("cargo test"),
        "changed value should be written: {saved}"
    );
    assert!(
        !saved.contains("cargo build"),
        "old value should be gone: {saved}"
    );
}

#[test]
fn test_save_to_existing_file_preserves_unknown_keys() {
    // Unknown top-level keys (typos, future fields) must survive a save.
    // The diff-based merge skips unknown keys in its stale-key sweep.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(
        &config_path,
        r#"# A user comment
unknown-key = "keep me"
skip-shell-integration-prompt = true
"#,
    )
    .unwrap();

    let config = UserConfig {
        skip_shell_integration_prompt: true,
        ..Default::default()
    };

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        saved.contains("unknown-key = \"keep me\""),
        "unknown key should be preserved: {saved}"
    );
    assert!(
        saved.contains("# A user comment"),
        "comment should be preserved: {saved}"
    );
    assert!(
        saved.contains("skip-shell-integration-prompt = true"),
        "known key should be preserved: {saved}"
    );
}

#[test]
fn test_save_to_existing_file_preserves_nested_unknown_keys() {
    // Unknown keys inside a known table (e.g., a newer-version field under
    // `[merge]`) must survive a save that touches unrelated settings. Older
    // wt versions should leave config data they don't recognize alone.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(
        &config_path,
        r#"[merge]
squash = false
future-option = true
"#,
    )
    .unwrap();

    // Mutate an unrelated setting so save_to() writes the file.
    let config = UserConfig {
        skip_shell_integration_prompt: true,
        merge: MergeConfig {
            squash: Some(false),
            ..Default::default()
        },
        ..Default::default()
    };

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        saved.contains("future-option = true"),
        "nested unknown key should be preserved: {saved}"
    );
    assert!(
        saved.contains("squash = false"),
        "known sibling should be preserved: {saved}"
    );
    assert!(
        saved.contains("skip-shell-integration-prompt = true"),
        "new top-level key should be written: {saved}"
    );
}

#[test]
fn test_save_to_existing_file_preserves_section_with_only_unknown_fields() {
    // A section whose known fields are all absent/default (so reserialization
    // skips the whole section) but that still contains unknown keys must
    // survive the save — including when a mutation later introduces a known
    // field to the same section.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(
        &config_path,
        r#"[merge]
future-option = true
"#,
    )
    .unwrap();

    // Mutation introduces a known field to `[merge]` that wasn't on disk.
    let config = UserConfig {
        merge: MergeConfig {
            squash: Some(false),
            ..Default::default()
        },
        ..Default::default()
    };

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        saved.contains("future-option = true"),
        "unknown key in otherwise-empty section should be preserved: {saved}"
    );
    assert!(
        saved.contains("squash = false"),
        "new known field should be written: {saved}"
    );
}

#[test]
fn test_save_to_existing_file_preserves_deeply_nested_unknown_keys() {
    // Unknown keys inside a doubly-nested table (e.g., `[commit.generation]`)
    // must also survive — the preserve set needs to traverse to the right level.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(
        &config_path,
        r#"[commit.generation]
command = "old-llm"
future-knob = "from-newer-wt"
"#,
    )
    .unwrap();

    let config = UserConfig {
        commit: CommitConfig {
            stage: None,
            generation: Some(CommitGenerationConfig {
                command: Some("new-llm".to_string()),
                ..Default::default()
            }),
        },
        ..Default::default()
    };

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        saved.contains(r#"future-knob = "from-newer-wt""#),
        "nested unknown key should be preserved: {saved}"
    );
    assert!(
        saved.contains(r#"command = "new-llm""#),
        "known field should be updated: {saved}"
    );
    assert!(!saved.contains("old-llm"), "old value not removed: {saved}");
}

#[test]
fn test_save_to_existing_file_preserves_unknown_keys_in_project_section() {
    // Unknown keys inside a project entry (e.g., `[projects."name"]`) are also
    // at a nested level — the fix must cover entries inside the projects map too.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(
        &config_path,
        r#"[projects."repo"]
worktree-path = "../custom"
future-per-project = "value"
"#,
    )
    .unwrap();

    let mut config = UserConfig::default();
    config.projects.insert(
        "repo".to_string(),
        UserProjectOverrides {
            worktree_path: Some("../custom".to_string()),
            ..Default::default()
        },
    );
    // Flip an unrelated flag so save_to() has a reason to write.
    config.skip_shell_integration_prompt = true;

    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        saved.contains(r#"future-per-project = "value""#),
        "unknown key inside a project entry should be preserved: {saved}"
    );
    assert!(
        saved.contains(r#"worktree-path = "../custom""#),
        "known field should be preserved: {saved}"
    );
}

#[test]
fn test_save_to_existing_file_preserves_inline_table_formatting() {
    // When a user writes a hook as an inline table (e.g., `post-start = { ... }`),
    // the diff-based merge must not rewrite it to a standard table if the value
    // is semantically unchanged.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let original = "post-start = { build = \"cargo build\" }\n";
    std::fs::write(&config_path, original).unwrap();

    // Load the config (which parses hooks via flatten), then save it back
    let config = UserConfig::load_from_str(original).unwrap();
    config.save_to(&config_path).unwrap();

    let saved = std::fs::read_to_string(&config_path).unwrap();
    // The inline table syntax should be preserved (not expanded to [post-start])
    assert!(
        saved.contains("post-start = { build = \"cargo build\" }"),
        "inline table should be preserved: {saved}"
    );
    assert!(
        !saved.contains("[post-start]"),
        "should not be expanded to standard table: {saved}"
    );
}

// =========================================================================
// mutation.rs — additional coverage
// =========================================================================

#[test]
fn test_set_project_worktree_path_noop_when_unchanged() {
    // Covers the `return false` early-exit in set_project_worktree_path's
    // mutator: when the path already matches, no save happens. We verify
    // this by checking that the file content is byte-identical across a
    // redundant call.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(&config_path, "# keep\n").unwrap();

    let mut config = UserConfig::default();
    config
        .set_project_worktree_path("user/repo", "../custom".to_string(), Some(&config_path))
        .unwrap();

    let after_first = std::fs::read_to_string(&config_path).unwrap();
    // Sanity: first call actually wrote the value
    assert!(after_first.contains("../custom"), "{after_first}");

    // Second call with identical value should be a no-op — reload_from
    // refreshes self from disk, the mutator compares equal and returns
    // false, so save is skipped.
    let mut config2 = UserConfig::default();
    config2
        .set_project_worktree_path("user/repo", "../custom".to_string(), Some(&config_path))
        .unwrap();

    let after_second = std::fs::read_to_string(&config_path).unwrap();
    assert_eq!(
        after_first, after_second,
        "unchanged value should not rewrite the file"
    );
}

#[test]
fn test_set_skip_shell_integration_prompt_noop_on_second_call() {
    // Covers the `return false` early-exit in set_skip_shell_integration_prompt's
    // mutator. reload_from refreshes all fields from disk — after the first
    // save, the flag is true on disk, so a second call sees it already true
    // and skips the save.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(&config_path, "# empty\n").unwrap();

    let mut config = UserConfig::default();
    config
        .set_skip_shell_integration_prompt(Some(&config_path))
        .unwrap();
    let after_first = std::fs::read_to_string(&config_path).unwrap();
    assert!(after_first.contains("skip-shell-integration-prompt = true"));

    // Second call with the flag already true in-memory — mutator returns
    // false, save is skipped, file is byte-identical.
    config
        .set_skip_shell_integration_prompt(Some(&config_path))
        .unwrap();
    let after_second = std::fs::read_to_string(&config_path).unwrap();
    assert_eq!(after_first, after_second);
}

#[test]
fn test_acquire_config_lock_handles_root_path() {
    // Covers the else branch of `if let Some(parent) = lock_path.parent()`
    // in acquire_config_lock: when config_path is `/`, `with_extension` is
    // a no-op, and `"/".parent()` is None, so we skip create_dir_all. The
    // subsequent OpenOptions.open fails (can't open a directory as a file),
    // which surfaces as a "Failed to open lock file" error — proving the
    // None branch executes cleanly.
    let mut config = UserConfig::default();
    let err = config
        .set_skip_shell_integration_prompt(Some(std::path::Path::new("/")))
        .unwrap_err();
    let msg = err.to_string();
    assert!(
        !msg.contains("Failed to create config directory"),
        "should skip create_dir when parent is None, got: {msg}"
    );
    assert!(
        msg.contains("Failed to open lock file"),
        "expected open lock error, got: {msg}"
    );
}

#[test]
fn test_acquire_config_lock_fails_when_parent_is_file() {
    // Covers the create_dir_all error branch in acquire_config_lock:
    // if the config path's parent is actually a regular file, we can't
    // create the lock directory and the mutation fails fast.
    let dir = tempfile::tempdir().unwrap();
    let blocker = dir.path().join("blocker");
    std::fs::write(&blocker, "i am a file").unwrap();

    let config_path = blocker.join("config.toml");

    let mut config = UserConfig::default();
    let err = config
        .set_skip_shell_integration_prompt(Some(&config_path))
        .unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("Failed to create config directory"),
        "expected create_dir error, got: {msg}"
    );
}

#[cfg(unix)]
#[test]
fn test_with_locked_mutation_propagates_save_error() {
    // Covers the `save_to(&path)?` error branch in with_locked_mutation:
    // after a successful lock + reload, the mutator closure chmods the
    // config file to 000. The subsequent save_to tries to read the
    // existing file and fails with a permission
    // error, which with_locked_mutation propagates back to the caller.
    use std::os::unix::fs::PermissionsExt;

    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(&config_path, "# valid\n").unwrap();

    struct RestorePerms<'a>(&'a std::path::Path);
    impl Drop for RestorePerms<'_> {
        fn drop(&mut self) {
            if let Ok(meta) = std::fs::metadata(self.0) {
                let mut perms = meta.permissions();
                perms.set_mode(0o644);
                let _ = std::fs::set_permissions(self.0, perms);
            }
        }
    }
    let _guard = RestorePerms(&config_path);

    if std::env::var("USER").as_deref() == Ok("root") {
        return;
    }

    let cfg_path_for_closure = config_path.clone();
    let mut config = UserConfig::default();
    let err = config
        .with_locked_mutation(Some(&config_path), move |_config| {
            // Mid-mutation: strip read permissions from the config file.
            // reload_from already ran; save_to will try to read again and fail.
            let mut perms = std::fs::metadata(&cfg_path_for_closure)
                .unwrap()
                .permissions();
            perms.set_mode(0o000);
            std::fs::set_permissions(&cfg_path_for_closure, perms).unwrap();
            true
        })
        .unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("Failed to read config file"),
        "expected save-side read error, got: {msg}"
    );
}