dodot-lib 4.0.0

Core library for dodot dotfiles manager
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
//! Integration tests for command API.

use std::sync::Arc;

use crate::commands;
use crate::config::ConfigManager;
use crate::datastore::{CommandOutput, CommandRunner, FilesystemDataStore};
use crate::fs::Fs;
use crate::packs::orchestration::ExecutionContext;
use crate::paths::Pather;
use crate::render;
use crate::testing::TempEnvironment;
use crate::Result;
use standout_render::OutputMode;

struct MockCommandRunner;
impl CommandRunner for MockCommandRunner {
    fn run(&self, _: &str, _: &[String]) -> Result<CommandOutput> {
        Ok(CommandOutput {
            exit_code: 0,
            stdout: String::new(),
            stderr: String::new(),
        })
    }
}

/// CommandRunner test double that returns canned outputs per `(exe,
/// args...)` key. Used by probe::app integration tests so the brew /
/// mdls / mdfind subprocesses don't actually run.
struct CannedRunner {
    responses: std::sync::Mutex<std::collections::HashMap<Vec<String>, CommandOutput>>,
}

impl CannedRunner {
    fn new() -> Self {
        Self {
            responses: std::sync::Mutex::new(std::collections::HashMap::new()),
        }
    }
    fn respond(&self, args: &[&str], stdout: &str, exit_code: i32) {
        let key: Vec<String> = args.iter().map(|s| s.to_string()).collect();
        self.responses.lock().unwrap().insert(
            key,
            CommandOutput {
                exit_code,
                stdout: stdout.into(),
                stderr: String::new(),
            },
        );
    }
}

impl CommandRunner for CannedRunner {
    fn run(&self, exe: &str, args: &[String]) -> Result<CommandOutput> {
        let mut full = vec![exe.to_string()];
        full.extend(args.iter().cloned());
        self.responses
            .lock()
            .unwrap()
            .get(&full)
            .cloned()
            .ok_or_else(|| {
                crate::DodotError::Other(format!("CannedRunner: no canned response for {full:?}"))
            })
    }
}

fn make_ctx(env: &TempEnvironment) -> ExecutionContext {
    let runner: Arc<dyn CommandRunner> = Arc::new(MockCommandRunner);
    let datastore = Arc::new(FilesystemDataStore::new(
        env.fs.clone(),
        env.paths.clone(),
        runner.clone(),
    ));
    let config_manager = Arc::new(ConfigManager::new(&env.dotfiles_root).unwrap());

    ExecutionContext {
        fs: env.fs.clone() as Arc<dyn Fs>,
        datastore,
        paths: env.paths.clone() as Arc<dyn Pather>,
        config_manager,
        syntax_checker: Arc::new(crate::shell::NoopSyntaxChecker),
        command_runner: runner,
        dry_run: false,
        no_provision: true,
        provision_rerun: false,
        force: false,
        view_mode: crate::commands::ViewMode::Full,
        group_mode: crate::commands::GroupMode::Name,
        verbose: false,
    }
}

/// Variant of make_ctx that swaps in a [`CannedRunner`] so probe
/// tests can exercise the brew/mdls/mdfind enrichment paths without
/// spawning processes.
fn make_ctx_with_runner(env: &TempEnvironment, runner: Arc<dyn CommandRunner>) -> ExecutionContext {
    let datastore = Arc::new(FilesystemDataStore::new(
        env.fs.clone(),
        env.paths.clone(),
        runner.clone(),
    ));
    let config_manager = Arc::new(ConfigManager::new(&env.dotfiles_root).unwrap());
    ExecutionContext {
        fs: env.fs.clone() as Arc<dyn Fs>,
        datastore,
        paths: env.paths.clone() as Arc<dyn Pather>,
        config_manager,
        syntax_checker: Arc::new(crate::shell::NoopSyntaxChecker),
        command_runner: runner,
        dry_run: false,
        no_provision: true,
        provision_rerun: false,
        force: false,
        view_mode: crate::commands::ViewMode::Full,
        group_mode: crate::commands::GroupMode::Name,
        verbose: false,
    }
}

// ── status ──────────────────────────────────────────────────

#[test]
fn status_shows_pending_before_up() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "set nocompatible")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    assert_eq!(result.packs.len(), 1);
    assert_eq!(result.packs[0].name, "vim");
    assert!(!result.packs[0].files.is_empty());

    // All should be pending
    for file in &result.packs[0].files {
        assert_eq!(
            file.status, "pending",
            "file {} should be pending",
            file.name
        );
    }
}

/// On non-macOS, `_lib/<rest>` entries resolve to `Resolution::Skip`
/// in the planner. Status must suppress the corresponding row and
/// only surface the warning — otherwise the user sees a confusing
/// "pending symlink" row alongside a "skipping on this platform"
/// warning. Regression for review feedback on PR #90.
#[test]
fn status_suppresses_lib_prefix_rows_when_skipped() {
    let env = TempEnvironment::builder()
        .pack("macapps")
        .file("_lib/LaunchAgents/com.example.foo.plist", "x")
        .file("regular.toml", "y")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    // The pack is present either way; what we're pinning is the
    // *file rows*: on non-macOS the `_lib/...` row is suppressed,
    // on macOS it appears like any other pending symlink.
    let pack = result
        .packs
        .iter()
        .find(|p| p.name == "macapps")
        .expect("macapps pack must appear");

    let lib_row = pack
        .files
        .iter()
        .find(|f| f.name.starts_with("_lib/") || f.name == "_lib");
    let regular_row = pack.files.iter().find(|f| f.name == "regular.toml");

    assert!(
        regular_row.is_some(),
        "non-_lib entry must always render; got files {:?}",
        pack.files.iter().map(|f| &f.name).collect::<Vec<_>>()
    );

    if cfg!(target_os = "macos") {
        assert!(
            lib_row.is_some(),
            "on macOS `_lib/` entries should render normally; got files {:?}",
            pack.files.iter().map(|f| &f.name).collect::<Vec<_>>()
        );
    } else {
        assert!(
            lib_row.is_none(),
            "on non-macOS `_lib/` rows must be suppressed; got files {:?}",
            pack.files.iter().map(|f| &f.name).collect::<Vec<_>>()
        );
        // The warning channel still carries the explanation. The
        // exact form depends on whether the catchall scanner matched
        // the top-level `_lib` directory or a nested `_lib/<rest>`
        // file — either way, the warning mentions `_lib` and the
        // macOS-only constraint.
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.contains("_lib") && w.contains("macOS-only")),
            "expected a `_lib` macOS-only warning; got {:?}",
            result.warnings
        );
    }
}

#[test]
fn status_renders_with_standout() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "x")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    // Render as text
    let output = render::render("pack-status", &result, OutputMode::Text).unwrap();
    assert!(output.contains("vim"), "output: {output}");
    assert!(output.contains("vimrc"), "output: {output}");
    assert!(output.contains("pending"), "output: {output}");

    // Render as JSON
    let json = render::render("pack-status", &result, OutputMode::Json).unwrap();
    assert!(json.contains("\"packs\""), "json: {json}");
}

#[test]
fn status_lists_ignored_packs() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "x")
        .done()
        .pack("disabled")
        .file("stuff", "x")
        .ignored()
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    assert_eq!(
        result
            .packs
            .iter()
            .map(|p| p.name.as_str())
            .collect::<Vec<_>>(),
        vec!["vim"]
    );
    assert_eq!(result.ignored_packs, vec!["disabled".to_string()]);

    let output = render::render("pack-status", &result, OutputMode::Text).unwrap();
    assert!(output.contains("Ignored Packs"), "output: {output}");
    assert!(output.contains("disabled"), "output: {output}");
}

#[test]
fn status_pack_filter_applies_to_ignored_packs() {
    // `dodot status <name>` should narrow both the main listing and the
    // ignored-packs section to just the requested name.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "x")
        .done()
        .pack("disabled")
        .file("stuff", "x")
        .ignored()
        .done()
        .pack("old")
        .file("thing", "x")
        .ignored()
        .done()
        .build();

    let ctx = make_ctx(&env);
    let filter = vec!["disabled".to_string()];
    let result = commands::status::status(Some(&filter), &ctx).unwrap();

    assert!(result.packs.is_empty(), "filter should exclude vim");
    assert_eq!(result.ignored_packs, vec!["disabled".to_string()]);
}

// ── status: correct target paths ────────────────────────────

#[test]
fn status_shows_xdg_target_for_subdirectory() {
    // Top-level directories (e.g. `nvim`) are linked wholesale to
    // `$XDG_CONFIG_HOME/<name>` — a single entry in status, not
    // one per nested file.
    let env = TempEnvironment::builder()
        .pack("nvim")
        .file("nvim/init.lua", "-- nvim config")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    let nvim_pack = &result.packs[0];
    let nvim_entry = nvim_pack
        .files
        .iter()
        .find(|f| f.name == "nvim")
        .expect("should have nvim dir entry");

    assert!(
        nvim_entry.description.contains(".config/nvim"),
        "expected XDG path for wholesale dir, got: {}",
        nvim_entry.description
    );
}

#[test]
fn status_lists_top_level_dirs_wholesale() {
    // Top-level dirs now appear as single entries (linked wholesale),
    // not expanded into one entry per nested file.
    let env = TempEnvironment::builder()
        .pack("nvim")
        .file("nvim/init.lua", "-- nvim config")
        .file("nvim/lua/plugins.lua", "return {}")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    let nvim_pack = &result.packs[0];
    let names: Vec<&str> = nvim_pack.files.iter().map(|f| f.name.as_str()).collect();
    assert_eq!(
        names,
        vec!["nvim"],
        "expected single wholesale dir entry, got {names:?}"
    );
}

// ── up ──────────────────────────────────────────────────────

#[test]
fn up_deploys_packs() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "set nocompatible")
        .file("gvimrc", "set guifont=Mono")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();

    assert!(!result.packs.is_empty());
    assert!(result.message.is_some());

    // After up, status should show deployed
    let status = commands::status::status(None, &ctx).unwrap();
    let deployed_count = status.packs[0]
        .files
        .iter()
        .filter(|f| f.status == "deployed")
        .count();
    assert!(deployed_count > 0, "some files should be deployed after up");
}

/// Regression for #42 (unify status rendering): `up` and `status` must
/// produce identical per-file status_label strings for the same handler
/// state. Before #42, `up` reported "staged bin" while `status` reported
/// "in PATH" for the same path-handler state — confusing duplicate
/// vocabulary.
#[test]
fn up_and_status_produce_matching_labels() {
    let env = TempEnvironment::builder()
        .pack("multi")
        .file("vimrc", "set nocompat") // symlink handler
        .file("aliases.sh", "alias x=y") // shell handler
        .done()
        .pack("withbin")
        .file("bin/tool", "#!/bin/sh\necho hi")
        .done()
        .build();

    let ctx = make_ctx(&env);

    let up_result = commands::up::up(None, &ctx).unwrap();
    let status_result = commands::status::status(None, &ctx).unwrap();

    // Build (pack, file_name) -> status_label maps for both.
    let to_map = |packs: &[commands::DisplayPack]| {
        let mut map = std::collections::HashMap::new();
        for p in packs {
            for f in &p.files {
                if f.status == "error" || f.name.is_empty() {
                    continue; // skip overlay error rows that have no status counterpart
                }
                map.insert((p.name.clone(), f.name.clone()), f.status_label.clone());
            }
        }
        map
    };

    let up_labels = to_map(&up_result.packs);
    let status_labels = to_map(&status_result.packs);

    assert_eq!(
        up_labels, status_labels,
        "up and status should report identical status_labels for the same files"
    );

    // Spot-check the actual labels: should be the steady-state vocabulary
    // ("deployed", "sourced", "in PATH"), not the executor vocabulary
    // ("staged X", "executed: X").
    let labels: Vec<&str> = up_labels.values().map(String::as_str).collect();
    assert!(
        labels.contains(&"in PATH"),
        "expected path handler to render as 'in PATH', got: {labels:?}"
    );
    assert!(
        labels.contains(&"sourced"),
        "expected shell handler to render as 'sourced', got: {labels:?}"
    );
    assert!(
        labels.contains(&"deployed"),
        "expected symlink handler to render as 'deployed', got: {labels:?}"
    );
    assert!(
        labels.iter().all(|l| !l.starts_with("staged ")),
        "no label should use the executor's 'staged X' vocabulary, got: {labels:?}"
    );
}

/// Regression for #42: `down` should likewise render through status, not
/// hand-rolled "removed" / "state removed" labels.
#[test]
fn down_and_status_produce_matching_labels() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "x")
        .file("aliases.sh", "alias v=vim")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    let down_result = commands::down::down(None, &ctx).unwrap();
    let status_result = commands::status::status(None, &ctx).unwrap();

    let to_map = |packs: &[commands::DisplayPack]| {
        let mut map = std::collections::HashMap::new();
        for p in packs {
            for f in &p.files {
                if f.status == "error" || f.name.is_empty() {
                    continue;
                }
                map.insert((p.name.clone(), f.name.clone()), f.status_label.clone());
            }
        }
        map
    };

    let down_labels = to_map(&down_result.packs);
    let status_labels = to_map(&status_result.packs);
    assert_eq!(
        down_labels, status_labels,
        "down and status should report identical status_labels for the same files"
    );

    // After down, files should be in handler-specific pending vocabulary.
    let labels: Vec<&str> = down_labels.values().map(String::as_str).collect();
    assert!(
        labels.iter().all(|l| !l.contains("removed")),
        "down output should use status vocabulary, not 'removed', got: {labels:?}"
    );
}

#[test]
fn up_generates_shell_init() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    // Shell init script should exist
    env.assert_exists(&env.paths.init_script_path());
    let init_content = env
        .fs
        .read_to_string(&env.paths.init_script_path())
        .unwrap();
    assert!(
        init_content.contains("aliases.sh"),
        "init script: {init_content}"
    );
}

#[test]
fn status_surfaces_syntax_error_sidecar_for_deployed_shell_file() {
    use crate::shell::{SyntaxCheckResult, SyntaxChecker};
    use std::path::Path;

    struct FlagAliases;
    impl SyntaxChecker for FlagAliases {
        fn check(&self, _interpreter: &str, file: &Path) -> SyntaxCheckResult {
            if file.file_name().and_then(|s| s.to_str()) == Some("aliases.sh") {
                SyntaxCheckResult::SyntaxError {
                    stderr: "/path/aliases.sh: line 47: bad substitution\n".into(),
                }
            } else {
                SyntaxCheckResult::Ok
            }
        }
    }

    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "echo ${broken")
        .file("env.sh", "export FOO=bar")
        .done()
        .build();

    let mut ctx = make_ctx(&env);
    ctx.syntax_checker = Arc::new(FlagAliases);
    commands::up::up(None, &ctx).unwrap();

    // Now run status — should flag aliases.sh as broken and leave
    // env.sh as plain deployed.
    let result = commands::status::status(None, &ctx).unwrap();
    let pack = &result.packs[0];

    let aliases = pack
        .files
        .iter()
        .find(|f| f.name == "aliases.sh")
        .expect("aliases.sh row missing");
    assert_eq!(aliases.status, "broken", "row: {aliases:?}");
    assert_eq!(aliases.status_label, "syntax error");
    let note_idx = aliases
        .note_ref
        .expect("aliases.sh should carry a note ref") as usize;
    assert!(
        result.notes[note_idx - 1].body.contains("bad substitution"),
        "note: {:?}",
        result.notes[note_idx - 1]
    );

    let env_row = pack
        .files
        .iter()
        .find(|f| f.name == "env.sh")
        .expect("env.sh row missing");
    assert_eq!(env_row.status, "deployed");
    assert_eq!(env_row.status_label, "sourced");
}

#[test]
fn status_surfaces_runtime_failures_from_recent_profiles() {
    // A clean source (passes syntax) that exits non-zero in 2 of the
    // 3 most recent shell startups should be flagged as broken with a
    // footnote summarizing the failure rate.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    // Write three fake profile TSVs by hand. Distinct exit codes for
    // the old vs. new failure — if the aggregator overwrites
    // last_failure_exit while iterating newest→oldest, this test
    // catches it: oldest=2, newest=1, so the label must say "exited 1"
    // (the most-recent failure), not "exited 2".
    let source_path = env.dotfiles_root.join("vim/aliases.sh");
    let target = source_path.display().to_string();
    let probes_dir = env.paths.probes_shell_init_dir();
    env.fs.mkdir_all(&probes_dir).unwrap();
    let make_profile = |t0: u64, exit: i32| {
        let body = format!(
            "# dodot shell-init profile v1\n\
             # shell\tbash 5.0\n\
             # start_t\t{t0}.000000\n\
             source\tvim\tshell\t{target}\t{t0}.000100\t{t0}.000900\t{exit}\n\
             # end_t\t{t0}.001000\n",
        );
        env.fs
            .write_file(
                &probes_dir.join(format!("profile-{t0:010}-100-1.tsv")),
                body.as_bytes(),
            )
            .unwrap();
    };
    make_profile(1714000001, 2); // oldest failure
    make_profile(1714000002, 0); // clean run in the middle
    make_profile(1714000003, 1); // most recent failure

    let result = commands::status::status(None, &ctx).unwrap();
    let row = result.packs[0]
        .files
        .iter()
        .find(|f| f.name == "aliases.sh")
        .expect("aliases.sh row missing");

    assert_eq!(row.status, "broken", "row: {row:?}");
    // Label must report the *most recent* failure's exit code (1),
    // not the older one (2).
    assert!(
        row.status_label.contains("exited 1") && row.status_label.contains("2/3"),
        "status_label was: {}",
        row.status_label
    );
    assert!(
        !row.status_label.contains("exited 2"),
        "status_label should report newest failure, not older: {}",
        row.status_label
    );
    let note_idx = row.note_ref.expect("expected note ref") as usize;
    let note = &result.notes[note_idx - 1];
    assert!(
        note.body.contains("2 of 3 recent shell startups"),
        "note body: {}",
        note.body
    );
    assert!(
        note.body.contains("last failure: exit 1"),
        "note should mention most recent failure exit code: {}",
        note.body
    );
    // The footnote should point users at the per-file probe view (not
    // `--history`, which only shows aggregate counts).
    assert!(
        note.body.contains("dodot probe shell-init vim/aliases.sh"),
        "note should point at the filtered probe view: {}",
        note.body
    );
}

#[test]
fn status_inlines_captured_stderr_into_runtime_failure_footnote() {
    // When a recent failing run also has a sibling errors.log entry,
    // the status footnote should inline a snippet of the stderr so the
    // user sees the actual error inline, not just the exit code.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .done()
        .build();
    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    let source_path = env.dotfiles_root.join("vim/aliases.sh");
    let target = source_path.display().to_string();
    let probes_dir = env.paths.probes_shell_init_dir();
    env.fs.mkdir_all(&probes_dir).unwrap();
    let prof_name = "profile-1714000003-100-1.tsv";
    let body = format!(
        "# dodot shell-init profile v1\n\
         # shell\tbash 5.0\n\
         # start_t\t1714000003.000000\n\
         source\tvim\tshell\t{target}\t1714000003.000100\t1714000003.000900\t1\n\
         # end_t\t1714000003.001000\n",
    );
    env.fs
        .write_file(&probes_dir.join(prof_name), body.as_bytes())
        .unwrap();
    let err_log = format!(
        "# dodot shell-init errors v1\n@@\t{target}\t1\nzsh: command not found: gpg-agent\n"
    );
    env.fs
        .write_file(
            &probes_dir.join("profile-1714000003-100-1.errors.log"),
            err_log.as_bytes(),
        )
        .unwrap();

    let result = commands::status::status(None, &ctx).unwrap();
    let row = result.packs[0]
        .files
        .iter()
        .find(|f| f.name == "aliases.sh")
        .expect("aliases.sh row missing");
    let note_idx = row.note_ref.expect("expected note ref") as usize;
    let note = &result.notes[note_idx - 1];
    assert!(
        note.body.contains("stderr:"),
        "footnote should label the stderr excerpt: {}",
        note.body
    );
    assert!(
        note.body.contains("zsh: command not found: gpg-agent"),
        "footnote should inline the captured stderr: {}",
        note.body
    );
    assert!(
        note.body.contains("dodot probe shell-init vim/aliases.sh"),
        "footnote should point at the per-file probe view: {}",
        note.body
    );
}

#[test]
fn up_writes_syntax_error_sidecar_when_check_fails() {
    use crate::shell::{SyntaxCheckResult, SyntaxChecker};
    use std::path::Path;

    // A checker that flags `aliases.sh` as broken so we can verify
    // up wires the validation pass through correctly.
    struct FlagAliases;
    impl SyntaxChecker for FlagAliases {
        fn check(&self, _interpreter: &str, file: &Path) -> SyntaxCheckResult {
            if file.file_name().and_then(|s| s.to_str()) == Some("aliases.sh") {
                SyntaxCheckResult::SyntaxError {
                    stderr: "aliases.sh: line 1: unexpected token\n".into(),
                }
            } else {
                SyntaxCheckResult::Ok
            }
        }
    }

    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "if [ x = y\nfi")
        .file("env.sh", "export FOO=bar")
        .done()
        .build();

    let mut ctx = make_ctx(&env);
    ctx.syntax_checker = Arc::new(FlagAliases);
    commands::up::up(None, &ctx).unwrap();

    // Sidecar present for the failing file…
    let bad = crate::shell::error_sidecar_path(env.paths.as_ref(), "vim", "aliases.sh");
    assert!(env.fs.exists(&bad), "expected sidecar at {}", bad.display());
    let body = env.fs.read_to_string(&bad).unwrap();
    assert!(body.contains("unexpected token"), "sidecar:\n{body}");

    // …and not for the clean file.
    let good = crate::shell::error_sidecar_path(env.paths.as_ref(), "vim", "env.sh");
    assert!(!env.fs.exists(&good));
}

#[test]
fn up_dry_run_no_changes() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "x")
        .done()
        .build();

    let mut ctx = make_ctx(&env);
    ctx.dry_run = true;

    let result = commands::up::up(None, &ctx).unwrap();
    assert!(result.dry_run);

    // Nothing should be deployed
    let status_ctx = make_ctx(&env); // fresh non-dry-run ctx
    let status = commands::status::status(None, &status_ctx).unwrap();
    for file in &status.packs[0].files {
        assert_eq!(file.status, "pending", "dry run should not deploy");
    }
}

#[test]
fn up_dry_run_does_not_write_preprocessing_baselines() {
    // Baselines anchor "the state of the last successful `up`," so
    // a dry run — which never executes — must not move that anchor.
    let env = TempEnvironment::builder()
        .pack("app")
        .file("config.toml.tmpl", "name = {{ name }}")
        .config("[preprocessor.template.vars]\nname = \"Alice\"\n")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let baseline_path = ctx
        .paths
        .preprocessor_baseline_path("app", "preprocessed", "config.toml");
    assert!(
        !ctx.fs.exists(&baseline_path),
        "test precondition: baseline should not exist before any up runs"
    );

    let mut dry_ctx = make_ctx(&env);
    dry_ctx.dry_run = true;
    let _ = commands::up::up(None, &dry_ctx).unwrap();

    assert!(
        !ctx.fs.exists(&baseline_path),
        "dry-run must NOT write a baseline; the cache must remain untouched"
    );
}

// ── cfprefsd drift marker (#109) ────────────────────────────

#[cfg(target_os = "macos")]
#[test]
fn up_writes_cfprefsd_marker_on_first_run_with_plists() {
    // First-ever `up`: no previous last-up marker, so any plist
    // file in an active pack counts as "drifted." The marker
    // must land for the post-up prompt to fire.
    let env = TempEnvironment::builder()
        .pack("mac-defaults")
        .file("com.example.app.plist", "<?xml?><plist></plist>")
        .done()
        .build();
    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    let marker = ctx.paths.data_dir().join("cfprefsd-needs-invalidation");
    assert!(
        ctx.fs.exists(&marker),
        "marker should land on the first up that deploys a plist"
    );
}

#[cfg(target_os = "macos")]
#[test]
fn up_does_not_write_cfprefsd_marker_when_pack_has_no_plists() {
    // Pack contains no plist files → the cfprefsd prompt has
    // nothing to invalidate; the marker must stay absent.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "set nocompatible")
        .done()
        .build();
    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    let marker = ctx.paths.data_dir().join("cfprefsd-needs-invalidation");
    assert!(
        !ctx.fs.exists(&marker),
        "marker must not appear when no plists are present"
    );
}

#[cfg(target_os = "macos")]
#[test]
fn up_with_pack_filter_does_not_write_cfprefsd_marker_for_unrelated_pack_plists() {
    // Pack A contains a plist; pack B has only non-plist files.
    // Running `dodot up` filtered to pack B must NOT drop the
    // cfprefsd marker — the user's command didn't touch any plist.
    let env = TempEnvironment::builder()
        .pack("mac-defaults")
        .file("com.example.app.plist", "<?xml?><plist></plist>")
        .done()
        .pack("vim")
        .file("vimrc", "set nocompatible")
        .done()
        .build();
    let ctx = make_ctx(&env);
    let filter = vec!["vim".to_string()];
    commands::up::up(Some(&filter), &ctx).unwrap();

    let marker = ctx.paths.data_dir().join("cfprefsd-needs-invalidation");
    assert!(
        !ctx.fs.exists(&marker),
        "drift detection must respect the pack filter — \
         a plist in an unrelated pack should not trigger the marker"
    );
}

// ── §7.4 passive-command contract (#121) ───────────────────

#[test]
fn status_does_not_write_to_datastore() {
    // §7.4: passive commands MUST NOT mutate the datastore.
    // Running `up` once primes the data dir; running `status`
    // afterwards must leave that state byte-identical.
    let env = TempEnvironment::builder()
        .pack("app")
        .file("config.toml.tmpl", "name = {{ name }}")
        .config("[preprocessor.template.vars]\nname = \"Alice\"\n")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    let snapshot = snapshot_dir_contents(&env, env.paths.data_dir());

    // Two consecutive status runs must leave data_dir unchanged.
    commands::status::status(None, &ctx).unwrap();
    commands::status::status(None, &ctx).unwrap();

    let after = snapshot_dir_contents(&env, env.paths.data_dir());
    assert_eq!(
        snapshot, after,
        "status must be byte-identical to the post-up snapshot — \
         no datastore writes allowed"
    );
}

#[test]
fn up_dry_run_does_not_write_to_datastore() {
    // Pin the same §7.4 contract for `up --dry-run`.
    let env = TempEnvironment::builder()
        .pack("app")
        .file("config.toml.tmpl", "name = {{ name }}")
        .config("[preprocessor.template.vars]\nname = \"Alice\"\n")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();
    let snapshot = snapshot_dir_contents(&env, env.paths.data_dir());

    let mut dry_ctx = make_ctx(&env);
    dry_ctx.dry_run = true;
    commands::up::up(None, &dry_ctx).unwrap();

    let after = snapshot_dir_contents(&env, env.paths.data_dir());
    assert_eq!(
        snapshot, after,
        "dry-run must be byte-identical to the post-up snapshot"
    );
}

#[test]
fn install_template_dry_run_emits_correct_sentinel_without_writing_rendered_file() {
    // The §7.4 unblocker: in Passive mode the rendered file isn't
    // on disk, so the install handler used to fail to compute its
    // sentinel. With `rendered_bytes` threaded through, dry-run now
    // emits a Run intent with the same sentinel as the active path
    // would — without ever writing the rendered file. (#121)
    let env = TempEnvironment::builder()
        .pack("app")
        .file("install.sh.tmpl", "#!/bin/sh\necho hello {{ name }}")
        .config("[preprocessor.template.vars]\nname = \"Alice\"\n")
        .done()
        .build();

    // First up establishes the baseline so Passive mode has
    // something to read. no_provision = false so the install
    // handler actually plans Run intents (the default test ctx
    // suppresses code-execution handlers).
    let mut ctx = make_ctx(&env);
    ctx.no_provision = false;
    commands::up::up(None, &ctx).unwrap();

    // Capture the active sentinel (it lives in the executed
    // RunCommand operation).
    let active_intents = crate::packs::orchestration::collect_pack_intents(
        &crate::packs::Pack::new(
            "app".into(),
            env.dotfiles_root.join("app"),
            ctx.config_manager
                .config_for_pack(&env.dotfiles_root.join("app"))
                .unwrap()
                .to_handler_config(),
        ),
        &ctx,
    )
    .unwrap();
    let active_sentinel = active_intents
        .iter()
        .find_map(|i| match i {
            crate::operations::HandlerIntent::Run { sentinel, .. } => Some(sentinel.clone()),
            _ => None,
        })
        .expect("active path must produce a Run intent for install.sh");

    // Snapshot the rendered datastore file's existence — Passive
    // must not modify it, but it should already exist from the
    // earlier active up.
    let rendered_path = env
        .paths
        .handler_data_dir("app", "preprocessed")
        .join("install.sh");
    assert!(
        ctx.fs.exists(&rendered_path),
        "active up must have written the rendered file"
    );
    let rendered_before = ctx.fs.read_file(&rendered_path).unwrap();

    // Now plan via dry-run; the install handler must produce the
    // same sentinel from in-memory bytes. Same no_provision = false
    // so the handler actually emits intents.
    let mut dry_ctx = make_ctx(&env);
    dry_ctx.no_provision = false;
    dry_ctx.dry_run = true;
    let plan = crate::packs::orchestration::plan_pack(
        &crate::packs::Pack::new(
            "app".into(),
            env.dotfiles_root.join("app"),
            dry_ctx
                .config_manager
                .config_for_pack(&env.dotfiles_root.join("app"))
                .unwrap()
                .to_handler_config(),
        ),
        &dry_ctx,
        crate::preprocessing::PreprocessMode::Passive,
    )
    .unwrap();
    let dry_sentinel = plan
        .intents
        .iter()
        .find_map(|i| match i {
            crate::operations::HandlerIntent::Run { sentinel, .. } => Some(sentinel.clone()),
            _ => None,
        })
        .expect("passive path must produce a Run intent for install.sh");

    assert_eq!(
        active_sentinel, dry_sentinel,
        "passive sentinel must match active — same rendered bytes either way"
    );
    let rendered_after = ctx.fs.read_file(&rendered_path).unwrap();
    assert_eq!(
        rendered_before, rendered_after,
        "passive must not rewrite the rendered file"
    );
}

#[test]
fn up_dry_run_first_time_pack_with_install_template_does_not_error() {
    // Regression for Copilot review on PR #126: a first-time pack
    // containing `install.sh.tmpl` (no baseline yet, no rendered
    // file on disk) must not crash dry-run intent collection. The
    // install handler used to read `m.absolute_path` unconditionally
    // and propagate an Fs error; now it skips intent generation for
    // the placeholder match instead. Same shape for `Brewfile.tmpl`
    // / homebrew handler.
    let env = TempEnvironment::builder()
        .pack("setup")
        .file("install.sh.tmpl", "#!/bin/sh\necho hello {{ name }}")
        .file("Brewfile.tmpl", "brew '{{ pkg }}'")
        .config("[preprocessor.template.vars]\nname = \"Alice\"\npkg = \"jq\"\n")
        .done()
        .build();

    let mut dry_ctx = make_ctx(&env);
    dry_ctx.no_provision = false;
    dry_ctx.dry_run = true;

    // The fix: this returns Ok and emits zero Run intents (the
    // placeholders skip intent generation cleanly). Pre-fix, the
    // install/homebrew handlers tried to read missing rendered
    // files and propagated an Fs error.
    let result = commands::up::up(None, &dry_ctx).unwrap();
    assert!(result.dry_run);
}

#[test]
fn passive_first_time_pack_surfaces_pending_placeholder() {
    // §7.4 acceptance: a passive command on a brand-new pack with
    // no baseline cache yet must surface a coherent placeholder
    // (template stripped name, status pending), never panic, never
    // fall through to template evaluation. (#121)
    let env = TempEnvironment::builder()
        .pack("app")
        .file("greet.tmpl", "hello {{ name }}")
        .config("[preprocessor.template.vars]\nname = \"Alice\"\n")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    let files = &result.packs[0].files;
    assert_eq!(files.len(), 1, "should surface the templated entry");
    assert_eq!(
        files[0].name, "greet",
        "stripped name (not source filename)"
    );
    assert_eq!(
        files[0].status, "pending",
        "first-time template before any up: pending"
    );
}

/// Snapshot a directory tree (file contents + directory paths) to a
/// stable signature for the §7.4 no-mutation contract tests. Each
/// entry is keyed by absolute path; files map to `Some(contents)`,
/// directories to `None`. Comparing two snapshots for equality is
/// equivalent to "directory tree is byte-identical, including empty
/// directories." Including dir paths catches mutations like
/// `mkdir <data_dir>/<pack>/preprocessed` that would silently slip
/// past a contents-only check.
///
/// Unreadable entries / read errors propagate as panics rather than
/// silent skips — a passive command that produces an unreadable
/// entry under `<data_dir>` is itself a §7.4 violation worth
/// failing the test on.
fn snapshot_dir_contents(
    env: &crate::testing::TempEnvironment,
    root: &std::path::Path,
) -> std::collections::BTreeMap<std::path::PathBuf, Option<Vec<u8>>> {
    use std::collections::BTreeMap;
    let mut out = BTreeMap::new();
    if !env.fs.exists(root) {
        return out;
    }
    let mut stack: Vec<std::path::PathBuf> = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let entries = env
            .fs
            .read_dir(&dir)
            .unwrap_or_else(|e| panic!("snapshot_dir_contents: read_dir({dir:?}): {e}"));
        for entry in entries {
            if entry.is_dir {
                out.insert(entry.path.clone(), None);
                stack.push(entry.path);
            } else {
                let bytes = env.fs.read_file(&entry.path).unwrap_or_else(|e| {
                    panic!("snapshot_dir_contents: read_file({:?}): {e}", entry.path)
                });
                out.insert(entry.path, Some(bytes));
            }
        }
    }
    out
}

// ── up: conflict handling ──────────────────────────────────

#[test]
fn up_reports_conflict_when_file_exists() {
    // home.gitconfig (post-#48 per-file home opt-in) routes to ~/.gitconfig,
    // which already exists in the home_file fixture. That collision
    // exercises the conflict path the test cares about.
    let env = TempEnvironment::builder()
        .pack("git")
        .file("home.gitconfig", "[user]\n  name = new")
        .done()
        .home_file(".gitconfig", "[user]\n  name = old")
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();

    // Should report errors
    assert!(
        result.message.as_deref() == Some("Packs deployed with errors."),
        "msg: {:?}",
        result.message
    );

    // The conflict file should show as error
    let error_files: Vec<&commands::DisplayFile> = result.packs[0]
        .files
        .iter()
        .filter(|f| f.status == "error")
        .collect();
    assert!(
        !error_files.is_empty(),
        "should have error files for conflicts"
    );
    // The conflict message now lives in the notes section, referenced by
    // the error row's note_ref. status_label stays a short "error" keyword
    // so the column layout is preserved.
    let note_idx = error_files[0]
        .note_ref
        .expect("error row should carry a note_ref") as usize
        - 1;
    assert!(
        result.notes[note_idx].body.contains("conflict"),
        "note should mention conflict: {}",
        result.notes[note_idx].body
    );
    // Error rows must identify the failing file in the left column,
    // not render with an empty name (regression: PR #45 review).
    assert!(
        !error_files[0].name.is_empty(),
        "error row should name the failing file, got empty name"
    );
    assert!(
        error_files[0].name.contains("gitconfig"),
        "error row name should reference gitconfig, got: {}",
        error_files[0].name
    );

    // Original file should be untouched
    env.assert_file_contents(&env.home.join(".gitconfig"), "[user]\n  name = old");

    // Status should NOT show deployed. The conflicted file should surface
    // as `warning` (PendingConflict) with a footnote pointing at the
    // pre-existing user file — see #43.
    let status = commands::status::status(None, &ctx).unwrap();
    for file in &status.packs[0].files {
        assert!(
            matches!(file.status.as_str(), "pending" | "warning"),
            "conflicted file {} should be pending or warning, got {}",
            file.name,
            file.status
        );
    }
    let conflicted = status.packs[0]
        .files
        .iter()
        .find(|f| f.status == "warning")
        .expect("the conflicted file should surface as warning (PendingConflict)");
    assert_eq!(
        conflicted.status_label, "pending",
        "warning label should be plain 'pending' (the [N] marker is a separate column now), got: {}",
        conflicted.status_label
    );
    assert!(
        conflicted.note_ref.is_some(),
        "conflicted row should carry a note_ref into the command-wide notes list"
    );
    assert!(
        !status.notes.is_empty(),
        "status should have at least one note describing the pre-existing file"
    );
    let note_idx = conflicted.note_ref.unwrap() as usize - 1;
    assert!(
        status.notes[note_idx].body.contains(".gitconfig"),
        "note should mention the conflicting path, got: {}",
        status.notes[note_idx].body
    );
}

#[test]
fn up_force_overwrites_existing_files() {
    let env = TempEnvironment::builder()
        .pack("git")
        .file("home.gitconfig", "[user]\n  name = new")
        .done()
        .home_file(".gitconfig", "[user]\n  name = old")
        .build();

    let mut ctx = make_ctx(&env);
    ctx.force = true;
    let result = commands::up::up(None, &ctx).unwrap();

    // Should succeed
    assert_eq!(result.message.as_deref(), Some("Packs deployed."));

    // File should now be a symlink with new content
    let content = env.fs.read_to_string(&env.home.join(".gitconfig")).unwrap();
    assert_eq!(content, "[user]\n  name = new");
}

// ── up: reconcile non-provisioning state (#58) ─────────────

/// `dodot up` was additive only: a deleted source file would leave its
/// datastore entry behind, so the regenerated init script kept sourcing
/// a now-missing path. The fix wipes configuration-handler state per
/// pack at the start of `up` and re-applies from current source.
#[test]
fn up_reconciles_deleted_shell_source() {
    let env = TempEnvironment::builder()
        .pack("gh")
        .file("aliases.sh", "alias g=git")
        .file("profile.sh", "export GH=true")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    let shell_dir = env.paths.handler_data_dir("gh", "shell");
    let mut before = env.list_dir_names(&shell_dir);
    before.sort();
    assert_eq!(before, vec!["aliases.sh", "profile.sh"]);

    // Delete one source from the pack and re-run up.
    env.fs
        .remove_file(&env.dotfiles_root.join("gh/profile.sh"))
        .unwrap();
    commands::up::up(None, &ctx).unwrap();

    let after = env.list_dir_names(&shell_dir);
    assert_eq!(
        after,
        vec!["aliases.sh"],
        "orphan datastore entry persisted after re-up"
    );

    let init = env
        .fs
        .read_to_string(&env.paths.init_script_path())
        .unwrap();
    assert!(
        !init.contains("profile.sh"),
        "regenerated init still references deleted file:\n{init}"
    );
    assert!(init.contains("aliases.sh"), "init: {init}");
}

#[test]
fn up_reconciles_deleted_symlink_source() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "set nocompatible")
        .file("gvimrc", "set guifont=Mono")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    let symlink_dir = env.paths.handler_data_dir("vim", "symlink");
    let mut before = env.list_dir_names(&symlink_dir);
    before.sort();
    assert_eq!(before, vec!["gvimrc", "vimrc"]);

    env.fs
        .remove_file(&env.dotfiles_root.join("vim/gvimrc"))
        .unwrap();
    commands::up::up(None, &ctx).unwrap();

    let after = env.list_dir_names(&symlink_dir);
    assert_eq!(
        after,
        vec!["vimrc"],
        "orphan datastore symlink persisted after re-up"
    );
}

#[test]
fn up_reconciles_deleted_path_dir() {
    let env = TempEnvironment::builder()
        .pack("tools")
        .file("bin/foo", "#!/bin/sh\necho foo")
        .file("vimrc", "set nocompatible")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    let path_dir = env.paths.handler_data_dir("tools", "path");
    assert_eq!(env.list_dir_names(&path_dir), vec!["bin"]);

    // Drop the bin/ directory entirely.
    env.fs
        .remove_dir_all(&env.dotfiles_root.join("tools/bin"))
        .unwrap();
    commands::up::up(None, &ctx).unwrap();

    let after = env.list_dir_names(&path_dir);
    assert!(
        after.is_empty(),
        "path datastore should be empty after source dir removed, got: {after:?}"
    );

    let init = env
        .fs
        .read_to_string(&env.paths.init_script_path())
        .unwrap();
    assert!(
        !init.contains("tools/bin"),
        "init script still exports deleted PATH entry:\n{init}"
    );
}

/// Provisioning handlers (install, homebrew) must NOT be wiped — their
/// sentinels record "did this run with this content?" and re-running
/// would defeat the point of sentinels (reinstall on every up).
#[test]
fn up_preserves_install_sentinel_when_source_persists() {
    let env = TempEnvironment::builder()
        .pack("setup")
        .file("install.sh", "#!/bin/sh\necho hi")
        .done()
        .build();

    let mut ctx = make_ctx(&env);
    ctx.no_provision = false;

    commands::up::up(None, &ctx).unwrap();

    let install_dir = env.paths.handler_data_dir("setup", "install");
    let sentinels_before = env.list_dir_names(&install_dir);
    assert_eq!(
        sentinels_before.len(),
        1,
        "expected one sentinel, got {sentinels_before:?}"
    );
    let original = sentinels_before.into_iter().next().unwrap();

    // Re-run up with no source change. The sentinel must persist —
    // wiping it would force the script to re-execute every time.
    commands::up::up(None, &ctx).unwrap();
    let sentinels_after = env.list_dir_names(&install_dir);
    assert_eq!(
        sentinels_after,
        vec![original],
        "install sentinel should persist across re-up"
    );
}

#[test]
fn up_preserves_install_sentinel_when_source_deleted() {
    let env = TempEnvironment::builder()
        .pack("setup")
        .file("install.sh", "#!/bin/sh\necho hi")
        .done()
        .build();

    let mut ctx = make_ctx(&env);
    ctx.no_provision = false;

    commands::up::up(None, &ctx).unwrap();
    let install_dir = env.paths.handler_data_dir("setup", "install");
    let sentinels_before = env.list_dir_names(&install_dir);
    assert_eq!(sentinels_before.len(), 1);

    // Source vanishes — but the sentinel still records that *some*
    // version of this script has run, and we don't want the wipe to
    // erase that history just because the source is no longer in the
    // pack right now.
    env.fs
        .remove_file(&env.dotfiles_root.join("setup/install.sh"))
        .unwrap();
    commands::up::up(None, &ctx).unwrap();

    let sentinels_after = env.list_dir_names(&install_dir);
    assert_eq!(
        sentinels_after, sentinels_before,
        "deleting an install source must not wipe its sentinel"
    );
}

// ── down ────────────────────────────────────────────────────

#[test]
fn down_removes_deployed_state() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "x")
        .done()
        .build();

    let ctx = make_ctx(&env);

    // Deploy first
    commands::up::up(None, &ctx).unwrap();

    // Verify something is deployed
    let status = commands::status::status(None, &ctx).unwrap();
    let has_deployed = status.packs[0].files.iter().any(|f| f.status == "deployed");
    assert!(has_deployed, "should have deployed files after up");

    // Down
    let down_result = commands::down::down(None, &ctx).unwrap();
    assert!(down_result.message.is_some());

    // After down, all files should be plain pending. The user-side
    // symlinks left dangling by `down` are NOT conflicts — the executor's
    // create_user_link gracefully replaces them on the next `up`. (#43
    // refines `PendingConflict` to only fire when the executor would
    // actually refuse: non-symlink + exists.)
    let status = commands::status::status(None, &ctx).unwrap();
    for file in &status.packs[0].files {
        assert_eq!(
            file.status, "pending",
            "file {} should be pending after down (dangling symlinks are not conflicts), got {}",
            file.name, file.status
        );
    }
}

// ── list ────────────────────────────────────────────────────

#[test]
fn list_shows_all_packs() {
    let env = TempEnvironment::builder()
        .pack("git")
        .file("gitconfig", "x")
        .done()
        .pack("vim")
        .file("vimrc", "x")
        .done()
        .pack("disabled")
        .file("x", "x")
        .ignored()
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::list::list(&ctx).unwrap();

    let names: Vec<&str> = result.packs.iter().map(|p| p.name.as_str()).collect();
    assert!(names.contains(&"git"));
    assert!(names.contains(&"vim"));
    assert!(names.contains(&"disabled"));

    let disabled = result.packs.iter().find(|p| p.name == "disabled").unwrap();
    assert!(disabled.ignored);

    // Render as text
    let output = render::render("list", &result, OutputMode::Text).unwrap();
    assert!(output.contains("vim"), "output: {output}");
    assert!(output.contains("(ignored)"), "output: {output}");
}

// ── init ────────────────────────────────────────────────────

#[test]
fn init_creates_pack_directory() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);

    let result = commands::init::init("newpack", &ctx).unwrap();
    assert!(result.message.contains("newpack"));

    env.assert_dir_exists(&env.dotfiles_root.join("newpack"));
    env.assert_exists(&env.dotfiles_root.join("newpack/.dodot.toml"));
}

#[test]
fn init_fails_if_exists() {
    let env = TempEnvironment::builder()
        .pack("existing")
        .file("f", "x")
        .done()
        .build();
    let ctx = make_ctx(&env);

    let err = commands::init::init("existing", &ctx).unwrap_err();
    assert!(
        matches!(err, crate::DodotError::PackInvalid { .. }),
        "expected PackInvalid, got: {err}"
    );
}

// ── adopt ───────────────────────────────────────────────────

#[test]
fn adopt_moves_file_and_creates_symlink() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("placeholder", "")
        .done()
        .home_file(".vimrc", "set nocompatible")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".vimrc");

    let result = commands::adopt::adopt(
        Some("vim"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    // File should have moved into pack with the `home.` prefix (post-#48
    // adopt rename — preserves the round-trip back to ~/.vimrc on `up`),
    // content preserved.
    env.assert_regular_file(
        &env.dotfiles_root.join("vim/home.vimrc"),
        "set nocompatible",
    );
    // Symlink should exist at original location
    assert!(env.fs.is_symlink(&source));

    // Status output should include the vim pack with the adopted file
    assert!(result.packs.iter().any(|p| p.name == "vim"));
    let vim = result.packs.iter().find(|p| p.name == "vim").unwrap();
    assert!(vim.files.iter().any(|f| f.name == "home.vimrc"));
}

#[test]
fn adopt_preserves_executable_permissions() {
    use std::os::unix::fs::PermissionsExt;

    // Uses a dotted file (post-#2: non-dotted $HOME entries are
    // refused for round-trip safety). The test's intent is exec-bit
    // preservation, not the dot-or-not policy.
    let env = TempEnvironment::builder()
        .pack("tools")
        .file("placeholder", "")
        .done()
        .home_file(".script.sh", "#!/bin/sh\necho hi")
        .build();

    let source = env.home.join(".script.sh");
    // Mark source as executable
    let perms = std::fs::Permissions::from_mode(0o755);
    std::fs::set_permissions(&source, perms).unwrap();

    let ctx = make_ctx(&env);
    commands::adopt::adopt(
        Some("tools"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    let dest = env.dotfiles_root.join("tools/home.script.sh");
    let meta = std::fs::metadata(&dest).unwrap();
    assert_eq!(
        meta.permissions().mode() & 0o777,
        0o755,
        "executable bit should be preserved on adopted file"
    );
}

/// Regression for review item #2 on PR #49: a non-dotted entry in
/// $HOME has no automatic round-trip path under the post-#48 XDG
/// default — adopt must refuse rather than silently relocate.
#[test]
fn adopt_refuses_non_dotted_home_entry() {
    let env = TempEnvironment::builder()
        .pack("tools")
        .file("placeholder", "")
        .done()
        .home_file("script.sh", "#!/bin/sh\necho hi")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join("script.sh");
    let err = commands::adopt::adopt(
        Some("tools"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap_err();

    let msg = err.to_string();
    assert!(
        msg.contains("non-dotted entry in $HOME"),
        "expected refusal message, got: {msg}"
    );
    assert!(
        msg.contains("[symlink.targets]"),
        "refusal should point at [symlink.targets] escape hatch, got: {msg}"
    );
    // Source untouched, no pack copy created.
    env.assert_regular_file(&source, "#!/bin/sh\necho hi");
    env.assert_not_exists(&env.dotfiles_root.join("tools/script.sh"));
}

#[test]
fn adopt_destination_conflict_refused_without_force() {
    // Destination conflict: pack already has `home.vimrc`. Adopt of
    // `~/.vimrc` derives `home.vimrc` as the pack filename (post-#48
    // adopt rename), so the existing file blocks the adoption.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("home.vimrc", "existing content")
        .done()
        .home_file(".vimrc", "new content")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".vimrc");

    let err = commands::adopt::adopt(
        Some("vim"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap_err();
    assert!(
        matches!(err, crate::DodotError::SymlinkConflict { .. }),
        "expected SymlinkConflict, got: {err}"
    );

    // Original file untouched; existing pack file untouched.
    env.assert_regular_file(&source, "new content");
    env.assert_regular_file(
        &env.dotfiles_root.join("vim/home.vimrc"),
        "existing content",
    );
}

#[test]
fn adopt_destination_conflict_resolved_with_force() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("home.vimrc", "OLD")
        .done()
        .home_file(".vimrc", "NEW")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".vimrc");

    commands::adopt::adopt(
        Some("vim"),
        std::slice::from_ref(&source),
        true, // --force
        false,
        false,
        &ctx,
    )
    .unwrap();

    env.assert_regular_file(&env.dotfiles_root.join("vim/home.vimrc"), "NEW");
    assert!(env.fs.is_symlink(&source));
}

#[test]
fn adopt_directory_creates_symlink_and_preserves_contents() {
    // Dotted-directory adoption from $HOME directly: contents move to
    // pack/_home/<stripped>/, which round-trips back via the `_home/`
    // subtree-escape (Priority 2) on `dodot up`. We use a non-XDG
    // dotted dir so the test stays decoupled from the XDG-source
    // inference rules — adopting `~/.config/` itself is now refused
    // explicitly (see `adopt_xdg_root_itself_refused`).
    let env = TempEnvironment::builder()
        .pack("editor")
        .file("placeholder", "")
        .done()
        .home_file(".vim/vimrc", "set nocompatible")
        .home_file(".vim/colors/scheme.vim", "\" colors")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".vim");

    commands::adopt::adopt(
        Some("editor"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    let pack_dir = env.dotfiles_root.join("editor/_home/vim");
    env.assert_dir_exists(&pack_dir);
    env.assert_regular_file(&pack_dir.join("vimrc"), "set nocompatible");
    env.assert_regular_file(&pack_dir.join("colors/scheme.vim"), "\" colors");

    // Original path is now a symlink to the pack copy.
    assert!(env.fs.is_symlink(&source));
    let target = env.fs.readlink(&source).unwrap();
    assert_eq!(target, pack_dir);
}

/// Regression for review item #1 on PR #49: a dotted directory adopted
/// from $HOME (not in force_home) must round-trip back via the
/// `_home/` escape hatch on `dodot up`. Without this, the file would
/// silently move from $HOME/.X to $XDG_CONFIG_HOME/<pack>/X.
#[test]
fn adopt_dotted_dir_from_home_round_trips_via_home_escape() {
    let env = TempEnvironment::builder()
        .pack("chats")
        .file("placeholder", "")
        .done()
        .home_file(".weechat/weechat.conf", "[server]")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".weechat");

    commands::adopt::adopt(
        Some("chats"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    // Adopted under chats/_home/weechat (the `_home/` per-subtree
    // routing tells the symlink handler to deploy back to $HOME/.X).
    let pack_dir = env.dotfiles_root.join("chats/_home/weechat");
    env.assert_dir_exists(&pack_dir);
    env.assert_regular_file(&pack_dir.join("weechat.conf"), "[server]");

    // Re-deploying with `dodot up` puts the symlink back at $HOME/.weechat
    // — the round-trip the rename was designed to preserve.
    commands::up::up(Some(&["chats".into()]), &ctx).unwrap();
    let user_path = env.home.join(".weechat");
    assert!(
        env.fs.is_symlink(&user_path),
        "~/.weechat should be a symlink after re-deploy"
    );
}

/// **Round-trip property** — the critical contract between `adopt` and
/// `resolve_target`. For every `$HOME` source that `adopt` accepts,
/// feeding the `derive_pack_filename` result back through
/// `resolve_target` must return the original source path.
///
/// `derive_pack_filename` encodes the *inverse* of `resolve_target`'s
/// priority rules (force_home, home. prefix, _home/ directory). The
/// two functions are separately implemented but must stay lockstep;
/// this test catches any drift directly.
///
/// Cases cover every accepted branch:
///   - force_home file (`~/.bashrc`)
///   - force_home directory (`~/.ssh`)
///   - dotted non-force_home file (`~/.vimrc`)
///   - dotted non-force_home directory (`~/.weechat`)
///
/// The refused branch (non-dotted $HOME entry) is covered by the
/// explicit refusal test `adopt_refuses_non_dotted_home_entry`.
#[test]
fn pack_filename_round_trips_through_resolve_target() {
    use crate::commands::adopt::derive_pack_filename;
    use crate::handlers::symlink::resolve_target;

    // Default force_home: match what dodot ships (keep this minimal
    // and explicit so test failures point at a real behavior change).
    let force_home: Vec<String> = vec![
        "ssh".into(),
        "gnupg".into(),
        "aws".into(),
        "kube".into(),
        "bashrc".into(),
        "zshrc".into(),
        "profile".into(),
        "inputrc".into(),
    ];
    let config = crate::handlers::HandlerConfig {
        force_home: force_home.clone(),
        ..crate::handlers::HandlerConfig::default()
    };

    let paths = crate::paths::XdgPather::builder()
        .home("/home/alice")
        .dotfiles_root("/home/alice/dotfiles")
        .xdg_config_home("/home/alice/.config")
        .build()
        .unwrap();

    struct Case {
        pack: &'static str,
        // The file/dir name as it would appear inside $HOME (.vimrc, .ssh, …).
        home_name: &'static str,
        is_dir: bool,
        // What `derive_pack_filename` should produce (here as documentation; the
        // test only asserts the round-trip, not the literal pack filename — a
        // future refactor of the inverse rules is allowed to pick a different
        // internal representation as long as the round-trip still holds).
        expected_pack_filename: &'static str,
    }

    let cases = [
        Case {
            pack: "shell",
            home_name: ".bashrc",
            is_dir: false,
            expected_pack_filename: "bashrc",
        },
        Case {
            pack: "net",
            home_name: ".ssh",
            is_dir: true,
            expected_pack_filename: "ssh",
        },
        Case {
            pack: "vim",
            home_name: ".vimrc",
            is_dir: false,
            expected_pack_filename: "home.vimrc",
        },
        Case {
            pack: "chats",
            home_name: ".weechat",
            is_dir: true,
            expected_pack_filename: "_home/weechat",
        },
    ];

    for c in &cases {
        let derived =
            derive_pack_filename(c.home_name, c.is_dir, &force_home).unwrap_or_else(|e| {
                panic!(
                    "derive_pack_filename refused accepted case {:?}: {e}",
                    c.home_name
                )
            });
        assert_eq!(
            derived, c.expected_pack_filename,
            "documentation-expected pack filename drifted for {}",
            c.home_name
        );

        let target = resolve_target(c.pack, &derived, &config, &paths);
        let expected_source = std::path::PathBuf::from(format!("/home/alice/{}", c.home_name));
        assert_eq!(
            target,
            expected_source,
            "round-trip broke for {}: derive_pack_filename → {} → resolve_target → {} \
             (expected back at {})",
            c.home_name,
            derived,
            target.display(),
            expected_source.display(),
        );
    }

    // Refused case: non-dotted entry — no round-trip path exists.
    let refused = derive_pack_filename("my_script.sh", false, &force_home);
    assert!(
        refused.is_err(),
        "non-dotted $HOME entry must be refused, got: {refused:?}"
    );
}

#[test]
fn adopt_preserves_inner_symlinks_as_symlinks() {
    // Uses a dotted directory (post-#2: non-dotted $HOME entries are
    // refused). Test intent: inner symlinks are preserved during the
    // copy phase. The `_home/` path comes from #1's dotted-dir
    // round-trip rename.
    let env = TempEnvironment::builder()
        .pack("shell")
        .file("placeholder", "")
        .done()
        .home_file(".mydir/real.txt", "hello")
        .build();

    // Create an inner symlink: .mydir/alias -> .mydir/real.txt
    let inner_target = env.home.join(".mydir/real.txt");
    let inner_link = env.home.join(".mydir/alias");
    env.fs.symlink(&inner_target, &inner_link).unwrap();

    let ctx = make_ctx(&env);
    let source = env.home.join(".mydir");
    commands::adopt::adopt(
        Some("shell"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    // The inner link should still be a symlink inside the pack copy.
    let copied_link = env.dotfiles_root.join("shell/_home/mydir/alias");
    assert!(
        env.fs.is_symlink(&copied_link),
        "inner symlink should be preserved as a symlink, not followed"
    );
}

/// `~/.config/<X>/<rest>` is now a recognized adopt source: the first
/// segment under `$XDG_CONFIG_HOME` is the inferred pack name, and the
/// remainder is the in-pack path. Round-trip is the resolver's default
/// rule — pack `nvim` containing `init.lua` deploys to
/// `$XDG_CONFIG_HOME/nvim/init.lua` on `dodot up`. (Pre-inference, this
/// case was refused as a nested source.)
#[test]
fn adopt_xdg_nested_file_lands_at_pack_root() {
    let env = TempEnvironment::builder()
        .pack("nvim")
        .file("placeholder", "")
        .done()
        .home_file(".config/nvim/init.lua", "-- config")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".config/nvim/init.lua");

    commands::adopt::adopt(
        Some("nvim"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    // No prefix gymnastics: pack `nvim`'s default deploy rule (Priority
    // 4 — `$XDG/<pack>/<rel>`) lands `init.lua` back at the original
    // `~/.config/nvim/init.lua`. So the in-pack name is just `init.lua`.
    let pack_file = env.dotfiles_root.join("nvim/init.lua");
    env.assert_regular_file(&pack_file, "-- config");
    assert!(env.fs.is_symlink(&source));
    let target = env.fs.readlink(&source).unwrap();
    assert_eq!(target, pack_file);
}

/// Pack name can be omitted when the source carries pack structure
/// under `$XDG_CONFIG_HOME`: `dodot adopt ~/.config/nvim/init.lua` (no
/// `--into`) auto-detects pack `nvim` and creates it if missing.
#[test]
fn adopt_xdg_source_infers_pack_and_auto_creates() {
    let env = TempEnvironment::builder()
        .home_file(".config/ghostty/config", "theme = dark")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".config/ghostty/config");

    commands::adopt::adopt(
        /*pack_override=*/ None,
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    // Pack auto-created at `<dotfiles>/ghostty/`, file landed at root.
    let pack_dir = env.dotfiles_root.join("ghostty");
    env.assert_dir_exists(&pack_dir);
    env.assert_regular_file(&pack_dir.join("config"), "theme = dark");
    assert!(env.fs.is_symlink(&source));
}

/// Adopting `~/.config/<X>/` (the pack-root directory itself) expands
/// into per-child plans rather than making the directory one big
/// symlink-to-pack-root. Each top-level entry becomes a top-level pack
/// member, so `dodot up` deploys per-entry like any other pack.
#[test]
fn adopt_xdg_pack_root_directory_expands_to_children() {
    let env = TempEnvironment::builder()
        .home_file(".config/helix/config.toml", "theme = \"onedark\"")
        .home_file(".config/helix/themes/extra.toml", "fg = \"white\"")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".config/helix");

    commands::adopt::adopt(
        None,
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    // Each top-level child of `~/.config/helix/` became its own pack
    // entry — `config.toml` (file) and `themes/` (dir) — both at pack
    // root, not nested under another `helix/`.
    let pack_dir = env.dotfiles_root.join("helix");
    env.assert_regular_file(&pack_dir.join("config.toml"), "theme = \"onedark\"");
    env.assert_regular_file(&pack_dir.join("themes/extra.toml"), "fg = \"white\"");
    // Original entries are now symlinks at their original paths
    // (one per top-level child, not one for the whole helix/ dir).
    assert!(env
        .fs
        .is_symlink(&env.home.join(".config/helix/config.toml")));
    assert!(env.fs.is_symlink(&env.home.join(".config/helix/themes")));
    // Parent directory `~/.config/helix/` itself stays a real directory
    // — only its children became symlinks.
    assert!(!env.fs.is_symlink(&source));
}

/// `~/.config/` itself is too broad to adopt as a single unit; refuse
/// explicitly so the user adopts an app subdirectory instead.
#[test]
fn adopt_xdg_root_itself_refused() {
    let env = TempEnvironment::builder()
        .home_file(".config/nvim/init.lua", "-- config")
        .build();
    let ctx = make_ctx(&env);
    let source = env.config_home.clone();

    let err = commands::adopt::adopt(
        None,
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap_err();
    let msg = format!("{err}");
    assert!(
        msg.contains("$XDG_CONFIG_HOME"),
        "expected XDG-root refusal, got: {msg}"
    );
}

/// Pack-root directory expansion under `--into` reroute keeps the
/// `_xdg/<X>/` prefix on each child so the round-trip survives the
/// pack-name change. Without this, expanded children would land at
/// pack root and `dodot up` would deploy them to `$XDG/<override>/...`
/// instead of the original `$XDG/<X>/...`. (Regression for Copilot
/// review on PR #85.)
#[test]
fn adopt_xdg_pack_root_expansion_with_override_uses_xdg_prefix() {
    let env = TempEnvironment::builder()
        .pack("toolbox")
        .file("placeholder", "")
        .done()
        .home_file(".config/lazygit/config.yml", "gui:\n  theme: dark")
        .home_file(".config/lazygit/themes/x.yml", "fg: white")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".config/lazygit");

    commands::adopt::adopt(
        Some("toolbox"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    // Each expanded child lives under `toolbox/_xdg/lazygit/...` so the
    // resolver's Priority 2 `_xdg/` prefix routes back to
    // `~/.config/lazygit/<child>` regardless of the override pack name.
    env.assert_regular_file(
        &env.dotfiles_root.join("toolbox/_xdg/lazygit/config.yml"),
        "gui:\n  theme: dark",
    );
    env.assert_regular_file(
        &env.dotfiles_root.join("toolbox/_xdg/lazygit/themes/x.yml"),
        "fg: white",
    );
    // Each original child is now a symlink (per-child expansion); the
    // pack-root dir itself stays a real directory.
    assert!(env
        .fs
        .is_symlink(&env.home.join(".config/lazygit/config.yml")));
    assert!(env.fs.is_symlink(&env.home.join(".config/lazygit/themes")));
    assert!(!env.fs.is_symlink(&source));
}

/// `--into <pack>` for an XDG source where the override differs from
/// the inferred pack name uses `_xdg/<X>/<rest>` so round-trip via
/// Priority 2 still lands the deployed file at the original location.
#[test]
fn adopt_xdg_with_into_override_uses_xdg_prefix() {
    let env = TempEnvironment::builder()
        .pack("toolbox")
        .file("placeholder", "")
        .done()
        .home_file(".config/lazygit/config.yml", "gui:\n  theme: dark")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".config/lazygit/config.yml");

    commands::adopt::adopt(
        Some("toolbox"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    // Round-trip via `_xdg/lazygit/config.yml`: the `_xdg/` prefix
    // bypasses pack-namespacing so the deployed path is still
    // `~/.config/lazygit/config.yml` despite the file living in
    // pack `toolbox`.
    let pack_file = env.dotfiles_root.join("toolbox/_xdg/lazygit/config.yml");
    env.assert_regular_file(&pack_file, "gui:\n  theme: dark");
    assert!(env.fs.is_symlink(&source));
}

/// Adopting a file under `~/Library/Application Support/<X>/` infers
/// pack `<X>`, places the file at `_app/<X>/<rest>` in the pack tree,
/// and round-trips via the resolver's Priority 2c `_app/` prefix back
/// to the original AppSupport location. The `TempEnvironment` pins
/// `app_support_dir` under the temp HOME on every platform so this
/// test runs identically on Linux and macOS.
#[test]
fn adopt_app_support_source_round_trips_through_app_prefix() {
    let env = TempEnvironment::builder()
        .home_file(
            "Library/Application Support/Code/User/settings.json",
            "{\"editor.fontSize\": 14}",
        )
        .build();

    let ctx = make_ctx(&env);
    let source = env.app_support.join("Code/User/settings.json");

    commands::adopt::adopt(
        /*pack_override=*/ None,
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    // Pack auto-created at `<dotfiles>/Code/`. The file lives at
    // `_app/Code/User/settings.json` — the prefix is mandatory at
    // natural pack name because the default rule routes through XDG,
    // not app_support_dir.
    let pack_file = env.dotfiles_root.join("Code/_app/Code/User/settings.json");
    env.assert_regular_file(&pack_file, "{\"editor.fontSize\": 14}");

    // Original deploy location is now a symlink — and the symlink
    // chain points (eventually) back at the pack copy. Resolve via
    // resolve_target_full to confirm round-trip.
    assert!(env.fs.is_symlink(&source));

    use crate::handlers::symlink::{resolve_target_full, Resolution};
    let resolution = resolve_target_full(
        "Code",
        "_app/Code/User/settings.json",
        &Default::default(),
        env.paths.as_ref(),
    );
    match resolution {
        Resolution::Path(p) => assert_eq!(p, source),
        Resolution::Skip { reason } => panic!("expected Path, got Skip({reason})"),
    }
}

/// Adopting `~/Library/Application Support/<X>/` (the directory
/// itself) expands into per-child plans, mirroring the XDG pack-root
/// expansion. Each top-level entry under the AppSupport folder
/// becomes a top-level pack entry, prefixed with `_app/<X>/`.
#[test]
fn adopt_app_support_pack_root_directory_expands_to_children() {
    let env = TempEnvironment::builder()
        .home_file(
            "Library/Application Support/Cursor/User/settings.json",
            "{}",
        )
        .home_file(
            "Library/Application Support/Cursor/User/keybindings.json",
            "[]",
        )
        .build();

    let ctx = make_ctx(&env);
    let source = env.app_support.join("Cursor");

    commands::adopt::adopt(
        None,
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    // The pack-root directory expanded: the single child of `Cursor/`
    // is `User/`, so the pack contains `_app/Cursor/User/` (a
    // directory whose contents come along).
    let pack_dir = env.dotfiles_root.join("Cursor");
    env.assert_dir_exists(&pack_dir);
    env.assert_regular_file(&pack_dir.join("_app/Cursor/User/settings.json"), "{}");
    env.assert_regular_file(&pack_dir.join("_app/Cursor/User/keybindings.json"), "[]");
    // The expanded child (`User/`) at the original AppSupport
    // location is now a symlink, but the parent `Cursor/` itself
    // stays a real directory.
    assert!(env.fs.is_symlink(&env.app_support.join("Cursor/User")));
    assert!(!env.fs.is_symlink(&source));
}

/// M5 capitalization-heuristic advisory: when a user adopts an
/// AppSupport source whose folder name passes the GUI-app heuristic
/// (`Code`, uppercase), adopt emits a tip pointing at the
/// `app_aliases` ergonomic. The pack tree itself is unaffected — the
/// hint is purely advisory.
#[test]
fn adopt_app_support_emits_capitalization_hint() {
    let env = TempEnvironment::builder()
        .home_file("Library/Application Support/Code/User/settings.json", "{}")
        .build();

    let ctx = make_ctx(&env);
    let source = env.app_support.join("Code/User/settings.json");

    let result = commands::adopt::adopt(
        /*pack_override=*/ None,
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    assert!(
        result
            .warnings
            .iter()
            .any(|w| w.contains("app_aliases") && w.contains("Code")),
        "expected an `app_aliases` tip in warnings, got: {:?}",
        result.warnings
    );
}

/// Reverse-DNS bundle-ID folders (`com.colliderli.iina`,
/// `dev.warp.Warp-Stable`) get a much better rename suggestion when
/// the M6 brew probe identifies a matching cask: prefer the cask
/// token (`iina`) over the awful whitespace-strip-lowercase fallback
/// (`comcolliderliiina`). Real IINA case from user testing on PR #91.
#[test]
#[cfg_attr(not(target_os = "macos"), ignore = "macOS-only enrichment paths")]
fn adopt_app_support_reverse_dns_uses_cask_token_in_tip() {
    let env = TempEnvironment::builder()
        .home_file(
            "Library/Application Support/com.colliderli.iina/input_conf/mine.conf",
            "x",
        )
        .build();

    let runner = Arc::new(CannedRunner::new());
    runner.respond(&["brew", "list", "--cask", "--versions"], "iina 1.4.0\n", 0);
    runner.respond(
        &["brew", "info", "--json=v2", "--cask", "iina"],
        r#"{"casks": [{
            "token": "iina",
            "artifacts": [
                {"app": ["IINA.app"]},
                {"zap": [{"trash": ["~/Library/Application Support/com.colliderli.iina"]}]}
            ]
        }]}"#,
        0,
    );
    let ctx = make_ctx_with_runner(&env, runner);
    let source = env
        .app_support
        .join("com.colliderli.iina/input_conf/mine.conf");

    let result = commands::adopt::adopt(
        /*pack_override=*/ None,
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    let tip = result
        .warnings
        .iter()
        .find(|w| w.contains("app_aliases"))
        .unwrap_or_else(|| panic!("expected an app_aliases tip, got: {:?}", result.warnings));

    // The good outcome: tip suggests `iina` as the rename target.
    assert!(
        tip.contains("renaming the pack to `iina`"),
        "expected cask-token-based rename suggestion (`iina`), got: {tip}"
    );
    // And explicitly NOT the whitespace-strip-lowercase fallback,
    // which would be `comcolliderliiina` for this folder.
    assert!(
        !tip.contains("comcolliderliiina"),
        "rename suggestion fell back to lowercase mangling instead of cask token: {tip}"
    );
    // The tip credits the cask so the user knows where the
    // recommendation came from.
    assert!(
        tip.contains("matches homebrew cask"),
        "tip should credit the cask source, got: {tip}"
    );
}

/// When no installed cask matches the folder, the tip falls back to
/// the original whitespace-strip-lowercase suggestion. Pins the
/// fallback so a refactor doesn't accidentally regress the no-cask
/// path (the heuristic still triggers on uppercase folders even when
/// brew has nothing to say).
#[test]
#[cfg_attr(not(target_os = "macos"), ignore = "macOS-only enrichment paths")]
fn adopt_app_support_falls_back_to_lowercase_when_no_cask_match() {
    // `Tinkerbell` — uppercase enough to trigger the heuristic, but
    // no real cask owns it, so the brew probe returns empty and the
    // tip falls back to the lowercase suggestion.
    let env = TempEnvironment::builder()
        .home_file("Library/Application Support/Tinkerbell/settings.json", "{}")
        .build();

    let runner = Arc::new(CannedRunner::new());
    runner.respond(&["brew", "list", "--cask", "--versions"], "", 0);
    let ctx = make_ctx_with_runner(&env, runner);
    let source = env.app_support.join("Tinkerbell/settings.json");

    let result = commands::adopt::adopt(
        None,
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    let tip = result
        .warnings
        .iter()
        .find(|w| w.contains("app_aliases"))
        .unwrap_or_else(|| panic!("expected an app_aliases tip, got: {:?}", result.warnings));

    // Fallback suggestion: lowercased pack name (no spaces here, but
    // the casing transformation still applies).
    assert!(
        tip.contains("renaming the pack to `tinkerbell`"),
        "expected fallback rename suggestion, got: {tip}"
    );
    assert!(
        !tip.contains("matches homebrew cask"),
        "tip should not claim a cask match when none exists: {tip}"
    );
}

/// The advisory is suppressed when the user passed `--into <pack>`:
/// they already chose their pack name, so suggesting another one
/// would be noise. The pack used here (`Code`) only exists to satisfy
/// `--into`'s typo-guard requirement.
#[test]
fn adopt_app_support_into_override_suppresses_hint() {
    let env = TempEnvironment::builder()
        .pack("Code")
        .file("placeholder", "")
        .done()
        .home_file("Library/Application Support/Code/User/settings.json", "{}")
        .build();

    let ctx = make_ctx(&env);
    let source = env.app_support.join("Code/User/settings.json");

    let result = commands::adopt::adopt(
        Some("Code"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    assert!(
        !result.warnings.iter().any(|w| w.contains("app_aliases")),
        "expected no app_aliases tip with --into, got: {:?}",
        result.warnings
    );
}

/// Lowercase CLI-tool-style folder names (`nvim`, `helix`, …) don't
/// trigger the heuristic. An XDG adopt of a typical CLI tool stays
/// hint-free.
#[test]
fn adopt_xdg_lowercase_pack_emits_no_hint() {
    let env = TempEnvironment::builder()
        .home_file(".config/nvim/init.lua", "-- nvim")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".config/nvim/init.lua");

    let result = commands::adopt::adopt(
        None,
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    assert!(
        !result.warnings.iter().any(|w| w.contains("app_aliases")),
        "expected no app_aliases tip for plain XDG adopt, got: {:?}",
        result.warnings
    );
}

/// Multiple sources whose inference picks different packs is refused
/// (without `--into`); the message names the conflicting candidates.
#[test]
fn adopt_disagreeing_inferred_packs_refused() {
    let env = TempEnvironment::builder()
        .home_file(".config/nvim/init.lua", "-- nvim")
        .home_file(".config/helix/config.toml", "# helix")
        .build();

    let ctx = make_ctx(&env);
    let sources = vec![
        env.home.join(".config/nvim/init.lua"),
        env.home.join(".config/helix/config.toml"),
    ];

    let err = commands::adopt::adopt(None, &sources, false, false, false, &ctx).unwrap_err();
    let msg = format!("{err}");
    assert!(
        msg.contains("different packs"),
        "expected disagreement message, got: {msg}"
    );
    assert!(msg.contains("nvim") && msg.contains("helix"));
}

/// Without `--into`, a HOME source can't infer a pack and adopt fails
/// with a hint pointing at `--into`.
#[test]
fn adopt_home_source_without_into_requires_pack() {
    let env = TempEnvironment::builder()
        .home_file(".vimrc", "set nocompatible")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".vimrc");
    let err = commands::adopt::adopt(
        None,
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap_err();
    let msg = format!("{err}");
    assert!(msg.contains("--into"), "expected '--into' hint, got: {msg}");
}

#[test]
fn adopt_already_adopted_source_is_skipped() {
    // Direct symlink to pack source — adopt skips with a #44 message
    // pointing the user at `dodot up` to upgrade to the full chain.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "content")
        .done()
        .build();

    // Pre-link home file to the pack.
    let source = env.home.join(".vimrc");
    let pack_file = env.dotfiles_root.join("vim/vimrc");
    env.fs.symlink(&pack_file, &source).unwrap();

    let ctx = make_ctx(&env);
    let result = commands::adopt::adopt(
        Some("vim"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    let warning = result
        .warnings
        .iter()
        .find(|w| w.contains("skipped"))
        .unwrap_or_else(|| panic!("expected a skipped warning, got: {:?}", result.warnings));
    assert!(
        warning.contains("direct symlink to pack source"),
        "expected #44 'direct symlink' wording, got: {warning}"
    );
    assert!(
        warning.contains("dodot up vim"),
        "warning should point user at `dodot up vim`, got: {warning}"
    );
    // Source still a symlink, pack file untouched.
    assert!(env.fs.is_symlink(&source));
    env.assert_regular_file(&pack_file, "content");
}

/// Regression for #44: when the source is fully managed (the user
/// symlink points at dodot's data_dir), adopt skips with the original
/// "already managed by dodot" wording — no upgrade needed.
#[test]
fn adopt_fully_managed_source_keeps_original_skip_message() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "content")
        .done()
        .build();

    let ctx = make_ctx(&env);
    // First, deploy normally so user_path goes through the dodot chain.
    // Under #48 the default deploy target is $XDG_CONFIG_HOME/<pack>/<file>.
    commands::up::up(Some(&["vim".into()]), &ctx).unwrap();

    let source = env.home.join(".config/vim/vimrc");
    assert!(env.fs.is_symlink(&source));

    let result = commands::adopt::adopt(
        Some("vim"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap();

    let warning = result
        .warnings
        .iter()
        .find(|w| w.contains("skipped"))
        .unwrap_or_else(|| panic!("expected a skipped warning, got: {:?}", result.warnings));
    assert!(
        warning.contains("already managed by dodot"),
        "fully-managed case should keep original wording, got: {warning}"
    );
    assert!(
        !warning.contains("direct symlink"),
        "fully-managed case should NOT use the #44 'direct symlink' wording, got: {warning}"
    );
}

/// Regression for #44: `dodot up` auto-replaces a pre-existing regular
/// file whose content is byte-identical to the pack source — no
/// `--force` needed, no conflict reported.
#[test]
fn up_auto_replaces_content_equivalent_pre_existing_file() {
    let env = TempEnvironment::builder()
        .pack("git")
        .file("home.gitconfig", "[user]\n  name = test")
        .done()
        // Same content as the pack source.
        .home_file(".gitconfig", "[user]\n  name = test")
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();

    assert_eq!(
        result.message.as_deref(),
        Some("Packs deployed."),
        "no errors expected for content-equivalent file, got: {:?}",
        result.message
    );
    // ~/.gitconfig is now a symlink (the dodot chain), not a regular file.
    let user_path = env.home.join(".gitconfig");
    assert!(
        env.fs.is_symlink(&user_path),
        "user file should now be a symlink"
    );
    // Content reaching the user is unchanged.
    assert_eq!(
        env.fs.read_to_string(&user_path).unwrap(),
        "[user]\n  name = test"
    );
    // And status agrees: deployed, not a conflict.
    let status = commands::status::status(None, &ctx).unwrap();
    let file = &status.packs[0].files[0];
    assert_eq!(file.status, "deployed");
}

/// Regression for #44: `dodot up` still refuses (without `--force`) when
/// the pre-existing file's content differs from the source. The
/// auto-replace only kicks in for content-equivalent files.
#[test]
fn up_still_refuses_content_different_pre_existing_file() {
    let env = TempEnvironment::builder()
        .pack("git")
        .file("home.gitconfig", "[user]\n  name = new")
        .done()
        .home_file(".gitconfig", "[user]\n  name = old")
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();

    assert_eq!(
        result.message.as_deref(),
        Some("Packs deployed with errors."),
        "different content should still conflict, got: {:?}",
        result.message
    );
    // Original content preserved.
    env.assert_file_contents(&env.home.join(".gitconfig"), "[user]\n  name = old");
}

/// Regression for #44: `status` does NOT flag a content-equivalent
/// pre-existing file as PendingConflict (since `up` will handle it
/// without `--force`). Stays plain `pending`, no footnote.
#[test]
fn status_does_not_flag_content_equivalent_file_as_conflict() {
    let env = TempEnvironment::builder()
        .pack("git")
        .file("home.gitconfig", "[user]\n  name = test")
        .done()
        .home_file(".gitconfig", "[user]\n  name = test")
        .build();

    let ctx = make_ctx(&env);
    let status = commands::status::status(None, &ctx).unwrap();
    let file = &status.packs[0].files[0];

    assert_eq!(
        file.status, "pending",
        "content-equivalent file should be plain pending (auto-replaceable), got: {}",
        file.status
    );
    assert!(
        file.note_ref.is_none(),
        "no note_ref for auto-replaceable case"
    );
    assert!(
        status.notes.is_empty(),
        "no notes for auto-replaceable case, got: {:?}",
        status.notes
    );
}

#[test]
fn adopt_relative_path_with_curdir_normalizes() {
    // `dodot adopt mypack ./.vimrc` run from HOME must not be rejected as
    // "nested" — the `.` component should normalize away so parent == HOME.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("placeholder", "")
        .done()
        .home_file(".vimrc", "content")
        .build();

    // Run with CWD = HOME so the relative path resolves naturally.
    let prev_cwd = std::env::current_dir().unwrap();
    std::env::set_current_dir(&env.home).unwrap();
    let ctx = make_ctx(&env);
    let result = commands::adopt::adopt(
        Some("vim"),
        &[std::path::PathBuf::from("./.vimrc")],
        false,
        false,
        false,
        &ctx,
    );
    std::env::set_current_dir(prev_cwd).unwrap();

    result.expect("adopt should accept ./.vimrc when CWD is HOME");
    env.assert_regular_file(&env.dotfiles_root.join("vim/home.vimrc"), "content");
    assert!(env.fs.is_symlink(&env.home.join(".vimrc")));
}

#[test]
fn adopt_ignored_pack_refused() {
    let env = TempEnvironment::builder()
        .pack("disabled")
        .file("placeholder", "")
        .ignored()
        .done()
        .home_file(".vimrc", "x")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".vimrc");
    let err = commands::adopt::adopt(
        Some("disabled"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap_err();
    assert!(
        matches!(err, crate::DodotError::PackInvalid { .. }),
        "expected PackInvalid, got: {err}"
    );
}

#[test]
fn adopt_filename_matching_pack_ignore_refused() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("placeholder", "")
        .config("[pack]\nignore = [\"*.bak\"]")
        .done()
        .home_file(".vimrc.bak", "old")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".vimrc.bak");
    let err = commands::adopt::adopt(
        Some("vim"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap_err();
    let msg = format!("{err}");
    assert!(
        msg.contains("ignore"),
        "expected ignore-pattern message, got: {msg}"
    );
}

#[test]
fn adopt_broken_pack_blocks_conflict_check() {
    // If another pack fails intent collection, adoption must refuse rather
    // than silently proceed — otherwise the conflict check produces a false
    // negative and we'd mutate into a state `dodot up` would later reject.
    let env = TempEnvironment::builder()
        .pack("broken")
        .file("config.toml.tmpl", "{{ missing_var }}")
        .done()
        .pack("target")
        .file("placeholder", "")
        .done()
        .home_file(".vimrc", "content")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".vimrc");
    let err = commands::adopt::adopt(
        Some("target"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap_err();

    // The error surfaces from the broken pack's intent collection
    // (template render failure), not a silent success.
    assert!(
        matches!(err, crate::DodotError::TemplateRender { .. }),
        "expected the broken pack's error to surface, got: {err}"
    );

    // Home untouched; no pack copy left behind.
    env.assert_regular_file(&source, "content");
    env.assert_not_exists(&env.dotfiles_root.join("target/vimrc"));
}

#[test]
fn adopt_deploy_conflict_refused() {
    // Two packs would both end up claiming ~/.bashrc after adoption.
    // Using `bashrc` because it's in `force_home` — different packs both
    // deploy it to ~/.bashrc, producing a real cross-pack conflict.
    let env = TempEnvironment::builder()
        .pack("unix")
        .file("bashrc", "existing")
        .done()
        .pack("work")
        .file("placeholder", "")
        .done()
        .home_file(".bashrc", "new")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".bashrc");
    let err = commands::adopt::adopt(
        Some("work"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap_err();
    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "expected CrossPackConflict, got: {err}"
    );

    // Home untouched.
    env.assert_regular_file(&source, "new");
    // Pack copy rolled back.
    env.assert_not_exists(&env.dotfiles_root.join("work/bashrc"));
}

#[test]
fn adopt_deploy_conflict_not_bypassed_by_force() {
    let env = TempEnvironment::builder()
        .pack("unix")
        .file("bashrc", "existing")
        .done()
        .pack("work")
        .file("placeholder", "")
        .done()
        .home_file(".bashrc", "new")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".bashrc");
    let err = commands::adopt::adopt(
        Some("work"),
        std::slice::from_ref(&source),
        true, // --force should NOT bypass deploy conflicts
        false,
        false,
        &ctx,
    )
    .unwrap_err();
    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "--force must not bypass deploy conflicts, got: {err}"
    );
}

#[test]
fn adopt_dry_run_makes_no_changes() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("placeholder", "")
        .done()
        .home_file(".vimrc", "content")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".vimrc");

    let result = commands::adopt::adopt(
        Some("vim"),
        std::slice::from_ref(&source),
        false,
        false,
        true, // dry-run
        &ctx,
    )
    .unwrap();
    assert!(result.dry_run);

    // Nothing changed at home.
    env.assert_regular_file(&source, "content");
    assert!(!env.fs.is_symlink(&source));
    // No copy in pack.
    env.assert_not_exists(&env.dotfiles_root.join("vim/home.vimrc"));
}

#[test]
fn adopt_no_follow_keeps_source_symlink_as_symlink() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("placeholder", "")
        .done()
        .home_file("real_vimrc", "real content")
        .build();

    // ~/.vimrc is a symlink to ~/real_vimrc
    let real = env.home.join("real_vimrc");
    let source = env.home.join(".vimrc");
    env.fs.symlink(&real, &source).unwrap();

    let ctx = make_ctx(&env);
    commands::adopt::adopt(
        Some("vim"),
        std::slice::from_ref(&source),
        false,
        true, // --no-follow
        false,
        &ctx,
    )
    .unwrap();

    // The pack copy should be a symlink (not a regular file with copied content).
    let pack_copy = env.dotfiles_root.join("vim/home.vimrc");
    assert!(
        env.fs.is_symlink(&pack_copy),
        "--no-follow should preserve source symlink as a symlink in the pack"
    );
    // Home path replaced with a symlink into the pack.
    assert!(env.fs.is_symlink(&source));
}

#[cfg(unix)]
#[test]
fn adopt_force_preserves_old_content_when_copy_fails() {
    // With --force, the old destination must remain intact if the copy of
    // the new source fails. Previously copy_all removed the dest before
    // copying, so a copy failure silently lost the old content.
    use std::os::unix::fs::PermissionsExt;

    let env = TempEnvironment::builder()
        .pack("vim")
        .file("home.vimrc", "OLD")
        .done()
        .home_file(".vimrc", "NEW")
        .build();

    let source = env.home.join(".vimrc");
    // chmod 000 makes the file unreadable, so the copy phase fails at
    // read-time without tripping preflight (which uses lstat only).
    std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o000)).unwrap();

    let ctx = make_ctx(&env);
    let result = commands::adopt::adopt(
        Some("vim"),
        std::slice::from_ref(&source),
        true, // --force
        false,
        false,
        &ctx,
    );

    // Restore perms so drop-cleanup works regardless of assertion outcome.
    let _ = std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o644));

    assert!(
        result.is_err(),
        "adopt should fail when the source is unreadable"
    );
    // The old pack content must survive the failed --force adoption.
    env.assert_regular_file(&env.dotfiles_root.join("vim/home.vimrc"), "OLD");
    // Home file also untouched.
    env.assert_regular_file(&source, "NEW");
    // No lingering stage file in the pack.
    let leftover = env.fs.read_dir(&env.dotfiles_root.join("vim")).unwrap();
    for entry in leftover {
        assert!(
            !entry.name.contains("dodot-adopt-stage"),
            "stage file leaked into pack: {}",
            entry.name
        );
    }
}

#[test]
fn adopt_no_follow_on_dangling_symlink_succeeds() {
    // A dangling symlink under --no-follow: readability check must inspect
    // the link itself (lstat), not try to follow it into a non-existent
    // target. Regression test: check_readable previously used fs.is_dir +
    // fs.stat, both of which follow symlinks and would fail here.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("placeholder", "")
        .done()
        .build();

    // Create ~/.dangling -> /does/not/exist (target intentionally missing).
    let source = env.home.join(".dangling");
    env.fs
        .symlink(std::path::Path::new("/does/not/exist"), &source)
        .unwrap();

    let ctx = make_ctx(&env);
    commands::adopt::adopt(
        Some("vim"),
        std::slice::from_ref(&source),
        false,
        true, // --no-follow
        false,
        &ctx,
    )
    .expect("adopt with --no-follow on a dangling symlink should succeed");

    // The pack copy should itself be a symlink (preserving the dangling link).
    // Post-#48 adopt rename: ~/.dangling → vim/home.dangling.
    let pack_copy = env.dotfiles_root.join("vim/home.dangling");
    assert!(env.fs.is_symlink(&pack_copy));
    let target = env.fs.readlink(&pack_copy).unwrap();
    assert_eq!(target, std::path::PathBuf::from("/does/not/exist"));
}

#[test]
fn adopt_nonexistent_source_errors() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("placeholder", "")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".does-not-exist");
    let err = commands::adopt::adopt(
        Some("vim"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap_err();
    assert!(matches!(err, crate::DodotError::Fs { .. }), "got: {err}");
}

#[test]
fn adopt_empty_sources_errors() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("placeholder", "")
        .done()
        .build();
    let ctx = make_ctx(&env);
    let err = commands::adopt::adopt(Some("vim"), &[], false, false, false, &ctx).unwrap_err();
    let msg = format!("{err}");
    assert!(msg.contains("no files"), "got: {msg}");
}

// ── addignore ───────────────────────────────────────────────

#[test]
fn addignore_creates_file() {
    let env = TempEnvironment::builder()
        .pack("scratch")
        .file("notes", "x")
        .done()
        .build();
    let ctx = make_ctx(&env);

    let result = commands::addignore::addignore("scratch", &ctx).unwrap();
    assert!(result.message.contains("ignored"));
    env.assert_exists(&env.dotfiles_root.join("scratch/.dodotignore"));
}

#[test]
fn addignore_idempotent() {
    let env = TempEnvironment::builder()
        .pack("scratch")
        .file("notes", "x")
        .ignored()
        .done()
        .build();
    let ctx = make_ctx(&env);

    let result = commands::addignore::addignore("scratch", &ctx).unwrap();
    assert!(result.message.contains("already ignored"));
}

// ── nonexistent pack ───────────────────────────────────────

#[test]
fn status_on_nonexistent_pack_returns_error() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "x")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let filter = vec!["nonexistent".into()];
    let err = commands::status::status(Some(&filter), &ctx).unwrap_err();
    assert!(
        matches!(err, crate::DodotError::PackNotFound { .. }),
        "expected PackNotFound, got: {err}"
    );
}

#[test]
fn up_on_nonexistent_pack_returns_error() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "x")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let filter = vec!["typo".into()];
    let err = commands::up::up(Some(&filter), &ctx).unwrap_err();
    assert!(
        matches!(err, crate::DodotError::PackNotFound { .. }),
        "expected PackNotFound, got: {err}"
    );
}

// ── down: already down ─────────────────────────────────────

#[test]
fn down_on_already_down_pack_says_nothing_to_do() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "x")
        .done()
        .build();

    let ctx = make_ctx(&env);
    // vim was never deployed — should not print misleading output
    let result = commands::down::down(None, &ctx).unwrap();
    assert_eq!(
        result.message.as_deref(),
        Some("Nothing to deactivate."),
        "should say nothing to deactivate"
    );
    assert!(result.packs.is_empty(), "should have no pack entries");
}

// ── addignore: warns about deployed ────────────────────────

#[test]
fn addignore_on_deployed_pack_warns() {
    let env = TempEnvironment::builder()
        .pack("git")
        .file("gitconfig", "[user]\n  name = test")
        .done()
        .build();

    let ctx = make_ctx(&env);
    // Deploy first
    commands::up::up(None, &ctx).unwrap();

    // Now addignore should warn
    let result = commands::addignore::addignore("git", &ctx).unwrap();
    assert!(result.message.contains("ignored"));
    let has_warning = result
        .details
        .iter()
        .any(|d| d.contains("currently deployed"));
    assert!(
        has_warning,
        "should warn about deployed pack: {:?}",
        result.details
    );
}

// ── adopt: pack not found hint ─────────────────────────────

#[test]
fn adopt_nonexistent_pack_returns_pack_not_found() {
    let env = TempEnvironment::builder()
        .home_file(".vimrc", "set nocompatible")
        .build();

    let ctx = make_ctx(&env);
    let source = env.home.join(".vimrc");
    let err = commands::adopt::adopt(
        Some("newpack"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        &ctx,
    )
    .unwrap_err();
    assert!(
        matches!(err, crate::DodotError::PackNotFound { .. }),
        "expected PackNotFound, got: {err}"
    );
}

// ── full lifecycle ──────────────────────────────────────────

#[test]
fn full_lifecycle_up_status_down_status() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "set nocompatible")
        .done()
        .pack("git")
        .file("gitconfig", "[user]\n  name = test")
        .done()
        .build();

    let ctx = make_ctx(&env);

    // 1. Status before up — all pending
    let s1 = commands::status::status(None, &ctx).unwrap();
    assert_eq!(s1.packs.len(), 2);
    for pack in &s1.packs {
        for file in &pack.files {
            assert_eq!(file.status, "pending");
        }
    }

    // 2. Up — deploy
    let up = commands::up::up(None, &ctx).unwrap();
    assert!(!up.packs.is_empty());

    // 3. Status after up — deployed
    let s2 = commands::status::status(None, &ctx).unwrap();
    let total_deployed: usize = s2
        .packs
        .iter()
        .flat_map(|p| &p.files)
        .filter(|f| f.status == "deployed")
        .count();
    assert!(total_deployed > 0);

    // 4. Down — remove
    commands::down::down(None, &ctx).unwrap();

    // 5. Status after down — pending again. Dangling user-side symlinks
    // left by `down` are not conflicts (executor handles them on
    // re-deploy), so they stay plain pending.
    let s3 = commands::status::status(None, &ctx).unwrap();
    for pack in &s3.packs {
        for file in &pack.files {
            assert_eq!(
                file.status, "pending",
                "{} should be pending after down, got {}",
                file.name, file.status
            );
        }
    }

    // 6. Up again — idempotent
    commands::up::up(None, &ctx).unwrap();
    let s4 = commands::status::status(None, &ctx).unwrap();
    let deployed_again: usize = s4
        .packs
        .iter()
        .flat_map(|p| &p.files)
        .filter(|f| f.status == "deployed")
        .count();
    assert_eq!(total_deployed, deployed_again, "idempotent re-deploy");
}

/// Regression for #43: status must distinguish "pending — clear to
/// deploy" from "pending — would conflict with a pre-existing file".
/// Both render under the `pending` *label*, but the conflict case gets
/// a `warning` status (so themes can color it differently) plus a
/// footnote explaining what's at the target path.
#[test]
fn status_surfaces_pre_existing_conflict_as_warning_with_footnote() {
    // Use `home.X` so the deploy targets ~/.X and collides with the
    // home_file fixture (under #48 the default deploy target is
    // $XDG_CONFIG_HOME/<pack>/X, which wouldn't collide).
    let env = TempEnvironment::builder()
        .pack("ghostty")
        .file("home.ghostrc", "theme=dark")
        .done()
        .home_file(".ghostrc", "theme=light")
        .pack("vim")
        .file("vimrc", "set nocompat")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    let ghostty = result
        .packs
        .iter()
        .find(|p| p.name == "ghostty")
        .expect("ghostty pack should appear");
    let vim = result
        .packs
        .iter()
        .find(|p| p.name == "vim")
        .expect("vim pack should appear");

    let ghostty_file = &ghostty.files[0];
    assert_eq!(
        ghostty_file.status, "warning",
        "ghostty/ghostrc collides with ~/.ghostrc — should surface as warning"
    );
    assert_eq!(
        ghostty_file.status_label, "pending",
        "label should be plain 'pending'; the [N] marker lives in a separate column, got: {}",
        ghostty_file.status_label
    );
    let ghostty_note = ghostty_file
        .note_ref
        .expect("ghostty row should carry a note_ref") as usize
        - 1;
    assert_eq!(
        result.notes.len(),
        1,
        "status should have exactly one note, got: {:?}",
        result.notes
    );
    assert!(
        result.notes[ghostty_note].body.contains(".ghostrc"),
        "note should mention the conflicting path, got: {}",
        result.notes[ghostty_note].body
    );
    assert!(
        result.notes[ghostty_note].body.contains("existing file"),
        "note should classify the target (existing file), got: {}",
        result.notes[ghostty_note].body
    );

    // vim has no pre-existing ~/.vimrc — should be plain pending, no note.
    let vim_file = &vim.files[0];
    assert_eq!(
        vim_file.status, "pending",
        "vim/vimrc has no conflict — should be plain pending"
    );
    assert_eq!(vim_file.status_label, "pending");
    assert!(
        vim_file.note_ref.is_none(),
        "vim row should carry no note_ref"
    );
}

/// Negative regression for #43: pre-existing symlinks at the user-target
/// path are NOT conflicts. The executor's `create_user_link` gracefully
/// replaces them (correct ones are no-ops, wrong/dangling ones are
/// removed and recreated), so flagging them would be a false positive.
/// Issue #44 may add an informational note for the equivalent-symlink
/// case, but that's separate from the conflict detection #43 introduces.
#[test]
fn status_does_not_flag_pre_existing_symlinks_as_conflict() {
    let env = TempEnvironment::builder()
        .pack("kitty")
        .file("kittyrc", "font_size 14")
        .done()
        .pack("ghostty")
        .file("ghostrc", "x")
        .done()
        .build();

    // Equivalent symlink: ~/.kittyrc already points at dodot's source.
    let source = env.dotfiles_root.join("kitty/kittyrc");
    let kitty_target = env.home.join(".kittyrc");
    env.fs.symlink(&source, &kitty_target).unwrap();

    // Non-equivalent symlink: ~/.ghostrc points somewhere else entirely.
    let ghostty_target = env.home.join(".ghostrc");
    env.fs
        .symlink(std::path::Path::new("/tmp/elsewhere"), &ghostty_target)
        .unwrap();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    let kitty = result.packs.iter().find(|p| p.name == "kitty").unwrap();
    assert_eq!(
        kitty.files[0].status, "pending",
        "equivalent symlink should be plain pending, not a conflict (executor handles it)"
    );
    assert!(
        kitty.files[0].note_ref.is_none(),
        "no note_ref for non-conflict"
    );

    let ghostty = result.packs.iter().find(|p| p.name == "ghostty").unwrap();
    assert_eq!(
        ghostty.files[0].status, "pending",
        "non-equivalent symlink should also be plain pending — executor will replace it"
    );
    assert!(
        ghostty.files[0].note_ref.is_none(),
        "no note_ref for non-conflict"
    );
    assert!(
        result.notes.is_empty(),
        "no notes for non-conflict case, got: {:?}",
        result.notes
    );
}

// ── status: chain verification ────────────────────────────

#[test]
fn status_verified_deployed_after_up() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "set nocompatible")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    let result = commands::status::status(None, &ctx).unwrap();
    let file = &result.packs[0].files[0];
    assert_eq!(file.status, "deployed", "should be verified deployed");
    assert_eq!(file.status_label, "deployed");
}

#[test]
fn status_detects_broken_source_deleted() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "set nocompatible")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    // Delete the source file — scanner won't find it so pack will have no
    // matches. But the orphaned data link persists in the datastore. This
    // verifies that deleting a source doesn't crash status and that the
    // data link survives (a subsequent `up` would clean it up).
    let source = env.dotfiles_root.join("vim/vimrc");
    env.fs.remove_file(&source).unwrap();

    let result = commands::status::status(None, &ctx).unwrap();
    assert!(
        result.packs[0].files.is_empty(),
        "deleted source should produce no scanner matches"
    );
    assert!(
        env.fs
            .is_symlink(&env.paths.handler_data_dir("vim", "symlink").join("vimrc")),
        "data link should still exist after source deletion"
    );
}

#[test]
fn status_detects_broken_user_link_removed() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "set nocompatible")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    // Remove the user link (under #48: $XDG_CONFIG_HOME/vim/vimrc).
    let user_path = env.home.join(".config/vim/vimrc");
    env.fs.remove_file(&user_path).unwrap();

    let result = commands::status::status(None, &ctx).unwrap();
    let file = &result.packs[0].files[0];
    assert_eq!(
        file.status, "stale",
        "should detect missing user link, got: {} ({})",
        file.status, file.status_label
    );
    assert!(
        file.status_label.contains("user link missing"),
        "label: {}",
        file.status_label
    );
}

#[test]
fn status_detects_conflict_at_user_path() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "set nocompatible")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    // Replace user symlink (under #48: $XDG_CONFIG_HOME/vim/vimrc) with a
    // regular file whose content does NOT match source — that's a real
    // conflict (#44 auto-replace would only kick in for matching content).
    let user_path = env.home.join(".config/vim/vimrc");
    env.fs.remove_file(&user_path).unwrap();
    env.fs.write_file(&user_path, b"manual file").unwrap();

    let result = commands::status::status(None, &ctx).unwrap();
    let file = &result.packs[0].files[0];
    assert_eq!(
        file.status, "broken",
        "should detect conflict, got: {} ({})",
        file.status, file.status_label
    );
    assert!(
        file.status_label.contains("conflict"),
        "label: {}",
        file.status_label
    );
}

#[test]
fn status_shell_handler_verified_deployed() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    let result = commands::status::status(None, &ctx).unwrap();
    let file = result.packs[0]
        .files
        .iter()
        .find(|f| f.handler == "shell")
        .expect("should have shell file");
    assert_eq!(
        file.status, "deployed",
        "shell handler should be verified deployed"
    );
    assert_eq!(file.status_label, "sourced");
}

#[test]
fn status_shell_handler_detects_broken_source() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    // Delete source but keep data link
    let source = env.dotfiles_root.join("vim/aliases.sh");
    env.fs.remove_file(&source).unwrap();

    // Scanner won't find the deleted file, so pack will have no matches.
    // Recreate the source so scanner finds it, but break the chain differently.
    // Instead, test that the data link pointing to missing source is detected.
    // We need the file in the pack for the scanner, so write a new one and
    // then break the data link.
    env.fs.write_file(&source, b"alias vi=vim").unwrap();

    // Now manually break the data link by pointing it elsewhere
    let data_link = env
        .paths
        .handler_data_dir("vim", "shell")
        .join("aliases.sh");
    env.fs.remove_file(&data_link).unwrap();
    let bogus = env.dotfiles_root.join("vim/nonexistent");
    env.fs.symlink(&bogus, &data_link).unwrap();

    let result = commands::status::status(None, &ctx).unwrap();
    let file = result.packs[0]
        .files
        .iter()
        .find(|f| f.handler == "shell")
        .expect("should have shell file");
    assert_eq!(
        file.status, "broken",
        "should detect broken data link, got: {} ({})",
        file.status, file.status_label
    );
}

#[test]
fn status_path_handler_verified_deployed() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("bin/myscript", "#!/bin/sh")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    let result = commands::status::status(None, &ctx).unwrap();
    let file = result.packs[0]
        .files
        .iter()
        .find(|f| f.handler == "path")
        .expect("should have path file");
    assert_eq!(
        file.status, "deployed",
        "path handler should be verified deployed"
    );
    assert_eq!(file.status_label, "in PATH");
}

// ── cross-pack conflict detection: up command ──────────────

#[test]
fn up_halts_on_cross_pack_symlink_conflict() {
    // Two packs both deploying a file that resolves to ~/.aliases
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("home.aliases", "alias a=1")
        .done()
        .pack("pack-b")
        .file("home.aliases", "alias b=2")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();

    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "expected CrossPackConflict, got: {err}"
    );

    // Error message should include both packs and the target
    let msg = err.to_string();
    assert!(msg.contains("pack-a"), "msg: {msg}");
    assert!(msg.contains("pack-b"), "msg: {msg}");
    assert!(msg.contains(".aliases"), "msg: {msg}");
}

#[test]
fn up_halts_no_partial_deployment_on_conflict() {
    // When a conflict is detected, NO packs should be deployed —
    // not even the non-conflicting ones.
    let env = TempEnvironment::builder()
        .pack("conflict-a")
        .file("home.aliases", "a")
        .done()
        .pack("conflict-b")
        .file("home.aliases", "b")
        .done()
        .pack("innocent")
        .file("vimrc", "set nocompatible")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let _err = commands::up::up(None, &ctx).unwrap_err();

    // Nothing should be deployed — check the innocent pack
    env.assert_no_handler_state("innocent", "symlink");
    env.assert_no_handler_state("conflict-a", "symlink");
    env.assert_no_handler_state("conflict-b", "symlink");
}

#[test]
fn up_force_does_not_override_cross_pack_conflict() {
    // --force only helps with pre-existing non-dodot files.
    // Cross-pack conflicts are a config problem and --force must NOT help.
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("home.aliases", "a")
        .done()
        .pack("pack-b")
        .file("home.aliases", "b")
        .done()
        .build();

    let mut ctx = make_ctx(&env);
    ctx.force = true;

    let err = commands::up::up(None, &ctx).unwrap_err();
    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "force should NOT override cross-pack conflict, got: {err}"
    );
    assert!(
        err.to_string().contains("--force does not override"),
        "msg: {}",
        err
    );
}

#[test]
fn up_dry_run_still_detects_cross_pack_conflict() {
    let env = TempEnvironment::builder()
        .pack("a")
        .file("bashrc", "a")
        .done()
        .pack("b")
        .file("bashrc", "b")
        .done()
        .build();

    let mut ctx = make_ctx(&env);
    ctx.dry_run = true;

    let err = commands::up::up(None, &ctx).unwrap_err();
    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "dry-run should still detect conflicts, got: {err}"
    );
}

/// Regression: `dodot up` on a cross-pack conflict must render the full
/// per-pack listing, notes, and ignored-pack section — not a bare
/// conflicts dump. Before the fix, the CLI handler hardcoded
/// `packs: Vec::new()` on the `CrossPackConflict` branch, so users only
/// saw the trailing conflicts section and lost all context about what
/// *would* have been deployed.
#[test]
fn up_with_cross_pack_conflict_renders_full_status_view() {
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("home.aliases", "alias a=1")
        .done()
        .pack("pack-b")
        .file("home.aliases", "alias b=2")
        .done()
        // An unrelated pack so we can assert the listing is preserved.
        .pack("innocent")
        .file("home.vimrc", "set nocompatible")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up_or_status_for_conflict(None, &ctx)
        .expect("status fallback should produce Ok on cross-pack conflict");

    // Top-level message explains why nothing deployed.
    assert_eq!(
        result.message.as_deref(),
        Some("Cross-pack conflicts prevent deployment."),
        "got message: {:?}",
        result.message
    );

    // Full per-pack listing is present — the regression was this being empty.
    assert!(
        !result.packs.is_empty(),
        "up-with-conflict must render pack rows, not a bare conflicts dump"
    );
    let pack_names: Vec<&str> = result.packs.iter().map(|p| p.name.as_str()).collect();
    assert!(
        pack_names.contains(&"pack-a"),
        "expected pack-a in listing, got: {:?}",
        pack_names
    );
    assert!(
        pack_names.contains(&"pack-b"),
        "expected pack-b in listing, got: {:?}",
        pack_names
    );
    assert!(
        pack_names.contains(&"innocent"),
        "expected innocent pack in listing, got: {:?}",
        pack_names
    );

    // Conflicts section is still populated — same data the old branch showed.
    assert!(
        !result.conflicts.is_empty(),
        "expected conflicts section to be populated"
    );
    let conflict = &result.conflicts[0];
    assert!(
        conflict.target.contains(".aliases"),
        "conflict target should reference .aliases, got: {}",
        conflict.target
    );

    // Nothing was actually deployed — rows should report pending, not deployed.
    for pack in &result.packs {
        for file in &pack.files {
            assert_ne!(
                file.status, "deployed",
                "{}::{} should not be deployed when conflict blocks up, got: {} ({})",
                pack.name, file.name, file.status, file.status_label
            );
        }
    }
}

#[test]
fn up_no_conflict_when_different_target_files() {
    // Different filenames → different targets → no conflict.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "set nocompatible")
        .done()
        .pack("git")
        .file("gitconfig", "[user]\n  name = test")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();
    assert_eq!(result.message.as_deref(), Some("Packs deployed."));
}

#[test]
fn up_no_conflict_within_same_pack() {
    // Same pack with multiple files targeting different paths — fine.
    let env = TempEnvironment::builder()
        .pack("shell")
        .file("bashrc", "# bash")
        .file("zshrc", "# zsh")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();
    assert_eq!(result.message.as_deref(), Some("Packs deployed."));
}

#[test]
fn up_conflict_via_config_mapping() {
    // Two packs with different source filenames but mapping to the same target
    // via [symlink.targets].
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("settings", "a")
        .config("[symlink]\ntargets = { settings = \"myapp/settings.toml\" }")
        .done()
        .pack("pack-b")
        .file("config", "b")
        .config("[symlink]\ntargets = { config = \"myapp/settings.toml\" }")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();

    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "expected CrossPackConflict for config mapping collision, got: {err}"
    );

    let msg = err.to_string();
    assert!(
        msg.contains("myapp/settings.toml"),
        "should mention the conflicting target: {msg}"
    );
}

#[test]
fn up_conflict_via_home_prefix() {
    // pack-a uses _home/vim/vimrc → ~/.vim/vimrc
    // pack-b uses vim/vimrc (subdirectory) → ~/.config/vim/vimrc
    // These target DIFFERENT paths, so no conflict.
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("_home/vim/vimrc", "a")
        .done()
        .pack("pack-b")
        .file("vim/vimrc", "b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();
    assert_eq!(
        result.message.as_deref(),
        Some("Packs deployed."),
        "different targets should not conflict"
    );
}

#[test]
fn up_conflict_two_packs_same_home_prefix_target() {
    // Both packs use the `home.X` per-file home opt-in → both resolve
    // to ~/.bashrc, conflict.
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("home.bashrc", "# a")
        .done()
        .pack("pack-b")
        .file("home.bashrc", "# b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();
    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "both targeting ~/.bashrc should conflict, got: {err}"
    );
}

#[test]
fn up_filtered_packs_only_checks_filtered_subset() {
    // pack-a and pack-b conflict, but if we only deploy pack-a,
    // there's no conflict.
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("home.aliases", "a")
        .done()
        .pack("pack-b")
        .file("home.aliases", "b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let filter = vec!["pack-a".into()];
    let result = commands::up::up(Some(&filter), &ctx).unwrap();

    assert_eq!(result.message.as_deref(), Some("Packs deployed."));
    assert_eq!(result.packs.len(), 1);
    assert_eq!(result.packs[0].name, "pack-a");
}

#[test]
fn up_same_name_shell_scripts_are_not_conflicts() {
    // Two packs both having aliases.sh is a legitimate and common
    // pattern — they're staged in per-pack namespaced directories.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .done()
        .pack("git")
        .file("aliases.sh", "alias g=git")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();
    assert_eq!(result.message.as_deref(), Some("Packs deployed."));
}

#[test]
fn up_path_dirs_with_different_executables_ok() {
    // Two packs both having bin/ with different file names — no conflict.
    let env = TempEnvironment::builder()
        .pack("tools-a")
        .file("bin/tool-a", "#!/bin/sh")
        .done()
        .pack("tools-b")
        .file("bin/tool-b", "#!/bin/sh")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();
    assert_eq!(result.message.as_deref(), Some("Packs deployed."));
}

#[test]
fn up_path_dirs_with_same_executable_name_conflicts() {
    // Two packs both have bin/tool — one would shadow the other in PATH.
    let env = TempEnvironment::builder()
        .pack("tools-a")
        .file("bin/tool", "#!/bin/sh\necho a")
        .done()
        .pack("tools-b")
        .file("bin/tool", "#!/bin/sh\necho b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();
    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "same-name executables across packs should conflict: {err}"
    );
    let msg = err.to_string();
    assert!(msg.contains("tool"), "should mention the executable: {msg}");
    assert!(msg.contains("tools-a"), "should mention pack a: {msg}");
    assert!(msg.contains("tools-b"), "should mention pack b: {msg}");
}

#[test]
fn up_no_cross_handler_conflict() {
    // A shell script and a symlink file with the same name don't conflict
    // because they're in different handler namespaces.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .done()
        .pack("git")
        .file("gitconfig", "[user]\n  name = test")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();
    assert_eq!(result.message.as_deref(), Some("Packs deployed."));
}

#[test]
fn up_three_packs_partial_conflict() {
    // Three packs, only two conflict — all three are blocked.
    let env = TempEnvironment::builder()
        .pack("a")
        .file("home.aliases", "a")
        .done()
        .pack("b")
        .file("home.aliases", "b")
        .done()
        .pack("c")
        .file("gitconfig", "c")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();

    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "should detect the conflict even if not all packs are involved"
    );

    // Verify nothing was deployed
    env.assert_no_handler_state("a", "symlink");
    env.assert_no_handler_state("b", "symlink");
    env.assert_no_handler_state("c", "symlink");
}

#[test]
fn up_error_message_includes_all_conflict_details() {
    let env = TempEnvironment::builder()
        .pack("alpha")
        .file("home.aliases", "a")
        .done()
        .pack("beta")
        .file("home.aliases", "b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();

    let msg = err.to_string();
    // Should mention both packs
    assert!(msg.contains("alpha"), "msg: {msg}");
    assert!(msg.contains("beta"), "msg: {msg}");
    // Should mention the handler
    assert!(msg.contains("symlink"), "msg: {msg}");
    // Should mention the target path
    assert!(msg.contains(".aliases"), "msg: {msg}");
}

// ── cross-pack conflict detection: status command ──────────

#[test]
fn status_warns_on_potential_cross_pack_conflict() {
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("home.aliases", "a")
        .done()
        .pack("pack-b")
        .file("home.aliases", "b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    // Status should still succeed (it's informational) and surface the
    // conflict as structured data on the result.
    assert_eq!(result.conflicts.len(), 1, "should detect one conflict");
    let c = &result.conflicts[0];
    assert_eq!(c.kind, "symlink");
    let packs: Vec<&str> = c.claimants.iter().map(|cl| cl.pack.as_str()).collect();
    assert!(packs.contains(&"pack-a"), "claimants: {:?}", c.claimants);
    assert!(packs.contains(&"pack-b"), "claimants: {:?}", c.claimants);
}

#[test]
fn status_no_warnings_without_conflicts() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "set nocompatible")
        .done()
        .pack("git")
        .file("gitconfig", "[user]\n  name = test")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    assert!(
        result.warnings.is_empty(),
        "no warnings expected, got: {:?}",
        result.warnings
    );
    assert!(
        result.conflicts.is_empty(),
        "no conflicts expected, got: {:?}",
        result.conflicts
    );
}

#[test]
fn status_shows_conflict_even_when_not_deployed() {
    // Neither pack is deployed yet — status should still show the
    // potential conflict.
    let env = TempEnvironment::builder()
        .pack("a")
        .file("bashrc", "a")
        .done()
        .pack("b")
        .file("bashrc", "b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    // Both packs should show as pending
    for pack in &result.packs {
        for file in &pack.files {
            assert_eq!(file.status, "pending");
        }
    }

    // Conflict data should still be emitted.
    assert!(
        !result.conflicts.is_empty(),
        "should flag potential conflict even when undeployed"
    );
}

#[test]
fn status_filtered_to_one_pack_no_conflict_warning() {
    // If we only ask about one pack, no cross-pack comparison happens.
    let env = TempEnvironment::builder()
        .pack("a")
        .file("home.aliases", "a")
        .done()
        .pack("b")
        .file("home.aliases", "b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let filter = vec!["a".into()];
    let result = commands::status::status(Some(&filter), &ctx).unwrap();

    assert!(
        result.conflicts.is_empty(),
        "single-pack filter should not produce cross-pack conflicts"
    );
}

#[test]
fn status_conflict_with_config_mapping() {
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("settings", "a")
        .config("[symlink]\ntargets = { settings = \"myapp/settings.toml\" }")
        .done()
        .pack("pack-b")
        .file("config", "b")
        .config("[symlink]\ntargets = { config = \"myapp/settings.toml\" }")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    assert_eq!(
        result.conflicts.len(),
        1,
        "config mapping collision should surface one conflict"
    );
    assert!(
        result.conflicts[0].target.contains("settings.toml"),
        "should mention the conflicting target: {:?}",
        result.conflicts[0]
    );
}

// ── edge cases ─────────────────────────────────────────────

#[test]
fn up_succeeds_after_resolving_conflict() {
    // Set up conflicting packs
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("home.aliases", "a")
        .done()
        .pack("pack-b")
        .file("home.aliases", "b")
        .done()
        .build();

    let ctx = make_ctx(&env);

    // First attempt fails
    let err = commands::up::up(None, &ctx).unwrap_err();
    assert!(matches!(err, crate::DodotError::CrossPackConflict { .. }));

    // "Resolve" conflict by deploying only one pack
    let filter = vec!["pack-a".into()];
    let result = commands::up::up(Some(&filter), &ctx).unwrap();
    assert_eq!(result.message.as_deref(), Some("Packs deployed."));

    // pack-a should be deployed
    let status = commands::status::status(Some(&filter), &ctx).unwrap();
    assert!(status.packs[0].files.iter().any(|f| f.status == "deployed"));
}

#[test]
fn up_conflict_with_home_prefix_convention() {
    // pack-a has `home.bashrc` (uses home. convention → ~/.bashrc)
    // pack-b has `bashrc` (in force_home → ~/.bashrc)
    // Same resolved target → conflict.
    let env = TempEnvironment::builder()
        .pack("a")
        .file("home.bashrc", "# pack a")
        .done()
        .pack("b")
        .file("bashrc", "# pack b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();
    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "home.bashrc and bashrc both resolve to ~/.bashrc: {err}"
    );
}

#[test]
fn up_multiple_simultaneous_conflicts() {
    // Two conflict groups at the same time
    let env = TempEnvironment::builder()
        .pack("a")
        .file("home.aliases", "a-aliases")
        .file("bashrc", "a-bash")
        .done()
        .pack("b")
        .file("home.aliases", "b-aliases")
        .file("bashrc", "b-bash")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();

    if let crate::DodotError::CrossPackConflict { conflicts } = &err {
        assert!(
            conflicts.len() >= 2,
            "should detect at least 2 conflict groups, got {}",
            conflicts.len()
        );
    } else {
        panic!("expected CrossPackConflict, got: {err}");
    }
}

#[test]
fn up_ignored_pack_does_not_cause_conflict() {
    // pack-b is ignored, so it shouldn't participate in conflict detection.
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("home.aliases", "a")
        .done()
        .pack("pack-b")
        .file("home.aliases", "b")
        .ignored()
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();
    assert_eq!(result.message.as_deref(), Some("Packs deployed."));
}

#[test]
fn status_no_warning_for_same_name_shell_scripts() {
    // Same-name shell scripts in different packs are legitimate
    // and should not produce conflict warnings.
    let env = TempEnvironment::builder()
        .pack("a")
        .file("aliases.sh", "alias a=1")
        .done()
        .pack("b")
        .file("aliases.sh", "alias b=2")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    assert!(
        result.warnings.is_empty(),
        "same-name shell scripts should not produce warnings, got: {:?}",
        result.warnings
    );
}

#[test]
fn up_conflict_xdg_path_both_packs_subdir() {
    // Both packs use `_xdg/nvim/init.lua` (the per-subtree XDG escape
    // hatch — skips the pack name in the path) → both resolve to
    // ~/.config/nvim/init.lua, conflict.
    //
    // (Without `_xdg/`, the new default would namespace each pack
    // under its own dir — `~/.config/nvim-base/...` vs `~/.config/
    // nvim-custom/...` — and they wouldn't collide.)
    let env = TempEnvironment::builder()
        .pack("nvim-base")
        .file("_xdg/nvim/init.lua", "-- base config")
        .done()
        .pack("nvim-custom")
        .file("_xdg/nvim/init.lua", "-- custom config")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();
    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "both targeting ~/.config/nvim/init.lua should conflict: {err}"
    );
}

// ── auto-chmod +x for path handler ─────────────────────────

#[test]
fn up_auto_chmod_makes_bin_files_executable() {
    let env = TempEnvironment::builder()
        .pack("tools")
        .file("bin/deploy", "#!/bin/sh\necho deploying")
        .done()
        .build();

    let ctx = make_ctx(&env);

    // Verify the file starts non-executable
    let tool_path = env.dotfiles_root.join("tools/bin/deploy");
    let meta_before = env.fs.stat(&tool_path).unwrap();
    assert_eq!(meta_before.mode & 0o111, 0, "should start non-executable");

    commands::up::up(None, &ctx).unwrap();

    // After up, file should be executable
    let meta_after = env.fs.stat(&tool_path).unwrap();
    assert_ne!(
        meta_after.mode & 0o111,
        0,
        "bin/ file should be executable after up"
    );
}

#[test]
fn up_auto_chmod_disabled_via_config() {
    let env = TempEnvironment::builder()
        .pack("tools")
        .file("bin/deploy", "#!/bin/sh\necho deploying")
        .done()
        .build();

    // Write root config disabling auto_chmod_exec
    env.fs
        .write_file(
            &env.dotfiles_root.join(".dodot.toml"),
            b"[path]\nauto_chmod_exec = false",
        )
        .unwrap();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    // File should remain non-executable
    let tool_path = env.dotfiles_root.join("tools/bin/deploy");
    let meta = env.fs.stat(&tool_path).unwrap();
    assert_eq!(
        meta.mode & 0o111,
        0,
        "auto_chmod_exec=false should leave file non-executable"
    );
}

// ── status: preprocessed file display ──────────────────────────

#[test]
fn status_reports_template_under_stripped_name() {
    // Regression guard: before the fix, status used the raw scanner
    // output (pre-preprocessing) for its file list, so a `greet.tmpl`
    // template would be listed as `greet.tmpl` and wrongly reported as
    // "pending" even after `dodot up` deployed the rendered `greet`.
    let env = TempEnvironment::builder()
        .pack("app")
        .file("greet.tmpl", "hello {{ name }}")
        .config("[preprocessor.template.vars]\nname = \"Alice\"\n")
        .done()
        .build();

    let ctx = make_ctx(&env);

    // Run up first so the deployment state is "deployed".
    commands::up::up(None, &ctx).unwrap();

    let result = commands::status::status(None, &ctx).unwrap();

    assert_eq!(result.packs.len(), 1);
    let files = &result.packs[0].files;
    assert_eq!(files.len(), 1, "files: {files:?}");

    // The display name must be the stripped name, not the .tmpl source.
    assert_eq!(files[0].name, "greet", "file name: {}", files[0].name);
    assert_eq!(
        files[0].status, "deployed",
        "template should report as deployed after up, not pending"
    );
}

#[test]
fn status_reports_template_pending_before_up() {
    // Even without running up, status should use the stripped name.
    let env = TempEnvironment::builder()
        .pack("app")
        .file("greet.tmpl", "hello {{ name }}")
        .config("[preprocessor.template.vars]\nname = \"Alice\"\n")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    let files = &result.packs[0].files;
    assert_eq!(files.len(), 1);
    assert_eq!(files[0].name, "greet");
    assert_eq!(files[0].status, "pending");
}

// ── view-mode / group-mode tests ────────────────────────────

#[test]
fn summary_aggregates_all_deployed_as_deployed() {
    use crate::commands::{DisplayFile, DisplayPack};

    let files = vec![
        DisplayFile {
            name: "a".into(),
            symbol: "".into(),
            description: "".into(),
            status: "deployed".into(),
            status_label: "deployed".into(),
            handler: "symlink".into(),
            note_ref: None,
        },
        DisplayFile {
            name: "b".into(),
            symbol: "".into(),
            description: "".into(),
            status: "deployed".into(),
            status_label: "deployed".into(),
            handler: "symlink".into(),
            note_ref: None,
        },
    ];
    let pack = DisplayPack::new("vim".into(), files);
    assert_eq!(pack.summary_status, "deployed");
    assert_eq!(pack.summary_count, 2);
}

#[test]
fn summary_rolls_up_error_over_pending_over_deployed() {
    use crate::commands::{DisplayFile, DisplayPack};

    let mk = |status: &str| DisplayFile {
        name: status.into(),
        symbol: "".into(),
        description: "".into(),
        status: status.into(),
        status_label: status.into(),
        handler: "symlink".into(),
        note_ref: None,
    };

    // error beats pending beats deployed
    let pack = DisplayPack::new(
        "mixed".into(),
        vec![mk("error"), mk("pending"), mk("deployed")],
    );
    assert_eq!(pack.summary_status, "error");
    assert_eq!(pack.summary_count, 1);

    // broken rolls into error bucket
    let pack = DisplayPack::new("b".into(), vec![mk("broken"), mk("deployed")]);
    assert_eq!(pack.summary_status, "error");

    // stale and warning roll into pending bucket
    let pack = DisplayPack::new("s".into(), vec![mk("stale"), mk("deployed")]);
    assert_eq!(pack.summary_status, "pending");
    let pack = DisplayPack::new("w".into(), vec![mk("warning"), mk("deployed")]);
    assert_eq!(pack.summary_status, "pending");

    // count counts only files in the winning bucket
    let pack = DisplayPack::new(
        "counts".into(),
        vec![
            mk("error"),
            mk("broken"),
            mk("pending"),
            mk("pending"),
            mk("deployed"),
        ],
    );
    assert_eq!(pack.summary_status, "error");
    assert_eq!(pack.summary_count, 2);
}

#[test]
fn short_mode_renders_one_line_per_pack_with_count() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "x")
        .done()
        .pack("nvim")
        .file("init.lua", "x")
        .done()
        .build();

    let mut ctx = make_ctx(&env);
    ctx.view_mode = crate::commands::ViewMode::Short;
    let result = commands::status::status(None, &ctx).unwrap();

    let output = render::render("pack-status", &result, OutputMode::Text).unwrap();

    // Short mode: one line per pack, count + status word, no per-file rows
    assert!(output.contains("vim"), "output: {output}");
    assert!(output.contains("nvim"), "output: {output}");
    assert!(output.contains("(1) pending"), "output: {output}");
    assert!(
        !output.contains("vimrc"),
        "short mode should not render individual files: {output}"
    );
    assert!(
        !output.contains("init.lua"),
        "short mode should not render individual files: {output}"
    );
}

#[test]
fn by_status_groups_packs_under_banners() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "x")
        .done()
        .pack("nvim")
        .file("init.lua", "x")
        .done()
        .build();

    let mut ctx = make_ctx(&env);
    ctx.group_mode = crate::commands::GroupMode::Status;
    let result = commands::status::status(None, &ctx).unwrap();

    let output = render::render("pack-status", &result, OutputMode::Text).unwrap();

    // All packs pending, so only the Pending banner appears
    assert!(output.contains("Pending Packs"), "output: {output}");
    assert!(
        !output.contains("Deployed Packs"),
        "no deployed packs — deployed banner should be hidden: {output}"
    );
    assert!(
        !output.contains("Error Packs"),
        "no error packs — error banner should be hidden: {output}"
    );
    // Pack names still render within the group
    assert!(output.contains("vim"), "output: {output}");
    assert!(output.contains("nvim"), "output: {output}");
}

// ── probe ──────────────────────────────────────────────────────

#[test]
fn probe_summary_lists_available_subcommands() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    let result = commands::probe::summary(&ctx).unwrap();
    let output = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(output.contains("deployment-map"), "output:\n{output}");
    assert!(output.contains("show-data-dir"), "output:\n{output}");
}

#[test]
fn probe_deployment_map_renders_rows_after_up() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .done()
        .build();
    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    let result = commands::probe::deployment_map(&ctx).unwrap();
    let output = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(output.contains("vim"), "output:\n{output}");
    assert!(output.contains("shell"), "output:\n{output}");
    assert!(output.contains("aliases.sh"), "output:\n{output}");
}

#[test]
fn probe_deployment_map_empty_state_shows_hint() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    let result = commands::probe::deployment_map(&ctx).unwrap();
    let output = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(
        output.contains("nothing deployed"),
        "empty probe should point the user at `dodot up`; got:\n{output}"
    );
}

#[test]
fn probe_show_data_dir_renders_tree_with_sizes() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .done()
        .build();
    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    let result = commands::probe::show_data_dir(&ctx, 4).unwrap();
    let output = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(output.contains("packs"), "output:\n{output}");
    assert!(output.contains("vim"), "output:\n{output}");
    assert!(output.contains("shell"), "output:\n{output}");
    // Tree should use box-drawing glyphs somewhere.
    assert!(
        output.contains("") || output.contains(""),
        "expected branch glyphs in tree; got:\n{output}"
    );
}

#[test]
fn probe_deployment_map_json_mode_is_kind_tagged() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    let result = commands::probe::deployment_map(&ctx).unwrap();
    let output = render::render("probe", &result, OutputMode::Json).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&output).unwrap();
    assert_eq!(parsed["kind"], "deployment-map");
    assert!(parsed["entries"].is_array());
}

// ── probe shell-init Phase 3 (--runs / --history) ─────────────────

fn write_fake_profile(env: &TempEnvironment, name: &str, lines: &[&str]) {
    let dir = env.paths.probes_shell_init_dir();
    env.fs.mkdir_all(&dir).unwrap();
    let mut content =
        String::from("# columns\tphase\tpack\thandler\ttarget\tstart_t\tend_t\texit_status\n");
    for l in lines {
        content.push_str(l);
        content.push('\n');
    }
    env.fs
        .write_file(&dir.join(name), content.as_bytes())
        .unwrap();
}

#[test]
fn probe_shell_init_aggregate_renders_percentile_table() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    // Three fake profiles with the same target; verify p50/p95/max
    // surface in the rendered text.
    write_fake_profile(
        &env,
        "profile-1714000001-1-1.tsv",
        &["source\tvim\tshell\t/x/aliases.sh\t1.000000\t1.000100\t0"],
    );
    write_fake_profile(
        &env,
        "profile-1714000002-1-1.tsv",
        &["source\tvim\tshell\t/x/aliases.sh\t1.000000\t1.000200\t0"],
    );
    write_fake_profile(
        &env,
        "profile-1714000003-1-1.tsv",
        &["source\tvim\tshell\t/x/aliases.sh\t1.000000\t1.000300\t0"],
    );
    let result = commands::probe::shell_init_aggregate(&ctx, 5).unwrap();
    let output = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(
        output.contains("aggregate"),
        "header missing; got:\n{output}"
    );
    assert!(output.contains("aliases.sh"), "row missing; got:\n{output}");
    assert!(output.contains("3/3"), "seen-label missing; got:\n{output}");
}

#[test]
fn probe_shell_init_aggregate_warns_when_fewer_runs_than_requested() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    write_fake_profile(
        &env,
        "profile-1714000001-1-1.tsv",
        &["source\tvim\tshell\t/x.sh\t1.000000\t1.000100\t0"],
    );
    // Asked for 10, only 1 on disk.
    let result = commands::probe::shell_init_aggregate(&ctx, 10).unwrap();
    let output = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(
        output.contains("requested 10"),
        "expected mismatch warning; got:\n{output}"
    );
}

#[test]
fn probe_shell_init_aggregate_empty_state_shows_hint() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    let result = commands::probe::shell_init_aggregate(&ctx, 5).unwrap();
    let output = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(
        output.contains("no profiles yet"),
        "expected empty hint; got:\n{output}"
    );
}

#[test]
fn probe_shell_init_history_renders_one_row_per_run_newest_first() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    // Three profiles with distinct timestamps in their filenames.
    write_fake_profile(
        &env,
        "profile-1714000000-1-1.tsv",
        &["source\tvim\tshell\t/a.sh\t1.000000\t1.000100\t0"],
    );
    write_fake_profile(
        &env,
        "profile-1714003600-1-1.tsv",
        &["source\tvim\tshell\t/a.sh\t1.000000\t1.000200\t1"],
    );
    write_fake_profile(
        &env,
        "profile-1714007200-1-1.tsv",
        &["source\tvim\tshell\t/a.sh\t1.000000\t1.000300\t0"],
    );
    let result = commands::probe::shell_init_history(&ctx, 50).unwrap();
    let output = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(output.contains("history"), "header missing; got:\n{output}");
    // Date stamps from the timestamps (1714000000 ≈ 2024-04-24 23:06 UTC).
    assert!(
        output.contains("2024-04-24"),
        "date missing; got:\n{output}"
    );
    // Three rendered rows; ordering check via JSON because the text
    // template's column padding makes substring offsets fragile.
    let json = render::render("probe", &result, OutputMode::Json).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
    let rows = parsed["rows"].as_array().unwrap();
    assert_eq!(rows.len(), 3);
    // Newest unix_ts first, oldest last (descending).
    let timestamps: Vec<u64> = rows
        .iter()
        .map(|r| r["unix_ts"].as_u64().unwrap_or(0))
        .collect();
    assert_eq!(timestamps, vec![1714007200, 1714003600, 1714000000]);
    // Middle row had a non-zero exit_status.
    assert_eq!(rows[1]["failed_entries"].as_u64().unwrap(), 1);
    assert_eq!(rows[0]["failed_entries"].as_u64().unwrap(), 0);
    assert_eq!(rows[2]["failed_entries"].as_u64().unwrap(), 0);
}

#[test]
fn probe_shell_init_history_empty_state_shows_hint() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    let result = commands::probe::shell_init_history(&ctx, 50).unwrap();
    let output = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(
        output.contains("no profiles yet"),
        "expected empty hint; got:\n{output}"
    );
}

#[test]
fn probe_shell_init_aggregate_json_is_kind_tagged() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    let result = commands::probe::shell_init_aggregate(&ctx, 1).unwrap();
    let output = render::render("probe", &result, OutputMode::Json).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&output).unwrap();
    assert_eq!(parsed["kind"], "shell-init-aggregate");
    assert!(parsed["rows"].is_array());
    assert!(parsed["requested_runs"].is_number());
}

#[test]
fn probe_shell_init_history_json_is_kind_tagged() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    let result = commands::probe::shell_init_history(&ctx, 1).unwrap();
    let output = render::render("probe", &result, OutputMode::Json).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&output).unwrap();
    assert_eq!(parsed["kind"], "shell-init-history");
    assert!(parsed["rows"].is_array());
}

#[test]
fn probe_shell_init_filter_json_is_kind_tagged() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    let result = commands::probe::shell_init_filter(&ctx, "vim", 5).unwrap();
    let output = render::render("probe", &result, OutputMode::Json).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&output).unwrap();
    assert_eq!(parsed["kind"], "shell-init-filter");
    assert!(parsed["targets"].is_array());
    assert_eq!(parsed["filter_pack"], "vim");
}

#[test]
fn probe_shell_init_errors_json_is_kind_tagged() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    let result = commands::probe::shell_init_errors(&ctx, 5).unwrap();
    let output = render::render("probe", &result, OutputMode::Json).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&output).unwrap();
    assert_eq!(parsed["kind"], "shell-init-errors");
    assert!(parsed["targets"].is_array());
}

// ── probe shell-init: staleness banner (#59) ────────────────

/// Plant a `last-up-at` marker at the given unix timestamp so tests
/// don't depend on real wall-clock writes.
fn write_last_up_marker_at(env: &TempEnvironment, ts: u64) {
    env.fs.mkdir_all(env.paths.data_dir()).unwrap();
    env.fs
        .write_file(&env.paths.last_up_path(), ts.to_string().as_bytes())
        .unwrap();
}

/// Profile filenames encode the unix timestamp. Profile pre-dates the
/// last `up`, so the staleness banner must fire.
#[test]
fn probe_shell_init_banner_when_profile_predates_last_up() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);

    write_fake_profile(
        &env,
        "profile-1714000000-1-1.tsv",
        &["source\tvim\tshell\t/x/aliases.sh\t1.000000\t1.000100\t0"],
    );
    // Up happened one hour after the profile.
    write_last_up_marker_at(&env, 1714003600);

    let result = commands::probe::shell_init(&ctx).unwrap();
    let json = render::render("probe", &result, OutputMode::Json).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed["stale"], true);

    let text = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(
        text.contains("warning:"),
        "expected staleness banner, got:\n{text}"
    );
    // Banner mentions both timestamps so the user can verify the comparison.
    assert!(
        text.contains("2024-04-24") && text.contains("2024-04-25"),
        "banner should reference both capture and up timestamps, got:\n{text}"
    );
    assert!(
        text.contains("capture a fresh profile"),
        "banner should explain the remediation, got:\n{text}"
    );
}

#[test]
fn probe_shell_init_no_banner_when_profile_postdates_last_up() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);

    // Up first, profile after — the user already opened a shell, so
    // the displayed profile reflects the post-up state. No banner.
    write_last_up_marker_at(&env, 1714000000);
    write_fake_profile(
        &env,
        "profile-1714003600-1-1.tsv",
        &["source\tvim\tshell\t/x/aliases.sh\t1.000000\t1.000100\t0"],
    );

    let result = commands::probe::shell_init(&ctx).unwrap();
    let json = render::render("probe", &result, OutputMode::Json).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed["stale"], false);

    let text = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(
        !text.contains("warning:"),
        "no banner expected when profile is fresh, got:\n{text}"
    );
}

#[test]
fn probe_shell_init_no_banner_when_no_last_up_marker() {
    // Profile exists but `up` has never run on this machine — we have
    // nothing to compare against, so the safe default is "no banner".
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);

    write_fake_profile(
        &env,
        "profile-1714000000-1-1.tsv",
        &["source\tvim\tshell\t/x/aliases.sh\t1.000000\t1.000100\t0"],
    );

    let result = commands::probe::shell_init(&ctx).unwrap();
    let text = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(
        !text.contains("warning:"),
        "no banner without an up marker, got:\n{text}"
    );
}

#[test]
fn probe_shell_init_no_banner_when_no_profile() {
    // Marker exists, but there's no profile yet (e.g. user just ran
    // first `up`). The empty-state hint is enough; no warning.
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    write_last_up_marker_at(&env, 1714000000);

    let result = commands::probe::shell_init(&ctx).unwrap();
    let text = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(
        !text.contains("warning:"),
        "no banner when there's no profile to flag, got:\n{text}"
    );
}

#[test]
fn probe_shell_init_aggregate_banner_when_newest_predates_last_up() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);

    write_fake_profile(
        &env,
        "profile-1714000001-1-1.tsv",
        &["source\tvim\tshell\t/x.sh\t1.000000\t1.000100\t0"],
    );
    write_fake_profile(
        &env,
        "profile-1714000002-1-1.tsv",
        &["source\tvim\tshell\t/x.sh\t1.000000\t1.000200\t0"],
    );
    // Up happened after the newest profile.
    write_last_up_marker_at(&env, 1714000003);

    let result = commands::probe::shell_init_aggregate(&ctx, 5).unwrap();
    let json = render::render("probe", &result, OutputMode::Json).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed["stale"], true);

    let text = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(
        text.contains("warning:"),
        "aggregate view should show banner, got:\n{text}"
    );
}

#[test]
fn probe_shell_init_history_banner_when_newest_predates_last_up() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);

    write_fake_profile(
        &env,
        "profile-1714000000-1-1.tsv",
        &["source\tvim\tshell\t/x.sh\t1.000000\t1.000100\t0"],
    );
    write_fake_profile(
        &env,
        "profile-1714003600-1-1.tsv",
        &["source\tvim\tshell\t/x.sh\t1.000000\t1.000200\t0"],
    );
    // Up after the newest history row.
    write_last_up_marker_at(&env, 1714007200);

    let result = commands::probe::shell_init_history(&ctx, 50).unwrap();
    let json = render::render("probe", &result, OutputMode::Json).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed["stale"], true);

    let text = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(
        text.contains("warning:"),
        "history view should show banner, got:\n{text}"
    );
}

// ── shell-init filter (positional pack[/file] drill-down) ──

fn write_fake_errors_log(env: &TempEnvironment, profile_name: &str, body: &str) {
    let dir = env.paths.probes_shell_init_dir();
    env.fs.mkdir_all(&dir).unwrap();
    let stem = profile_name.trim_end_matches(".tsv");
    let path = dir.join(format!("{stem}.errors.log"));
    let mut content = String::from("# dodot shell-init errors v1\n");
    content.push_str(body);
    env.fs.write_file(&path, content.as_bytes()).unwrap();
}

#[test]
fn probe_shell_init_filter_pack_only_lists_each_target_in_pack() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    write_fake_profile(
        &env,
        "profile-1714000001-1-1.tsv",
        &[
            "source\tgpg\tshell\t/p/gpg/env.sh\t1.0\t1.001\t1",
            "source\tgpg\tshell\t/p/gpg/aliases.sh\t1.0\t1.001\t0",
            "source\tvim\tshell\t/p/vim/aliases.sh\t1.0\t1.001\t0",
        ],
    );
    let result =
        commands::probe::shell_init_filter(&ctx, "gpg", commands::probe::DEFAULT_FILTER_RUNS)
            .unwrap();
    let view = match result {
        commands::probe::ProbeResult::ShellInitFilter(v) => v,
        other => panic!("expected ShellInitFilter, got {other:?}"),
    };
    assert_eq!(view.filter_pack, "gpg");
    assert!(view.filter_filename.is_none());
    assert_eq!(view.targets.len(), 2, "expected both gpg targets");
    let names: Vec<&str> = view
        .targets
        .iter()
        .map(|t| t.display_target.as_str())
        .collect();
    assert!(names.contains(&"env.sh"));
    assert!(names.contains(&"aliases.sh"));
}

#[test]
fn probe_shell_init_filter_with_filename_narrows_to_single_target() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    write_fake_profile(
        &env,
        "profile-1714000001-1-1.tsv",
        &[
            "source\tgpg\tshell\t/p/gpg/env.sh\t1.0\t1.001\t1",
            "source\tgpg\tshell\t/p/gpg/aliases.sh\t1.0\t1.001\t0",
        ],
    );
    let result = commands::probe::shell_init_filter(
        &ctx,
        "gpg/env.sh",
        commands::probe::DEFAULT_FILTER_RUNS,
    )
    .unwrap();
    let view = match result {
        commands::probe::ProbeResult::ShellInitFilter(v) => v,
        other => panic!("expected ShellInitFilter, got {other:?}"),
    };
    assert_eq!(view.filter_pack, "gpg");
    assert_eq!(view.filter_filename.as_deref(), Some("env.sh"));
    assert_eq!(view.targets.len(), 1);
    assert_eq!(view.targets[0].display_target, "env.sh");
    assert_eq!(view.targets[0].failure_count, 1);
}

#[test]
fn probe_shell_init_filter_attaches_captured_stderr_to_matching_run() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    write_fake_profile(
        &env,
        "profile-1714000001-1-1.tsv",
        &["source\tgpg\tshell\t/p/gpg/env.sh\t1.0\t1.001\t1"],
    );
    write_fake_errors_log(
        &env,
        "profile-1714000001-1-1.tsv",
        "@@\t/p/gpg/env.sh\t1\nfirst error line\nsecond error line\n",
    );
    let result = commands::probe::shell_init_filter(
        &ctx,
        "gpg/env.sh",
        commands::probe::DEFAULT_FILTER_RUNS,
    )
    .unwrap();
    let view = match result {
        commands::probe::ProbeResult::ShellInitFilter(v) => v,
        other => panic!("expected ShellInitFilter, got {other:?}"),
    };
    assert_eq!(view.targets.len(), 1);
    assert_eq!(view.targets[0].runs.len(), 1);
    assert_eq!(
        view.targets[0].runs[0].stderr_lines,
        vec!["first error line", "second error line"]
    );
}

#[test]
fn probe_shell_init_filter_runs_are_newest_first() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    // Three runs with monotonically increasing timestamps in the
    // filename — the filter view should display them newest first
    // (most recent run at the top of the per-target block).
    for ts in [1714000001u64, 1714000002, 1714000003] {
        write_fake_profile(
            &env,
            &format!("profile-{ts}-1-1.tsv"),
            &["source\tgpg\tshell\t/p/gpg/env.sh\t1.0\t1.001\t0"],
        );
    }
    let result = commands::probe::shell_init_filter(
        &ctx,
        "gpg/env.sh",
        commands::probe::DEFAULT_FILTER_RUNS,
    )
    .unwrap();
    let view = match result {
        commands::probe::ProbeResult::ShellInitFilter(v) => v,
        other => panic!("expected ShellInitFilter, got {other:?}"),
    };
    let runs = &view.targets[0].runs;
    assert_eq!(runs.len(), 3);
    assert_eq!(runs[0].profile_filename, "profile-1714000003-1-1.tsv");
    assert_eq!(runs[2].profile_filename, "profile-1714000001-1-1.tsv");
}

#[test]
fn probe_shell_init_filter_renders_with_template() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    write_fake_profile(
        &env,
        "profile-1714000001-1-1.tsv",
        &["source\tgpg\tshell\t/p/gpg/env.sh\t1.0\t1.001\t1"],
    );
    write_fake_errors_log(
        &env,
        "profile-1714000001-1-1.tsv",
        "@@\t/p/gpg/env.sh\t1\nboom\n",
    );
    let result = commands::probe::shell_init_filter(
        &ctx,
        "gpg/env.sh",
        commands::probe::DEFAULT_FILTER_RUNS,
    )
    .unwrap();
    let output = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(
        output.contains("Shell-init filter"),
        "header missing:\n{output}"
    );
    assert!(output.contains("env.sh"), "target missing:\n{output}");
    assert!(output.contains("exit 1"), "exit code missing:\n{output}");
    assert!(
        output.contains("boom"),
        "captured stderr missing:\n{output}"
    );
}

#[test]
fn probe_shell_init_filter_supports_nested_subpaths() {
    // A target deployed under a subdirectory (e.g. `pack/sub/dir/x.sh`)
    // should be matchable both by basename (`x.sh`) and by subpath
    // (`sub/dir/x.sh`). The latter is the disambiguator when two files
    // share a basename.
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    write_fake_profile(
        &env,
        "profile-1714000001-1-1.tsv",
        &[
            "source\tgpg\tshell\t/p/gpg/sub/dir/env.sh\t1.0\t1.001\t1",
            "source\tgpg\tshell\t/p/gpg/other/env.sh\t1.0\t1.001\t0",
        ],
    );

    // Subpath filter narrows to the matching nested file only.
    let result = commands::probe::shell_init_filter(
        &ctx,
        "gpg/sub/dir/env.sh",
        commands::probe::DEFAULT_FILTER_RUNS,
    )
    .unwrap();
    let view = match result {
        commands::probe::ProbeResult::ShellInitFilter(v) => v,
        other => panic!("expected ShellInitFilter, got {other:?}"),
    };
    assert_eq!(view.targets.len(), 1);
    assert_eq!(view.targets[0].target, "/p/gpg/sub/dir/env.sh");

    // Bare basename still matches both nested files.
    let result_basename = commands::probe::shell_init_filter(
        &ctx,
        "gpg/env.sh",
        commands::probe::DEFAULT_FILTER_RUNS,
    )
    .unwrap();
    let view_basename = match result_basename {
        commands::probe::ProbeResult::ShellInitFilter(v) => v,
        other => panic!("expected ShellInitFilter, got {other:?}"),
    };
    assert_eq!(view_basename.targets.len(), 2);
}

#[test]
fn probe_shell_init_filter_basename_does_not_partial_match() {
    // Boundary check: `env.sh` filter must not match `nvenv.sh`.
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    write_fake_profile(
        &env,
        "profile-1714000001-1-1.tsv",
        &[
            "source\tnv\tshell\t/p/nv/nvenv.sh\t1.0\t1.001\t0",
            "source\tnv\tshell\t/p/nv/env.sh\t1.0\t1.001\t0",
        ],
    );
    let result =
        commands::probe::shell_init_filter(&ctx, "nv/env.sh", commands::probe::DEFAULT_FILTER_RUNS)
            .unwrap();
    let view = match result {
        commands::probe::ProbeResult::ShellInitFilter(v) => v,
        other => panic!("expected ShellInitFilter, got {other:?}"),
    };
    assert_eq!(view.targets.len(), 1);
    assert_eq!(view.targets[0].target, "/p/nv/env.sh");
}

#[test]
fn probe_shell_init_filter_empty_when_no_match() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    write_fake_profile(
        &env,
        "profile-1714000001-1-1.tsv",
        &["source\tvim\tshell\t/p/vim/aliases.sh\t1.0\t1.001\t0"],
    );
    let result =
        commands::probe::shell_init_filter(&ctx, "missing", commands::probe::DEFAULT_FILTER_RUNS)
            .unwrap();
    let view = match result {
        commands::probe::ProbeResult::ShellInitFilter(v) => v,
        other => panic!("expected ShellInitFilter, got {other:?}"),
    };
    assert!(view.targets.is_empty());
    assert_eq!(view.runs_examined, 1);
}

// ── shell-init --errors-only ─────────────────────────────────────

#[test]
fn probe_shell_init_errors_only_keeps_only_failed_runs() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    write_fake_profile(
        &env,
        "profile-1714000001-1-1.tsv",
        &[
            "source\tgpg\tshell\t/p/gpg/env.sh\t1.0\t1.001\t1",
            "source\tvim\tshell\t/p/vim/aliases.sh\t1.0\t1.001\t0",
        ],
    );
    let result =
        commands::probe::shell_init_errors(&ctx, commands::probe::DEFAULT_FILTER_RUNS).unwrap();
    let view = match result {
        commands::probe::ProbeResult::ShellInitErrors(v) => v,
        other => panic!("expected ShellInitErrors, got {other:?}"),
    };
    // vim/aliases.sh succeeded — must not appear. Only gpg/env.sh.
    assert_eq!(view.targets.len(), 1);
    assert_eq!(view.targets[0].display_target, "env.sh");
    assert_eq!(view.targets[0].failure_count, 1);
}

#[test]
fn probe_shell_init_errors_only_sorts_by_failure_count_desc() {
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    // Three profiles: target A fails twice, B fails once.
    write_fake_profile(
        &env,
        "profile-1714000001-1-1.tsv",
        &[
            "source\ta\tshell\t/p/a.sh\t1.0\t1.001\t1",
            "source\tb\tshell\t/p/b.sh\t1.0\t1.001\t1",
        ],
    );
    write_fake_profile(
        &env,
        "profile-1714000002-1-1.tsv",
        &["source\ta\tshell\t/p/a.sh\t1.0\t1.001\t1"],
    );
    let result =
        commands::probe::shell_init_errors(&ctx, commands::probe::DEFAULT_FILTER_RUNS).unwrap();
    let view = match result {
        commands::probe::ProbeResult::ShellInitErrors(v) => v,
        other => panic!("expected ShellInitErrors, got {other:?}"),
    };
    assert_eq!(view.targets.len(), 2);
    assert_eq!(
        view.targets[0].pack, "a",
        "most-broken target must come first"
    );
    assert_eq!(view.targets[0].failure_count, 2);
    assert_eq!(view.targets[1].pack, "b");
    assert_eq!(view.targets[1].failure_count, 1);
}

#[test]
fn probe_shell_init_errors_only_clean_window_says_so() {
    // Only successful runs in the window — view shows 0 targets and
    // the renderer surfaces a cheerful "no failed sources" line.
    let env = TempEnvironment::builder().build();
    let ctx = make_ctx(&env);
    write_fake_profile(
        &env,
        "profile-1714000001-1-1.tsv",
        &["source\tvim\tshell\t/p/aliases.sh\t1.0\t1.001\t0"],
    );
    let result =
        commands::probe::shell_init_errors(&ctx, commands::probe::DEFAULT_FILTER_RUNS).unwrap();
    match &result {
        commands::probe::ProbeResult::ShellInitErrors(v) => {
            assert!(v.targets.is_empty());
            assert_eq!(v.runs_examined, 1);
        }
        other => panic!("expected ShellInitErrors, got {other:?}"),
    }

    let output = render::render("probe", &result, OutputMode::Text).unwrap();
    assert!(
        output.contains("no failed sources"),
        "clean-window message missing:\n{output}"
    );
}

// ── up command misc ─────────────────────────────────────────────

#[test]
fn up_writes_last_up_marker() {
    // The marker is what the staleness check compares against, so the
    // up command must always leave one behind on a successful run.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "x")
        .done()
        .build();
    let ctx = make_ctx(&env);

    assert!(
        !env.fs.exists(&env.paths.last_up_path()),
        "marker should not exist before first up"
    );
    commands::up::up(None, &ctx).unwrap();
    assert!(
        env.fs.exists(&env.paths.last_up_path()),
        "marker should be written by up"
    );

    let raw = env.fs.read_to_string(&env.paths.last_up_path()).unwrap();
    let parsed: u64 = raw.trim().parse().expect("marker should be a unix ts");
    // Sanity: post-2023.
    assert!(parsed > 1_700_000_000, "ts should look recent: {parsed}");
}

// ── deployment map (written on up/down alongside the init script) ──

#[test]
fn up_writes_deployment_map() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .file("bin/tool", "#!/bin/sh")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    env.assert_exists(&env.paths.deployment_map_path());
    let content = env
        .fs
        .read_to_string(&env.paths.deployment_map_path())
        .unwrap();
    assert!(content.starts_with("# dodot deployment map v1"));
    assert!(
        content.contains("vim\tshell\tsymlink\t"),
        "expected a vim/shell row; content:\n{content}"
    );
    assert!(
        content.contains("vim\tpath\tsymlink\t"),
        "expected a vim/path row; content:\n{content}"
    );
}

#[test]
fn down_refreshes_deployment_map_to_empty() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();
    // Precondition: map has a row.
    let content_before = env
        .fs
        .read_to_string(&env.paths.deployment_map_path())
        .unwrap();
    assert!(content_before.contains("aliases.sh"));

    commands::down::down(None, &ctx).unwrap();

    let content_after = env
        .fs
        .read_to_string(&env.paths.deployment_map_path())
        .unwrap();
    // Header stays; data rows are gone.
    assert!(content_after.starts_with("# dodot deployment map v1"));
    assert!(
        !content_after.contains("aliases.sh"),
        "map should be empty after down; got:\n{content_after}"
    );
}

#[test]
fn up_dry_run_does_not_touch_deployment_map() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .done()
        .build();

    let mut ctx = make_ctx(&env);
    ctx.dry_run = true;
    commands::up::up(None, &ctx).unwrap();

    // Map file should not have been written for a dry-run.
    env.assert_not_exists(&env.paths.deployment_map_path());
}

#[test]
fn by_status_folds_ignored_packs_into_ignored_group() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "x")
        .done()
        .pack("disabled")
        .file("stuff", "x")
        .ignored()
        .done()
        .build();

    let mut ctx = make_ctx(&env);
    ctx.group_mode = crate::commands::GroupMode::Status;
    let result = commands::status::status(None, &ctx).unwrap();

    let output = render::render("pack-status", &result, OutputMode::Text).unwrap();

    assert!(output.contains("Ignored Packs"), "output: {output}");
    assert!(output.contains("disabled"), "output: {output}");
    assert!(output.contains("Pending Packs"), "output: {output}");
}

// ── M6: probe::app + advisory probes ─────────────────────────

/// `dodot probe app <pack>` collects every folder this pack would
/// route to (alias, force_app, _app/), checks each against the
/// app-support root, and (with mocked brew + mdls) enriches the
/// matching cask token, .app bundle, and bundle ID. The probe is
/// advisory — resolver state is unchanged.
#[test]
#[cfg_attr(not(target_os = "macos"), ignore = "macOS-only enrichment paths")]
fn probe_app_collects_alias_force_and_underscore_entries() {
    let env = TempEnvironment::builder()
        .pack("vscode")
        .file("settings.json", "{}")
        .file("_app/Cursor/User/keys.json", "[]")
        .file("Code/User/extra.json", "{}")
        .config("[symlink.app_aliases]\nvscode = \"VSCodeAliased\"\n")
        .done()
        .build();
    // Pre-create one of the target folders so `target_exists` differs
    // across rows and the test pins the existence column.
    env.fs.mkdir_all(&env.app_support.join("Cursor")).unwrap();

    let runner = Arc::new(CannedRunner::new());
    runner.respond(
        &["brew", "list", "--cask", "--versions"],
        "cursor 0.42.0\n",
        0,
    );
    runner.respond(
        &["brew", "info", "--json=v2", "--cask", "cursor"],
        r#"{"casks": [{
            "token": "cursor",
            "installed": "0.42.0",
            "artifacts": [
                {"app": ["Cursor.app"]},
                {"zap": [{"trash": [
                    "~/Library/Application Support/Cursor",
                    "~/Library/Preferences/com.todesktop.Cursor.plist"
                ]}]}
            ]
        }]}"#,
        0,
    );
    runner.respond(
        &[
            "mdls",
            "-name",
            "kMDItemCFBundleIdentifier",
            "/Applications/Cursor.app",
        ],
        "kMDItemCFBundleIdentifier = \"com.todesktop.Cursor\"\n",
        0,
    );
    let ctx = make_ctx_with_runner(&env, runner);

    let result = commands::probe::app("vscode", false, &ctx).unwrap();
    let view = match result {
        commands::probe::ProbeResult::App(v) => v,
        other => panic!("expected App variant, got {other:?}"),
    };
    assert_eq!(view.pack, "vscode");
    assert!(view.macos);

    // Three folders: VSCodeAliased (alias), Code (force_app default
    // includes Code), Cursor (_app/ subtree).
    let folders: Vec<&str> = view.entries.iter().map(|e| e.folder.as_str()).collect();
    assert!(folders.contains(&"VSCodeAliased"), "folders: {folders:?}");
    assert!(folders.contains(&"Code"), "folders: {folders:?}");
    assert!(folders.contains(&"Cursor"), "folders: {folders:?}");

    // Cursor is the only pre-created folder → exists; others missing.
    let cursor_row = view.entries.iter().find(|e| e.folder == "Cursor").unwrap();
    assert!(cursor_row.target_exists);
    // `cask` is always an *installed* token (matching iterates only
    // `brew list --cask --versions`), so a `Some` value implies
    // installed — there's no separate field for it any more.
    assert_eq!(cursor_row.cask.as_deref(), Some("cursor"));
    assert_eq!(cursor_row.app_bundle.as_deref(), Some("Cursor.app"));
    assert_eq!(
        cursor_row.bundle_id.as_deref(),
        Some("com.todesktop.Cursor")
    );

    // Sibling-adoption suggestions surfaced from cask zap.
    assert!(
        view.suggested_adoptions
            .iter()
            .any(|s| s.contains("Cursor.plist")),
        "suggested adoptions: {:?}",
        view.suggested_adoptions
    );
}

/// `dodot probe app ..` (or any other path-traversing input) must
/// not let `pack_path` traversal escape the dotfiles root. Probe
/// validates that `pack_name` is a single-component path before
/// passing it to `Pather::pack_path`. Regression for review feedback
/// on PR #91.
#[test]
fn probe_app_rejects_path_traversal_input() {
    let env = TempEnvironment::builder().build();
    let runner = Arc::new(CannedRunner::new());
    let ctx = make_ctx_with_runner(&env, runner);

    for evil in ["..", "foo/../bar", "../sibling", "/abs/path"] {
        let result = commands::probe::app(evil, false, &ctx).unwrap();
        let view = match result {
            commands::probe::ProbeResult::App(v) => v,
            other => panic!("expected App variant, got {other:?}"),
        };
        // Empty-but-named view: the pack name echoes back, but no
        // entries are surfaced (filesystem traversal was skipped).
        assert_eq!(view.pack, evil, "input echoed back unchanged");
        assert!(
            view.entries.is_empty(),
            "path-traversing input must not produce entries: got {:?}",
            view.entries
        );
    }
}

/// On non-macOS, probe::app still produces a useful view (folder
/// existence under the collapsed app-support root) but skips brew /
/// Spotlight enrichment entirely. `macos` is `false`.
#[test]
fn probe_app_non_macos_returns_minimal_view() {
    if cfg!(target_os = "macos") {
        // The cfg! gate inside probe::app keys off the host. On macOS
        // hosts we can't simulate the Linux path; skip rather than
        // contort the test fixture.
        return;
    }
    let env = TempEnvironment::builder()
        .pack("vscode")
        .file("Code/User/foo", "{}")
        .done()
        .build();
    let runner = Arc::new(CannedRunner::new());
    let ctx = make_ctx_with_runner(&env, runner);

    let result = commands::probe::app("vscode", false, &ctx).unwrap();
    let view = match result {
        commands::probe::ProbeResult::App(v) => v,
        other => panic!("expected App variant, got {other:?}"),
    };
    assert!(!view.macos);
    // No brew enrichment.
    for entry in &view.entries {
        assert!(entry.cask.is_none(), "row: {entry:?}");
        assert!(entry.app_bundle.is_none(), "row: {entry:?}");
        assert!(entry.bundle_id.is_none(), "row: {entry:?}");
    }
}

/// `up` / `status` emit a missing-target hint when an app-support
/// folder doesn't exist on disk and a brew cask matches. macOS-only
/// — the orchestration gate is the same `cfg!(target_os = "macos")`.
#[test]
#[cfg_attr(not(target_os = "macos"), ignore = "macOS-only behavior")]
fn plan_pack_emits_missing_target_hint_with_cask_enrichment() {
    use crate::packs::orchestration;
    use crate::packs::Pack;

    let env = TempEnvironment::builder()
        .pack("vscode")
        .file("settings.json", "{}")
        .config("[symlink.app_aliases]\nvscode = \"Code\"\n")
        .done()
        .build();
    // `Code` folder is intentionally absent — the hint should fire.
    assert!(!env.app_support.join("Code").exists());

    let runner = Arc::new(CannedRunner::new());
    runner.respond(
        &["brew", "list", "--cask", "--versions"],
        "visual-studio-code 1.95.0\n",
        0,
    );
    runner.respond(
        &["brew", "info", "--json=v2", "--cask", "visual-studio-code"],
        r#"{"casks": [{
            "token": "visual-studio-code",
            "artifacts": [
                {"app": ["Visual Studio Code.app"]},
                {"zap": [{"trash": ["~/Library/Application Support/Code"]}]}
            ]
        }]}"#,
        0,
    );
    let ctx = make_ctx_with_runner(&env, runner);

    // The planner uses cache_only=true to keep `up`/`status` fast —
    // an empty cache produces the unenriched message. Pre-warm the
    // cache by calling info_cask once (the on-demand path that may
    // spawn brew). Production users get the same warm cache via
    // `dodot probe app` or `dodot adopt`.
    let cache_dir = ctx.paths.probes_brew_cache_dir();
    let _ = crate::probe::brew::info_cask(
        "visual-studio-code",
        &cache_dir,
        crate::probe::brew::now_secs_unix(),
        ctx.fs.as_ref(),
        ctx.command_runner.as_ref(),
    );

    // Synthesize a Pack matching the on-disk pack we built.
    let pack_path = env.dotfiles_root.join("vscode");
    let pack_config = ctx.config_manager.config_for_pack(&pack_path).unwrap();
    let pack = Pack {
        name: "vscode".into(),
        display_name: "vscode".into(),
        path: pack_path,
        config: pack_config.to_handler_config(),
    };

    let plan = orchestration::plan_pack(&pack, &ctx, crate::preprocessing::PreprocessMode::Active)
        .unwrap();
    let hint = plan.warnings.iter().find(|w| w.contains("Code"));
    assert!(
        hint.is_some(),
        "expected missing-target hint mentioning `Code`; got {:?}",
        plan.warnings
    );
    let hint_text = hint.unwrap();
    assert!(
        hint_text.contains("visual-studio-code"),
        "expected cask-enriched hint, got: {hint_text}"
    );
    // Per review feedback: the cask is installed (we read it from
    // `brew list`), so the message must NOT claim it isn't installed.
    assert!(
        !hint_text.contains("isn't installed"),
        "hint should not falsely claim the cask is uninstalled, got: {hint_text}"
    );
}