dodot-lib 5.4.1

Core library for dodot dotfiles manager
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
//! Integration tests for the command API.

mod adopt;
mod gating;
mod probe;
mod reset;
mod support;

#[allow(unused_imports)]
use std::sync::Arc;

use crate::commands;
#[allow(unused_imports)]
use crate::config::ConfigManager;
#[allow(unused_imports)]
use crate::datastore::{CommandOutput, CommandRunner, FilesystemDataStore};
use crate::fs::Fs;
#[allow(unused_imports)]
use crate::packs::orchestration::ExecutionContext;
#[allow(unused_imports)]
use crate::paths::Pather;
use crate::render;
use crate::testing::TempEnvironment;
#[allow(unused_imports)]
use crate::Result;
use standout_render::OutputMode;

use support::make_ctx;
#[allow(unused_imports)]
use support::{make_ctx_with_runner, CannedRunner};

// ── 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());

    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.
#[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_marks_readme_and_license_as_skipped() {
    // Files matched by `mappings.skip` (defaults: README, LICENSE,
    // CHANGELOG, …) should appear in status with handler "skip"
    // and status "skipped" rather than being silently dropped or
    // routed to the symlink catchall.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "set nocompatible")
        .file("README.md", "# vim pack")
        .file("license", "MIT")
        .file("CHANGELOG", "v1: initial")
        .done()
        .build();

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

    let pack = &result.packs[0];
    let by_name: std::collections::HashMap<&str, &commands::DisplayFile> =
        pack.files.iter().map(|f| (f.name.as_str(), f)).collect();

    let readme = by_name.get("README.md").expect("README.md in status");
    assert_eq!(readme.handler, "skip");
    assert_eq!(readme.status, "skipped");
    assert_eq!(readme.status_label, "skipped");

    let license = by_name.get("license").expect("license in status");
    assert_eq!(license.handler, "skip", "case-insensitive match");

    let changelog = by_name.get("CHANGELOG").expect("CHANGELOG in status");
    assert_eq!(changelog.handler, "skip");

    let vimrc = by_name.get("vimrc").expect("vimrc in status");
    assert_eq!(vimrc.handler, "symlink");
}

#[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();

    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}");

    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.len(), 1);
    assert_eq!(result.ignored_packs[0].name, "disabled");
    assert_eq!(result.ignored_packs[0].display_name, "disabled");
    assert_eq!(result.ignored_packs[0].ignore_file, ".dodotignore");

    let output = render::render("pack-status", &result, OutputMode::Text).unwrap();
    assert!(!output.contains("Ignored Packs"), "output: {output}");
    assert!(
        output.contains("\n\n∅ disabled"),
        "ignored row should follow active rows after one blank line: {output}"
    );
    assert!(output.contains(".dodotignore"), "output: {output}");
    assert!(output.ends_with("ignored\n"), "output: {output}");

    let styled = render::render("pack-status", &result, OutputMode::TermDebug).unwrap();
    let ignored_row = styled
        .lines()
        .find(|line| line.contains("disabled"))
        .expect("ignored row");
    assert!(
        ignored_row.starts_with("[dim]∅[/dim] disabled"),
        "{ignored_row}"
    );
    assert!(
        ignored_row.contains("[dim].dodotignore")
            && ignored_row.contains("[/dim] [ignored-pack]ignored"),
        "{ignored_row}"
    );
    assert!(
        ignored_row.ends_with("[ignored-pack]ignored[/ignored-pack]"),
        "{ignored_row}"
    );
    assert!(
        !ignored_row.contains("[ignored-pack]disabled"),
        "{ignored_row}"
    );

    let json = render::render("pack-status", &result, OutputMode::Json).unwrap();
    let value: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert_eq!(value["ignored_packs"][0]["ignore_file"], ".dodotignore");
}

#[test]
fn status_pack_filter_applies_to_ignored_packs() {
    // `dodot status <name>` should narrow both the main listing and the
    // ignored rows 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");
    let ignored_names: Vec<String> = result
        .ignored_packs
        .iter()
        .map(|p| p.name.clone())
        .collect();
    assert_eq!(ignored_names, vec!["disabled".to_string()]);

    let output = render::render("pack-status", &result, OutputMode::Text).unwrap();
    assert!(!output.starts_with('\n'), "ignored-only output: {output:?}");
    assert!(
        output.starts_with("∅ disabled"),
        "ignored-only output: {output:?}"
    );
}

// ── 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() {
    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:?}"
    );
}

/// Status must follow the planner's intent expansion for
/// escape-prefix directories (`_home/`, `_xdg/`, `_app/`, `_lib/`).
///
/// Iterating raw scanner matches would render `_app` as a single row
/// resolving to the default rule
/// (`$XDG_CONFIG_HOME/<pack>/_app`) — a path the planner never deploys
/// to. Because the data link for that bogus target never exists,
/// verification reported "pending" indefinitely, even after a
/// successful `up`. Meanwhile the real leaf files (deployed under
/// `<app_support>/...` per the `_app/<rest>` rule) didn't appear in
/// status output at all.
///
/// Status drives its deployable rows from
/// `orchestration::plan_pack` (the same intents the executor runs),
/// not from raw matches. This test pins that contract end-to-end:
/// after `up`, status must show the per-leaf row deployed at the
/// app-support path — never an `_app` row pointing at
/// `~/.config/<pack>/_app pending`.
#[test]
fn up_then_status_expands_app_escape_prefix_per_file() {
    let env = TempEnvironment::builder()
        .pack("iina")
        .file("_app/com.colliderli.iina/input_conf/mine.conf", "# keys")
        .done()
        .build();

    let ctx = make_ctx(&env);

    // up must deploy the leaf to the app-support path the planner's
    // `_app/<rest>` rule resolves to.
    commands::up::up(None, &ctx).unwrap();
    let deployed_user_link = env
        .app_support
        .join("com.colliderli.iina/input_conf/mine.conf");
    assert!(
        env.fs.is_symlink(&deployed_user_link),
        "up should have created the user link at {}",
        deployed_user_link.display()
    );

    // status must render that deployment, not a bogus `_app` row.
    let result = commands::status::status(None, &ctx).unwrap();
    let pack = result
        .packs
        .iter()
        .find(|p| p.name == "iina")
        .expect("iina pack must appear in status");

    // No row should claim the bogus default-rule target. If status
    // emits an `_app` row at all, it must not pretend the deploy
    // landed under `~/.config/iina/_app`.
    let bogus_target_row = pack
        .files
        .iter()
        .find(|f| f.handler == "symlink" && f.description.contains(".config/iina/_app"));
    assert!(
        bogus_target_row.is_none(),
        "status must not surface the default-rule `_app` target; \
         escape-prefix dirs expand per-file. got: {:?}",
        pack.files
            .iter()
            .map(|f| (&f.name, &f.description, &f.status))
            .collect::<Vec<_>>()
    );

    // The leaf file must appear as a deployed symlink row, with the
    // target pointing somewhere under the app-support root.
    let leaf = pack
        .files
        .iter()
        .find(|f| {
            f.handler == "symlink"
                && f.description
                    .contains("com.colliderli.iina/input_conf/mine.conf")
        })
        .unwrap_or_else(|| {
            panic!(
                "expected a deployed leaf row for the `_app/.../mine.conf` file; got: {:?}",
                pack.files
                    .iter()
                    .map(|f| (&f.name, &f.description, &f.status))
                    .collect::<Vec<_>>()
            )
        });
    assert_eq!(
        leaf.status, "deployed",
        "leaf row must be deployed after up; row: {leaf:?}"
    );
}

// ── 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());

    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");
}

/// `up` and `status` must
/// produce identical per-file status_label strings for the same handler
/// state, using steady-state 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);

    // Shell rows report the newest observed shell-init run, so seed a
    // clean profile for aliases.sh up front — both the up rendering
    // and the status call then see the same observation.
    let target = env
        .dotfiles_root
        .join("multi/aliases.sh")
        .display()
        .to_string();
    write_shell_profile(&env, 1714000001, &[(&target, 0)]);

    let up_result = commands::up::up(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; // 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
    // ("linked", "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(&"linked"),
        "expected symlink handler to render as 'linked', got: {labels:?}"
    );
    assert!(
        labels.iter().all(|l| !l.starts_with("staged ")),
        "no label should use the executor's 'staged X' vocabulary, got: {labels:?}"
    );
}

/// `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"
    );

    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();

    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();

    // Runtime history exists for both files — including a FAILING run
    // for aliases.sh — but the syntax-error sidecar is the harder
    // signal and must take precedence over runtime history; env.sh's
    // clean newest run renders as sourced.
    let aliases_target = env
        .dotfiles_root
        .join("vim/aliases.sh")
        .display()
        .to_string();
    let env_target = env.dotfiles_root.join("vim/env.sh").display().to_string();
    write_shell_profile(&env, 1714000001, &[(&aliases_target, 1), (&env_target, 0)]);

    // Status flags aliases.sh as broken and leaves
    // 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");
}

/// Write one fake shell-init profile TSV under the probes dir. `t0`
/// orders profiles (higher = newer); `entries` adds one `source` row
/// per (absolute target path, exit status) pair. The pack column is a
/// fixed placeholder — status matches runs by phase + target only.
fn write_shell_profile(env: &TempEnvironment, t0: u64, entries: &[(&str, i32)]) {
    let probes_dir = env.paths.probes_shell_init_dir();
    env.fs.mkdir_all(&probes_dir).unwrap();
    let mut body =
        format!("# dodot shell-init profile v1\n# shell\tbash 5.0\n# start_t\t{t0}.000000\n");
    for (target, exit) in entries {
        body.push_str(&format!(
            "source\tvim\tshell\t{target}\t{t0}.000100\t{t0}.000900\t{exit}\n"
        ));
    }
    body.push_str(&format!("# end_t\t{t0}.001000\n"));
    env.fs
        .write_file(
            &probes_dir.join(format!("profile-{t0:010}-100-1.tsv")),
            body.as_bytes(),
        )
        .unwrap();
}

#[test]
fn status_shell_latest_failure_reports_newest_exit() {
    // The row verdict comes from the NEWEST observed run. Distinct
    // exit codes for the old vs. new failure: oldest=2, newest=1, so
    // the label must say `exited 1` — and nothing else: the failure
    // count lives in the warning footnote, not the row.
    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 target = env
        .dotfiles_root
        .join("vim/aliases.sh")
        .display()
        .to_string();
    write_shell_profile(&env, 1714000001, &[(&target, 2)]); // oldest failure
    write_shell_profile(&env, 1714000002, &[(&target, 0)]); // clean middle run
    write_shell_profile(&env, 1714000003, &[(&target, 1)]); // newest 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:?}");
    assert_eq!(
        row.status_label, "exited 1",
        "row label is the newest run's verdict alone"
    );

    let note_idx = row.note_ref.expect("expected note ref") as usize;
    let note = &result.notes[note_idx - 1];
    assert_eq!(note.kind, "warning", "run history is a warning: {note:?}");
    assert_eq!(note.body, "2 of the last 3 runs failed");
    // Timeline is oldest→newest so its last symbol matches the row
    // verdict: ✗ ✓ ✗.
    assert_eq!(note.timeline, Some(vec![false, true, false]));
    assert_eq!(
        note.command.as_deref(),
        Some("dodot probe shell-init vim/aliases.sh"),
        "footnote points at the per-file probe view for history + stderr"
    );
}

#[test]
fn status_shell_latest_success_keeps_row_deployed_despite_history() {
    // Historical failures must not turn a currently successful row
    // red or roll the pack up as an error — they only add a
    // warning-kind footnote.
    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 target = env
        .dotfiles_root
        .join("vim/aliases.sh")
        .display()
        .to_string();
    write_shell_profile(&env, 1714000001, &[(&target, 1)]); // old failure
    write_shell_profile(&env, 1714000002, &[(&target, 0)]); // newest run clean

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

    assert_eq!(row.status, "deployed", "row: {row:?}");
    assert_eq!(row.status_label, "sourced");
    assert_eq!(
        pack.summary_status, "deployed",
        "recent instability must not roll the pack up as broken"
    );

    let note_idx = row.note_ref.expect("expected note ref") as usize;
    let note = &result.notes[note_idx - 1];
    assert_eq!(note.kind, "warning");
    assert_eq!(note.body, "1 of the last 2 runs failed");
    assert_eq!(note.timeline, Some(vec![false, true]));
}

#[test]
fn status_shell_clean_history_renders_sourced_without_note() {
    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 target = env
        .dotfiles_root
        .join("vim/aliases.sh")
        .display()
        .to_string();
    write_shell_profile(&env, 1714000001, &[(&target, 0)]);
    write_shell_profile(&env, 1714000002, &[(&target, 0)]);

    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, "deployed", "row: {row:?}");
    assert_eq!(row.status_label, "sourced");
    assert!(row.note_ref.is_none(), "clean history needs no footnote");
    assert!(result.notes.is_empty(), "notes: {:?}", result.notes);
}

#[test]
fn status_shell_unobserved_renders_pending() {
    // Deployed chain but no shell-init run has been observed yet:
    // dodot claims `sourced` only after seeing it happen, so the row
    // keeps the pending presentation.
    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 row = result.packs[0]
        .files
        .iter()
        .find(|f| f.name == "aliases.sh")
        .expect("aliases.sh row missing");

    assert_eq!(row.status, "pending", "row: {row:?}");
    assert_eq!(row.status_label, "not sourced");
    assert!(row.note_ref.is_none());
}

#[test]
fn status_shell_unrelated_profile_entries_do_not_count() {
    // Profiles exist but none of them sourced this file — unrelated
    // entries never count as applicable runs, so the row stays on the
    // pending presentation instead of borrowing another file's runs.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .file("env.sh", "export FOO=bar")
        .done()
        .build();

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

    let other = env.dotfiles_root.join("vim/env.sh").display().to_string();
    write_shell_profile(&env, 1714000001, &[(&other, 1)]);

    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, "pending", "row: {row:?}");
    assert_eq!(row.status_label, "not sourced");
    assert!(row.note_ref.is_none());
}

#[test]
fn status_shell_profiling_disabled_keeps_chain_verdict() {
    // With `[profiling]` off no observation can ever arrive, so the
    // chain verdict stands — the row must not pin itself on a pending
    // state it could never leave.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .done()
        .build();

    env.fs
        .write_file(
            &env.dotfiles_root.join(".dodot.toml"),
            b"[profiling]\nenabled = false\n",
        )
        .unwrap();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).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");

    assert_eq!(row.status, "deployed", "row: {row:?}");
    assert_eq!(row.status_label, "sourced");
}

#[test]
fn pack_status_renders_flaky_timeline_with_semantic_styles() {
    // TermDebug mode renders style names as bracket tags, pinning the
    // exact style boundaries: warning marker, per-run ✓/✗ symbols in
    // deployed/error styles (oldest→newest), warning prose around a
    // normal-emphasis probe command — under `Warnings:`, never under
    // a red-only `Errors:` header.
    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 target = env
        .dotfiles_root
        .join("vim/aliases.sh")
        .display()
        .to_string();
    write_shell_profile(&env, 1714000001, &[(&target, 0)]);
    write_shell_profile(&env, 1714000002, &[(&target, 0)]);
    write_shell_profile(&env, 1714000003, &[(&target, 0)]);
    write_shell_profile(&env, 1714000004, &[(&target, 1)]);
    write_shell_profile(&env, 1714000005, &[(&target, 1)]);

    let result = commands::status::status(None, &ctx).unwrap();
    let out = render::render("pack-status", &result, OutputMode::TermDebug).unwrap();

    // Row: newest run failed, but only the status text carries the verdict.
    assert!(
        out.contains("vim                  [dim]⚙[/dim]")
            && out.contains("[dim]aliases.sh")
            && out.contains("[broken]exited 1[/broken] [dim][1][/dim]"),
        "row should isolate the broken verdict to its status, got:\n{out}"
    );
    assert!(
        !out.contains("[broken]vim"),
        "pack must stay unstyled: {out}"
    );
    // Footnote: plain marker, ✓/✗ timeline oldest→newest, warning
    // prose around a muted normal-colour probe command.
    assert!(
        out.contains(
            "[1] [deployed]✓[/deployed] [deployed]✓[/deployed] \
             [deployed]✓[/deployed] [error]✗[/error] [error]✗[/error] \
             [warning]2 of the last 5 runs failed, see [/warning]\
             [diagnostic-command]dodot probe shell-init vim/aliases.sh[/diagnostic-command]\
             [warning] for more.[/warning]"
        ),
        "footnote should render the styled timeline, got:\n{out}"
    );
    assert!(
        out.contains("Warnings:"),
        "run history renders under Warnings:, got:\n{out}"
    );
    assert!(
        !out.contains("Errors:"),
        "run history must not present under Errors:, got:\n{out}"
    );
}

#[test]
fn pack_status_renders_latest_success_row_green_with_warning_marker() {
    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 target = env
        .dotfiles_root
        .join("vim/aliases.sh")
        .display()
        .to_string();
    write_shell_profile(&env, 1714000001, &[(&target, 1)]);
    write_shell_profile(&env, 1714000002, &[(&target, 0)]);

    let result = commands::status::status(None, &ctx).unwrap();
    let out = render::render("pack-status", &result, OutputMode::TermDebug).unwrap();

    assert!(
        out.contains("vim                  [dim]⚙[/dim]")
            && out.contains("[dim]aliases.sh")
            && out.contains("[deployed]sourced[/deployed] [dim][1][/dim]"),
        "currently-clean row styles only its status and marker, got:\n{out}"
    );
    assert!(
        !out.contains("[deployed]vim"),
        "pack must stay unstyled: {out}"
    );
    assert!(
        out.contains(
            "[error]✗[/error] [deployed]✓[/deployed] \
             [warning]1 of the last 2 runs failed, see [/warning]\
             [diagnostic-command]dodot probe shell-init vim/aliases.sh[/diagnostic-command]\
             [warning] for more.[/warning]"
        ),
        "timeline reads oldest→newest so the last symbol matches the row, got:\n{out}"
    );
    assert!(!out.contains("Errors:"), "got:\n{out}");
}

#[test]
fn pack_status_renders_unobserved_shell_row_as_pending() {
    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 out = render::render("pack-status", &result, OutputMode::TermDebug).unwrap();

    assert!(
        out.contains("vim                  [dim]⚙[/dim]")
            && out.contains("[dim]aliases.sh")
            && out.contains("[pending]not sourced[/pending]"),
        "unobserved shell row styles only its pending status, got:\n{out}"
    );
    assert!(
        !out.contains("[pending]vim"),
        "pack must stay unstyled: {out}"
    );
    assert!(!out.contains("Warnings:"), "got:\n{out}");
    assert!(!out.contains("Errors:"), "got:\n{out}");
}

#[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();

    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}");

    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);

    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 ───────────────────────────────────

#[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"
    );
}

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

#[test]
fn up_reports_conflict_when_file_exists() {
    // home.gitconfig 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();

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

    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 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 identify the failing file in the left column.
    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
    );

    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.
    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();

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

    let content = env.fs.read_to_string(&env.home.join(".gitconfig")).unwrap();
    assert_eq!(content, "[user]\n  name = new");
}

// ── up: reconcile non-provisioning state ────────────────────

/// `dodot up` wipes configuration-handler state per pack before
/// reapplying current sources, so deleted entries cannot remain sourced.
#[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"]);

    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"]);

    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: Vec<_> = env
        .list_dir_names(&install_dir)
        .into_iter()
        .filter(|n| !n.ends_with(".snapshot"))
        .collect();
    assert_eq!(
        sentinels_before.len(),
        1,
        "expected one sentinel, got {sentinels_before:?}"
    );
    let original = sentinels_before.into_iter().next().unwrap();

    commands::up::up(None, &ctx).unwrap();
    let sentinels_after: Vec<_> = env
        .list_dir_names(&install_dir)
        .into_iter()
        .filter(|n| !n.ends_with(".snapshot"))
        .collect();
    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: Vec<_> = env
        .list_dir_names(&install_dir)
        .into_iter()
        .filter(|n| !n.ends_with(".snapshot"))
        .collect();
    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: Vec<_> = env
        .list_dir_names(&install_dir)
        .into_iter()
        .filter(|n| !n.ends_with(".snapshot"))
        .collect();
    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);

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

    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");

    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`.
    // `PendingConflict` only fires 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);

    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}"
    );
}

// ── 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);
    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);
    commands::up::up(None, &ctx).unwrap();

    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
    );
}

// ── 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);

    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");
        }
    }

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

    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);

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

    // Dangling user-side symlinks left by `down` are not conflicts
    // (the 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
            );
        }
    }

    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");
}

/// 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 (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
    );

    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"
    );
}

/// 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.
#[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();

    let source = env.dotfiles_root.join("kitty/kittyrc");
    let kitty_target = env.home.join(".kittyrc");
    env.fs.symlink(&source, &kitty_target).unwrap();

    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, "linked");
}

#[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();

    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 the user symlink with a
    // regular file whose content does NOT match source — that's a real
    // conflict; auto-replace only applies to 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();

    // "Verified" for shell files means observed: seed a clean
    // shell-init run so the row can claim `sourced`.
    let target = env
        .dotfiles_root
        .join("vim/aliases.sh")
        .display()
        .to_string();
    write_shell_profile(&env, 1714000001, &[(&target, 0)]);

    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();

    let source = env.dotfiles_root.join("vim/aliases.sh");
    env.fs.remove_file(&source).unwrap();

    // Recreate the source so the scanner sees it, then break the data link.
    env.fs.write_file(&source, b"alias vi=vim").unwrap();

    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");
}

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

#[test]
fn up_succeeds_after_resolving_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 err = commands::up::up(None, &ctx).unwrap_err();
    assert!(matches!(err, crate::DodotError::CrossPackConflict { .. }));

    let filter = vec!["pack-a".into()];
    let result = commands::up::up(Some(&filter), &ctx).unwrap();
    assert_eq!(result.message.as_deref(), Some("Packs 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() {
    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 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);

    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();

    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();

    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();

    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() {
    // Status uses post-preprocessing entries so a deployed `greet.tmpl`
    // appears as `greet`, not a pending source template.
    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);

    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:?}");

    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() {
    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,
    };

    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);

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

    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");

    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();

    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 full_mode_renders_80_column_rows_with_isolated_status_style() {
    use crate::commands::{DisplayFile, DisplayPack, PackStatusResult};

    let result = PackStatusResult {
        message: None,
        dry_run: false,
        packs: vec![DisplayPack::new(
            "vim".into(),
            vec![DisplayFile {
                name: "a-very-long-middle-section-that-must-be-clipped-config.toml".into(),
                symbol: "".into(),
                description: "SHOULD NOT RENDER".into(),
                status: "deployed".into(),
                status_label: "stale: user link missing, re-deploy to fix".into(),
                handler: "symlink".into(),
                note_ref: None,
            }],
        )],
        warnings: Vec::new(),
        notes: Vec::new(),
        conflicts: Vec::new(),
        ignored_packs: Vec::new(),
        inactive_packs: Vec::new(),
        view_mode: "full".into(),
        group_mode: "name".into(),
        diffs: Vec::new(),
    };

    let text = render::render("pack-status", &result, OutputMode::Text).unwrap();
    let row = text.lines().next().expect("status row");
    assert_eq!(standout_render::tabular::display_width(row), 80, "{row:?}");
    assert!(
        row.starts_with("vim                  ➞ "),
        "filename should start in column 24 after a 20-column pack: {row:?}"
    );
    assert!(row.contains(''), "long filenames should clip: {row:?}");
    assert!(
        row.ends_with("stale: user link missing, re-deploy to fix"),
        "full status should survive and touch column 80: {row:?}"
    );

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

    assert!(
        output.contains("[dim]➞[/dim]"),
        "row should contain the dimmed icon: {output}"
    );
    assert!(
        output.contains("vim "),
        "row should contain the pack name: {output}"
    );
    assert!(
        output.contains("[dim]a-very") && output.contains('') && output.contains("ig.toml[/dim]"),
        "row should contain the dimmed, middle-clipped file name: {output}"
    );
    assert!(
        output.contains("[deployed]stale: user link missing, re-deploy to fix[/deployed]"),
        "row should contain the full deployed status tag: {output}"
    );
    assert!(
        !output.contains("[deployed]vim"),
        "pack must be regular: {output}"
    );
    assert_eq!(output.matches("[deployed]").count(), 1, "{output}");
    assert!(
        !output.contains("SHOULD NOT RENDER"),
        "full output should not include the handler-description column: {output}"
    );
}

#[test]
fn diagnostics_render_severity_headings_plain_markers_and_muted_commands() {
    use crate::commands::{DisplayNote, PackStatusResult};

    let result = PackStatusResult {
        message: None,
        dry_run: false,
        packs: Vec::new(),
        warnings: Vec::new(),
        notes: vec![
            DisplayNote {
                body: "target exists".into(),
                hint: None,
                kind: "error".into(),
                timeline: None,
                command: Some("dodot status git".into()),
            },
            DisplayNote {
                body: "1 of the last 2 runs failed".into(),
                hint: None,
                kind: "warning".into(),
                timeline: Some(vec![false, true]),
                command: Some("dodot probe shell-init vim/aliases.sh".into()),
            },
        ],
        conflicts: Vec::new(),
        ignored_packs: Vec::new(),
        inactive_packs: Vec::new(),
        view_mode: "full".into(),
        group_mode: "name".into(),
        diffs: Vec::new(),
    };

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

    assert!(output.contains("[error]Errors:[/error]"), "got:\n{output}");
    assert!(
        output.contains("[warning]Warnings:[/warning]"),
        "got:\n{output}"
    );
    assert!(
        output.contains(
            "[1] [error]target exists, see [/error]\
             [diagnostic-command]dodot status git[/diagnostic-command]\
             [error] for more.[/error]"
        ),
        "error note should keep marker plain and command muted: {output}"
    );
    assert!(
        output.contains(
            "[2] [error]✗[/error] [deployed]✓[/deployed] \
             [warning]1 of the last 2 runs failed, see [/warning]\
             [diagnostic-command]dodot probe shell-init vim/aliases.sh[/diagnostic-command]\
             [warning] for more.[/warning]"
        ),
        "warning note should keep marker plain, timeline styled, and command muted: {output}"
    );
    assert!(
        !output.contains("[warning][2][/warning]"),
        "diagnostic list markers should not carry severity styling: {output}"
    );
    assert!(
        !output.contains("`dodot"),
        "diagnostic commands should render without Markdown backticks: {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();

    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}"
    );
    assert!(output.contains("vim"), "output: {output}");
    assert!(output.contains("nvim"), "output: {output}");
}

#[test]
fn multi_file_pack_and_ignored_pack_rendering() {
    use crate::commands::{DisplayFile, DisplayPack, PackStatusResult};
    use crate::packs::IgnoredPack;

    let result = PackStatusResult {
        message: None,
        dry_run: false,
        packs: vec![DisplayPack::new(
            "tmux".into(),
            vec![
                DisplayFile {
                    name: "tmux.conf".into(),
                    symbol: "".into(),
                    description: "".into(),
                    status: "deployed".into(),
                    status_label: "deployed".into(),
                    handler: "symlink".into(),
                    note_ref: None,
                },
                DisplayFile {
                    name: "tmux.conf.local".into(),
                    symbol: "".into(),
                    description: "".into(),
                    status: "deployed".into(),
                    status_label: "deployed".into(),
                    handler: "symlink".into(),
                    note_ref: None,
                },
            ],
        )],
        warnings: Vec::new(),
        notes: Vec::new(),
        conflicts: Vec::new(),
        ignored_packs: vec![IgnoredPack {
            name: "vscode".into(),
            display_name: "vscode".into(),
            ignore_file: ".dodotignore".into(),
        }],
        inactive_packs: Vec::new(),
        view_mode: "full".into(),
        group_mode: "name".into(),
        diffs: Vec::new(),
    };

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

    let row1 = lines.next().unwrap();
    assert!(
        row1.starts_with("tmux                 ➞ tmux.conf"),
        "first row shows pack name: {row1:?}"
    );

    let row2 = lines.next().unwrap();
    assert!(
        row2.starts_with("                     ➞ tmux.conf.local"),
        "second row suppresses pack name: {row2:?}"
    );

    let ignored_row = lines.find(|l| !l.trim().is_empty()).unwrap();
    assert!(
        ignored_row.starts_with("∅ vscode               .dodotignore"),
        "ignored packs keep explicit layout: {ignored_row:?}"
    );
}