fallow-types 3.29.0

Shared types and serde paths for fallow codebase intelligence
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
//! Workspace and source-discovery diagnostic data types.
//!
//! The serializable `WorkspaceDiagnostic` / `WorkspaceDiagnosticKind` pair
//! lives here, upstream of both `fallow-config` (which owns the registry and
//! emission logic and re-exports these types for back-compat) and
//! `fallow-output` (which embeds `Vec<WorkspaceDiagnostic>` in its JSON
//! envelopes). Keeping the data types in `fallow-types` lets the output layer
//! reference the real, schema-bearing type instead of an opaque
//! `serde_json::Value` newtype, so `workspace_diagnostics[]` keeps its typed
//! `kind`/`path`/`message` shape (and the typed `kind` oneOf) in
//! `docs/output-schema.json` without coupling output contracts to config
//! loading.

use std::path::{Path, PathBuf};

use rustc_hash::FxHashSet;
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::path_util::display_relative;
use crate::serde_path;

/// Why a workspace-discovery candidate was rejected, or why a sibling
/// directory looked workspace-like but was not declared.
///
/// Wire-format names are kebab-case so JSON consumers (CI integrations, MCP
/// agents, LSP clients) get a stable, language-neutral identifier.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum WorkspaceDiagnosticKind {
    /// A directory contains `package.json` but is not declared as a workspace
    /// in `package.json` `workspaces`, `pnpm-workspace.yaml`, or
    /// `tsconfig.json` `references`. Surfaced by
    /// `find_undeclared_workspaces`.
    UndeclaredWorkspace,
    /// A declared workspace's `package.json` failed to parse. The directory is
    /// dropped from discovery, but analysis still proceeds (degraded).
    MalformedPackageJson {
        /// `serde_json` parse error text.
        error: String,
    },
    /// A workspace glob pattern matched a directory that contains no
    /// `package.json`. Honors the extended skip list and `ignorePatterns`
    /// before emitting.
    GlobMatchedNoPackageJson {
        /// The glob pattern that matched the directory.
        pattern: String,
    },
    /// `tsconfig.json` exists at the root but failed to parse. Project
    /// references cannot be discovered.
    MalformedTsconfig {
        /// JSONC parse error text.
        error: String,
    },
    /// `tsconfig.json` lists a `references[].path` that does not point to an
    /// existing directory.
    TsconfigReferenceDirMissing,
    /// `pnpm-workspace.yaml` exists but failed to parse as YAML. Catalog and
    /// dependency-override analysis proceeds with no entries (degraded), so
    /// `catalog:`-referenced dependencies may be misclassified until the
    /// syntax is fixed.
    MalformedPnpmWorkspaceYaml {
        /// `serde_yaml_ng` parse error text.
        error: String,
    },
    /// A source file was skipped at discovery because it exceeds the configured
    /// per-file size limit (`--max-file-size` / `FALLOW_MAX_FILE_SIZE`, default
    /// 5 MB). The file is never read, parsed, or analyzed, guarding against the
    /// out-of-memory blowup a single multi-MB generated/vendored/bundled file
    /// causes (issue #1086). Surfaced by source discovery, not workspace
    /// discovery, but shares this channel so the skip is visible in
    /// `workspace_diagnostics[]` on `fallow dead-code / dupes / health` JSON.
    SkippedLargeFile {
        /// On-disk size of the skipped file in bytes.
        size_bytes: u64,
    },
    /// A large JavaScript bundle was skipped at discovery because it appears to
    /// be minified generated output. The file is never parsed or analyzed,
    /// guarding against sub-limit bundles that can still create very large ASTs
    /// and extraction payloads (issue #1086). Use `--max-file-size 0` when the
    /// bundled file really should be analyzed.
    SkippedMinifiedFile {
        /// On-disk size of the skipped file in bytes.
        size_bytes: u64,
    },
    /// A dot-prefixed directory was not traversed by source discovery even
    /// though it contains at least one source file the project has not
    /// excluded. Hidden directories are skipped by default apart from a small
    /// convention allowlist (`.storybook`, `.vitepress`, `.well-known`,
    /// `.changeset`, `.github`) and the directories an active framework plugin
    /// or a `package.json` script reference contributes, so files inside are
    /// never parsed and their imports and exports are invisible to every
    /// analysis. A file, export or dependency that only the directory uses can
    /// be reported as unused. No config field adds a directory to traversal:
    /// add the file to `entry`, the export to `ignoreExports` or the dependency
    /// to `ignoreDependencies` to stop that false positive, or add the
    /// directory to `ignorePatterns` to silence this (issue #461). Running
    /// fallow with `--root` against the directory analyzes it on its own and
    /// does not fix the main run (issue #2797).
    ///
    /// "Not excluded" is measured the way the run measures it: a directory
    /// whose contents are gitignored, or excluded by `ignorePatterns`, or (on
    /// a `--production` run) excluded as test or story files, never earns this
    /// diagnostic, because the advertised remedies would find nothing there
    /// either. Generated tool output and non-git VCS metadata are excluded by
    /// name.
    ///
    /// The advisory is best-effort and bounded: one run inspects a fixed
    /// number of skipped directories with a fixed I/O budget, in sorted path
    /// order, so a pathological tree yields a deterministic prefix rather than
    /// an unbounded array or an unbounded scan. The stderr note says "at
    /// least" when a ceiling bound the run.
    ///
    /// Surfaced by source discovery, not workspace discovery, but shares this
    /// channel so the skip is visible in `workspace_diagnostics[]` on
    /// `fallow dead-code / dupes / health` JSON.
    ///
    /// Unlike the two skipped-file kinds beside it, this one is CAPPED. To
    /// bound the directory reads the check costs, a run classifies at most 64
    /// candidate directories and spends at most 1024 directory entries across
    /// all of them, so on a project that exceeds either ceiling the array is a
    /// prefix of the skipped directories rather than all of them, and the
    /// stderr note says "at least N". No measured repository comes close to
    /// either ceiling. A consumer needing an exact total should run fallow
    /// with `--root` against the tree rather than infer one from this array.
    SkippedSourceDotdir,
    /// A source discovered with a stable [`FileId`](crate::discover::FileId)
    /// could not be read before parsing. Analysis continues with the remaining
    /// sparse module IDs and reports the underlying filesystem or UTF-8 error.
    SourceReadFailure {
        /// Filesystem or UTF-8 decoding error from `read_to_string`.
        error: String,
    },
    /// A source file was read but parsed with diagnostics, so the module
    /// extracted from it may be missing imports, exports, or references after
    /// the first error. Analysis proceeds with the partial module, which is why
    /// this is reported: an import the parser never saw credits nothing, and its
    /// target can surface as a confident `unused-file` or `unused-export`
    /// finding with a `delete-file` or `remove-export` action on it.
    ///
    /// Recorded by the parse stage, alongside `source-read-failure`, and never
    /// used to withhold a finding. oxc reports recoverable errors for valid
    /// syntax newer than the parser as well as for genuinely broken files, so
    /// gating findings on this would mute real results project-wide instead of
    /// just the affected file.
    SourceParseDegraded {
        /// Number of parser diagnostics reported for the file.
        error_count: u32,
        /// `true` when the parser abandoned the file instead of recovering, so
        /// the extracted module is a fragment at best.
        panicked: bool,
    },
    /// Dependency-override resolution was skipped because bun's legacy binary
    /// `bun.lockb` sits next to this `package.json`, fallow cannot read the
    /// binary format, and no parseable text lockfile was found to use
    /// instead: no `bun.lock` that parses, and no readable `pnpm-lock.yaml`,
    /// `package-lock.json`, or `npm-shrinkwrap.json`. A `yarn.lock` is never
    /// consulted (yarn ignores `overrides`), so it does not prevent the skip
    /// either. The manifest declares overrides, so the
    /// `unused-dependency-overrides` check would otherwise have run; without
    /// resolution ground truth it would flag every transitive-only pin, so no
    /// unused-override findings are reported at all (issue #2358). Surfaced
    /// by the override analysis, not workspace discovery, but shares this
    /// channel so the skip is visible in `workspace_diagnostics[]` JSON and
    /// as a stderr warning.
    BunLockbOverrideResolutionSkipped,
    /// Dependency-override resolution was skipped because bun's text
    /// `bun.lock` exists but could not be parsed and no readable pnpm or npm
    /// lockfile was available as independent resolution ground truth.
    BunLockOverrideResolutionSkipped,
    /// A bun manifest declares both `overrides` and a non-empty `resolutions`
    /// object. Bun applies `overrides` and ignores `resolutions`, so fallow
    /// reports the shadowed configuration without offering removal advice.
    BunResolutionsShadowedByOverrides,
    /// The project has no `node_modules` directory and is not a Deno project
    /// that legitimately runs without one. Analysis proceeds, but three things
    /// degrade silently: package `exports` and conditional exports cannot be
    /// read, so imports into a dependency's subpaths resolve less precisely;
    /// framework plugins that activate on an installed package stay inactive,
    /// so their entry points and path aliases are missing; and a dependency's
    /// installed shape cannot be inspected, so type-only dependency
    /// classification falls back to declaration-based heuristics.
    ///
    /// Recorded once per run by the source walk, anchored at the missing
    /// `node_modules` directory so the reported path is a real location rather
    /// than the empty string a root-anchored diagnostic would render. This used
    /// to be a bare `tracing::warn!` duplicated in two pipelines, so it never
    /// reached JSON output and never reached `fallow doctor`, which reported
    /// `pass` on a tree that had never been installed.
    NodeModulesMissing,
    /// `boundaries` is empty while `boundary-violation` is not `off`, so the
    /// boundary detector never ran. Its summary counters are therefore
    /// structurally zero and say nothing about the project.
    ///
    /// This is the UNCONFIGURED zero, not the user-chosen one: a project that
    /// sets `boundary-violation: off` asked for silence and can see that
    /// choice in `fallow config`. A project that left `boundaries` empty
    /// cannot distinguish "no violations" from "nothing was measured".
    BoundariesNotConfigured,
    /// `rulePacks` is empty while `policy-violation` is not `off`, so the
    /// policy detector never ran and its summary counters are structurally
    /// zero. The unconfigured counterpart of
    /// [`Self::BoundariesNotConfigured`].
    RulePacksNotConfigured,
    /// One of fallow's built-in discovery ignore patterns (`**/dist/**`,
    /// `**/build/**`, `**/coverage/**`, and the four minified-bundle globs)
    /// removed at least one candidate source file from this walk. The files
    /// are never read, so their imports and exports are invisible to every
    /// analysis, and until issue #2638 the drop was completely silent:
    /// pointing fallow at a directory a built-in pattern matches returned a
    /// clean report with exit 0 and nothing said why.
    ///
    /// `**/node_modules/**` is carved out and never appears in `pattern`:
    /// installed dependencies are not the first-party source this diagnostic
    /// is about, and a project that does not gitignore them would get a
    /// five-figure count with no useful remedy. `**/.git/**` cannot fire,
    /// because hidden directories are not traversed.
    ///
    /// One entry per pattern, never per file or per directory, so the array
    /// grows by at most the number of built-in patterns on a project of any
    /// size. `path` anchors at the matched directory holding the most excluded
    /// files for that pattern, ties broken by the lexicographically first
    /// path, so two runs on one tree report the same location. On a nested
    /// match it is the DEEPEST segment the pattern matched
    /// (`build/tools/build`, not `build`), because that is the directory the
    /// `--root` remedy names and re-rooting at a shallower one would leave a
    /// matching segment behind. That directory is the
    /// largest group and not a majority: a flat monorepo can spread ten
    /// excluded files over ten sibling `dist/` directories and every one of
    /// them is then "the largest". `file_count` spans all of them, and
    /// `directory_count` says how many there were, so a reader can tell a
    /// single tree from a scattered one without a directory list in the
    /// payload.
    ///
    /// Three properties of the population are load-bearing and easy to
    /// misread:
    ///
    /// - **Gitignored trees count zero.** Source discovery honors
    ///   `.gitignore`, `.git/info/exclude`, and the global gitignore, and
    ///   prunes those directories before this check runs. The honest reading
    ///   is "candidate source files git did not already hide and a built-in
    ///   pattern then dropped", which is why a repository that gitignores its
    ///   own `dist/` never sees this diagnostic.
    /// - **A user `ignorePatterns` entry is not a surprise.** The compiled
    ///   ignore set is the union of `ignorePatterns` and the built-ins, so a
    ///   file both matched was an explicit project choice and is attributed to
    ///   no pattern here. The union also only ever adds: `ignorePatterns`
    ///   cannot negate a built-in, so a config edit is never the remedy.
    /// - **The remedy depends on the pattern's shape.** A directory-shaped
    ///   built-in (`**/dist/**`) is matched against the path relative to the
    ///   run root, so re-rooting inside the matched directory removes the
    ///   matched segment and the files become visible: the message advertises
    ///   `fallow --root <dir>`. A file-shaped built-in (`**/*.min.js` and the
    ///   three other bundle globs) matches on the file name and keeps matching
    ///   at any root, so the message says so and points at renaming instead of
    ///   handing out a command that provably does nothing.
    ///
    /// Deliberately NOT one of the [`Self::source_never_analyzed`] kinds. These
    /// exclusions are the product's designed behavior on generated output, not
    /// a degraded run: answering `true` would attach `IncompleteFileAnalysis`
    /// and `IncompleteImportGraph` caveats to findings on nearly every project
    /// that keeps a non-gitignored `dist/` or `coverage/`, and make `fallow
    /// fix` withhold `delete-file` and `remove-export` actions project-wide.
    ExcludedByDefaultIgnore {
        /// The built-in glob that matched, verbatim (for example
        /// `**/build/**`).
        pattern: String,
        /// Candidate source files this pattern excluded in this walk, across
        /// every directory it matched, not just the one `path` anchors at.
        /// Exact: the walk counts each excluded candidate once.
        file_count: u32,
        /// Distinct directories this pattern matched at, `path` included, and
        /// not the number of directories that held the files. A
        /// directory-shaped pattern (`**/dist/**`) matches at the directory it
        /// names, so an excluded subtree counts once however many nested
        /// directories inside it held source: a `dist/` holding files in three
        /// sub-directories reports `1`. A file-shaped pattern (`**/*.min.js`)
        /// has no directory to collapse to and counts each matched file's own
        /// parent. Exact either way, and anything above `1` says `path` names
        /// one matched location out of several.
        directory_count: u32,
    },
    /// The walk finished with no source file to analyze at all, so every
    /// finding count this run reports is zero because nothing was measured
    /// rather than because the project is clean (issue #2686).
    ///
    /// Distinct from [`Self::ExcludedByDefaultIgnore`], which reports one
    /// pattern's exclusions and is designed behavior on generated output. The
    /// alarm is not the exclusion, it is having nothing left afterwards, and
    /// that condition also fires with no exclusion at all: a docs-only
    /// repository, a workspace member with no TypeScript, or a path filter that
    /// matched nothing. `excluded_file_count` names the built-in-ignore
    /// contribution so the common cause is still attributable, and is `0` when
    /// no built-in pattern took part.
    ///
    /// This is the kind a CI consumer reads to tell "measured zero" from
    /// "measured nothing": the human report has said so since 3.26.0, but only
    /// in human format and only under the built-in-ignore cause, so `--quiet
    /// --format json` saw a clean green either way.
    NoSourceFilesAnalyzed {
        /// Candidate source files the built-in ignore patterns removed from
        /// this walk, summed across every pattern. `0` when the walk found no
        /// candidate to exclude in the first place.
        excluded_file_count: u32,
    },
    /// Per-file health scoring failed, so the score list is empty and the
    /// scored-file count is `0` because nothing was measured rather than
    /// because the project has no files worth scoring. Every score-derived
    /// number (the average maintainability index, the refactoring targets, the
    /// hotspot complexity half) is then structurally zero (issue #2689).
    FileScoresUnavailable {
        /// Scoring error text.
        error: String,
    },
    /// Churn-based hotspot analysis was skipped, so the hotspots, churn and
    /// ownership sections report nothing at all. The remaining health sections
    /// are unaffected.
    HotspotsSkipped {
        /// Which input stopped it, as a kebab-case token: `not-a-repository`,
        /// `no-commits`, `invalid-since` or `churn-file-unreadable`. The set is
        /// open.
        ///
        /// The cause decides the remedy, which is why it is on the wire: a run
        /// outside a repository is fixed by running fallow inside one, a
        /// branch without a commit by committing, a malformed `--since` by
        /// respelling the flag, and a churn file that changed under the run by
        /// rerunning it. A consumer reading only the kind would offer the first
        /// remedy for all four.
        cause: String,
    },
    /// The repository is a shallow clone, so churn is measured over the fetched
    /// history only and every hotspot figure is incomplete.
    ShallowClone {
        /// `true` when the run also asked for ownership attribution, which a
        /// shallow clone skews further by inflating single-author dominance.
        ownership_requested: bool,
    },
    /// No commit timestamp was available, so churn recency and ownership
    /// staleness were measured against the wall clock and drift between two
    /// runs over the same commit.
    UnpinnedClock,
    /// Ownership attribution was requested but its inputs did not load, so
    /// hotspot entries carry degraded or absent owner signals.
    OwnershipUnavailable {
        /// Which input failed, as a kebab-case token: `invalid-bot-pattern` or
        /// `codeowners-parse-failed`. The set is open.
        cause: String,
        /// Underlying error text.
        error: String,
    },
    /// A saved health snapshot could not be read or parsed, so the trend is
    /// computed over fewer snapshots than the project has on disk and a
    /// direction can flip on the missing point alone.
    TrendSnapshotUnreadable {
        /// Filesystem or JSON error text.
        error: String,
    },
    /// A framework plugin read a build config and could not read one of its
    /// keys in full, so part of what the key declares never reached the
    /// analysis. `path` names the config file.
    ///
    /// The reader is syntactic, so a key whose value is computed at build time
    /// is invisible to it: a Module Federation `exposes: makeExposes()` or a
    /// `remotes` map spread from an environment module declares entries this
    /// run does not know about. The consequence is a finding, not a missing
    /// number: an unread `exposes` target is not registered as an entry point
    /// and its file can surface as `unused-file`, and an unread `remotes` alias
    /// is not treated as provided by a remote container and its import can
    /// surface as an unlisted dependency.
    ///
    /// Recorded by the plugin stage, which runs before analysis and is not
    /// cached, so the entry is present on a warm cache too. It used to be a
    /// bare `tracing::warn!` from inside the plugin, so it reached no envelope
    /// and no CI consumer (issue #2736).
    ///
    /// A source file that calls the Module Federation runtime API gets the same
    /// entry: `path` names the source file, `key` names the runtime function
    /// (`registerRemotes`, `loadRemote`, `init`, `createInstance`) and
    /// `reason` is `dynamic-argument` when the call receives a value that is
    /// not a static literal. The analysis records it from the facts of the
    /// parse, which a warm cache restores (issue #2795). A `.vue` or `.svelte`
    /// file gets it for a call in its `<script>` blocks (issue #2876).
    PluginConfigUnreadable {
        /// The plugin that read the config, as it labels itself:
        /// `module-federation` for a standalone `module-federation.config.*`,
        /// or the bundler plugin (`webpack`, `rspack`, `rsbuild`, `vite`) that
        /// read the same options inline from its own config.
        plugin: String,
        /// The config key that was present and not fully readable (`exposes`,
        /// `remotes`), or the Module Federation runtime function whose
        /// argument was not readable (`registerRemotes`, `loadRemote`, `init`,
        /// `createInstance`). The set is open.
        key: String,
        /// Why it could not be read, as a kebab-case token:
        /// `not-object-literal`, `array-form`, `spread`,
        /// `unreadable-entries`, `unrecognized-call`,
        /// `import-target-unreadable` or `dynamic-argument`. The set is open.
        ///
        /// The reason decides the remedy, which is why it is on the wire: a
        /// value that is not an object literal is fixed by writing one, while
        /// unreadable entries are fixed by naming those entries in the config
        /// option the message points at.
        reason: String,
    },
    /// A framework plugin read a config key it understands, does not model
    /// that key's effect, and therefore stood a modeled default down. `path`
    /// names the config file.
    ///
    /// A file can also be the `path`: a Nuxt file that reads `#components` or
    /// `#imports` in a way fallow cannot narrow to names, such as a spread of
    /// a namespace import, has `key` set to that module and `reason` set to
    /// `key-effect-not-modeled`. Every name of the module then counts as used.
    ///
    /// The Nuxt auto-import gate is the case this exists for. With
    /// `autoImports` enabled fallow drops the Nuxt convention entry patterns
    /// so a genuinely unreferenced convention file is reported, and a
    /// `components:` or `imports:` block whose effect it cannot model keeps
    /// them, which silently costs the user the findings they opted in for.
    ///
    /// Deliberately NOT one of the [`Self::warns_on_stderr`] kinds. Nothing
    /// was lost that the run could have measured: the patterns stayed, so
    /// findings are suppressed rather than invented, and a project in this
    /// state would otherwise warn on every run forever with "write different
    /// config" as the only remedy, which is the reason
    /// `boundaries-not-configured` is off stderr as well.
    PluginEffectNotModeled {
        /// The plugin that read the config, as it labels itself (`nuxt`).
        plugin: String,
        /// The config key whose effect is not modeled (`components`,
        /// `imports`), or the virtual module a file reads (`#components`,
        /// `#imports`). The set is open.
        key: String,
        /// Why the effect is not modeled, as a kebab-case token:
        /// `key-effect-not-modeled` when the key's own value is the reason,
        /// `config-property-unreadable` when a top-level property of the same
        /// config file could not be read statically, so no surface in it can
        /// be classified at all. The set is open.
        reason: String,
    },
    /// Test coverage was auto-detected on disk rather than passed with
    /// `--coverage`, and `path` names the file that fed the CRAP scores.
    ///
    /// Deliberately NOT one of the [`Self::warns_on_stderr`] kinds: nothing
    /// degraded, the run measured exactly what it found. It is provenance, and
    /// it is on the wire because a score computed against a file the user did
    /// not name is not reproducible and nothing else says which file it was.
    CoverageAutoDetected,
}

impl WorkspaceDiagnosticKind {
    /// Stable kebab-case identifier used in dedupe keys and tracing payloads.
    #[must_use]
    pub const fn id(&self) -> &'static str {
        match self {
            Self::UndeclaredWorkspace => "undeclared-workspace",
            Self::MalformedPackageJson { .. } => "malformed-package-json",
            Self::GlobMatchedNoPackageJson { .. } => "glob-matched-no-package-json",
            Self::MalformedTsconfig { .. } => "malformed-tsconfig",
            Self::TsconfigReferenceDirMissing => "tsconfig-reference-dir-missing",
            Self::MalformedPnpmWorkspaceYaml { .. } => "malformed-pnpm-workspace-yaml",
            Self::SkippedLargeFile { .. } => "skipped-large-file",
            Self::SkippedMinifiedFile { .. } => "skipped-minified-file",
            Self::SkippedSourceDotdir => "skipped-source-dotdir",
            Self::SourceReadFailure { .. } => "source-read-failure",
            Self::SourceParseDegraded { .. } => "source-parse-degraded",
            Self::BunLockbOverrideResolutionSkipped => "bun-lockb-override-resolution-skipped",
            Self::BunLockOverrideResolutionSkipped => "bun-lock-override-resolution-skipped",
            Self::BunResolutionsShadowedByOverrides => "bun-resolutions-shadowed-by-overrides",
            Self::NodeModulesMissing => "node-modules-missing",
            Self::BoundariesNotConfigured => "boundaries-not-configured",
            Self::RulePacksNotConfigured => "rule-packs-not-configured",
            Self::ExcludedByDefaultIgnore { .. } => "excluded-by-default-ignore",
            Self::NoSourceFilesAnalyzed { .. } => "no-source-files-analyzed",
            Self::FileScoresUnavailable { .. } => "file-scores-unavailable",
            Self::HotspotsSkipped { .. } => "hotspots-skipped",
            Self::ShallowClone { .. } => "shallow-clone",
            Self::UnpinnedClock => "unpinned-clock",
            Self::OwnershipUnavailable { .. } => "ownership-unavailable",
            Self::TrendSnapshotUnreadable { .. } => "trend-snapshot-unreadable",
            Self::PluginConfigUnreadable { .. } => "plugin-config-unreadable",
            Self::PluginEffectNotModeled { .. } => "plugin-effect-not-modeled",
            Self::CoverageAutoDetected => "coverage-auto-detected",
        }
    }

    /// Whether this diagnostic is worth a `tracing::warn!` line on stderr, on
    /// top of its permanent entry in `workspace_diagnostics[]`.
    ///
    /// A warning is for a run whose RESULTS are degraded: something the user
    /// installed, wrote, or expected did not reach the analysis. The two
    /// unconfigured-check kinds are not that. They fire in the product's
    /// default state, on every project that never opted into boundaries or
    /// rule packs, and they will keep firing forever, because the remedy they
    /// offer is to write configuration in order to silence a warning about not
    /// having written configuration. They stay in the structured array, where a
    /// consumer that wants to distinguish "measured zero" from "measured
    /// nothing" can read them, and off the stderr surface that every other
    /// command shares.
    ///
    /// `coverage-auto-detected` answers false for a third reason: it reports
    /// the provenance of an input that DID load, so a consumer sentence about a
    /// degraded run would state something untrue about it. Its own note is
    /// printed by the health pipeline.
    ///
    /// `plugin-effect-not-modeled` answers false for the first reason: the
    /// config was readable and nothing the run could have measured was lost,
    /// so it would warn forever on a project whose `nuxt.config` fallow does
    /// not model. Its sibling `plugin-config-unreadable` answers true, because
    /// there a declaration the user wrote did not reach the analysis and
    /// findings can be wrong in either direction.
    #[must_use]
    pub const fn warns_on_stderr(&self) -> bool {
        match self {
            Self::BoundariesNotConfigured
            | Self::RulePacksNotConfigured
            | Self::ExcludedByDefaultIgnore { .. }
            | Self::PluginEffectNotModeled { .. }
            | Self::CoverageAutoDetected => false,
            Self::UndeclaredWorkspace
            | Self::MalformedPackageJson { .. }
            | Self::GlobMatchedNoPackageJson { .. }
            | Self::MalformedTsconfig { .. }
            | Self::TsconfigReferenceDirMissing
            | Self::MalformedPnpmWorkspaceYaml { .. }
            | Self::SkippedLargeFile { .. }
            | Self::SkippedMinifiedFile { .. }
            | Self::SkippedSourceDotdir
            | Self::SourceReadFailure { .. }
            | Self::SourceParseDegraded { .. }
            | Self::BunLockbOverrideResolutionSkipped
            | Self::BunLockOverrideResolutionSkipped
            | Self::BunResolutionsShadowedByOverrides
            | Self::NodeModulesMissing
            | Self::NoSourceFilesAnalyzed { .. }
            | Self::FileScoresUnavailable { .. }
            | Self::HotspotsSkipped { .. }
            | Self::ShallowClone { .. }
            | Self::UnpinnedClock
            | Self::OwnershipUnavailable { .. }
            | Self::TrendSnapshotUnreadable { .. }
            | Self::PluginConfigUnreadable { .. } => true,
        }
    }

    /// Whether this diagnostic is produced by SOURCE discovery (the file walk in
    /// `discover_files`) rather than WORKSPACE discovery (config load). Source-
    /// discovery diagnostics are APPENDED to the registry after config load, so
    /// `stash_workspace_diagnostics` must preserve them when it replaces the
    /// workspace-discovery set, otherwise the per-analysis config re-loads in
    /// combined-mode (`fallow` with no subcommand re-loads config for check,
    /// dupes, and health) wipe them before the JSON envelope is built (issue
    /// #1086).
    #[must_use]
    pub const fn is_source_discovery(&self) -> bool {
        matches!(
            self,
            Self::SkippedLargeFile { .. }
                | Self::SkippedMinifiedFile { .. }
                | Self::SkippedSourceDotdir
                | Self::SourceReadFailure { .. }
                | Self::SourceParseDegraded { .. }
                | Self::NodeModulesMissing
                | Self::ExcludedByDefaultIgnore { .. }
                | Self::NoSourceFilesAnalyzed { .. }
        )
    }

    /// Whether this diagnostic is written by the source file WALK
    /// (`discover_files`), the subset of [`Self::is_source_discovery`] that a
    /// walk replaces wholesale for its root. `source-read-failure` is the
    /// other source-discovery kind and is NOT one of these: the parse stage
    /// records it after the walk, so it has to keep reaching consumers through
    /// the registry.
    ///
    /// A walk-recorded entry must reach an analysis from its OWN walk's return
    /// value. Combined mode runs the dead-code and duplication walks under
    /// `rayon::join` whenever a per-analysis `production` split stops them from
    /// sharing a file list, so a registry read answers "whichever walk wrote
    /// last" and varies between runs of the same command (issue #2366).
    #[must_use]
    pub const fn is_source_walk_recorded(&self) -> bool {
        matches!(
            self,
            Self::SkippedLargeFile { .. }
                | Self::SkippedMinifiedFile { .. }
                | Self::SkippedSourceDotdir
                | Self::NodeModulesMissing
                | Self::ExcludedByDefaultIgnore { .. }
                | Self::NoSourceFilesAnalyzed { .. }
        )
    }

    /// Whether this diagnostic reports a source file whose contents this run
    /// never analyzed, so every import and export the file holds is invisible
    /// to the module graph.
    ///
    /// This is the class `reachability_caveats[]` exists for. A file the run
    /// never read credits nothing, so the modules it imports surface as
    /// confident `unused-file` and `unused-export` findings carrying
    /// `delete-file` and `remove-export` actions, and `fallow fix` would
    /// otherwise apply the removal against source that still imports the
    /// target.
    ///
    /// All four discovery-side kinds qualify, for the same reason and with the
    /// same consequence:
    ///
    /// - `skipped-large-file` and `skipped-minified-file`: the file is in the
    ///   project tree and was never opened, so its import list is unknown.
    /// - `skipped-source-dotdir`: the directory holds at least one source file
    ///   the project did not exclude, and none of them were traversed. The
    ///   diagnostic is capped, so it under-reports rather than over-reports;
    ///   its presence still proves unseen source exists.
    /// - `source-read-failure`: the file was discovered and then could not be
    ///   read, so nothing was extracted from it at all.
    ///
    /// `source-parse-degraded` is deliberately NOT one of these, though it
    /// belongs to the same family. Neither is `excluded-by-default-ignore`,
    /// for a different reason: that one reports designed behavior on generated
    /// output rather than a degraded run, and its own doc comment carries the
    /// argument.
    ///
    /// `source-parse-degraded`: that file WAS read, so it has a module and
    /// a graph node and its reachability is observable, which lets the caveat
    /// pass narrow it: a degraded module that is itself unreachable cannot
    /// change a reachability verdict. Every kind above has no node to ask (a
    /// read failure has one with nothing extracted into it), so no narrowing
    /// is available and the caveat they raise is run-level.
    ///
    /// The match is exhaustive on purpose: a new "the run did not see this
    /// file" kind has to be classified here, and answering `true` is the only
    /// wiring its findings need in order to inherit both the caveat and the
    /// `fallow fix` withholding that follows it.
    #[must_use]
    pub const fn source_never_analyzed(&self) -> bool {
        match self {
            Self::SkippedLargeFile { .. }
            | Self::SkippedMinifiedFile { .. }
            | Self::SkippedSourceDotdir
            | Self::SourceReadFailure { .. } => true,
            Self::UndeclaredWorkspace
            | Self::MalformedPackageJson { .. }
            | Self::GlobMatchedNoPackageJson { .. }
            | Self::MalformedTsconfig { .. }
            | Self::TsconfigReferenceDirMissing
            | Self::MalformedPnpmWorkspaceYaml { .. }
            | Self::SourceParseDegraded { .. }
            | Self::BunLockbOverrideResolutionSkipped
            | Self::BunLockOverrideResolutionSkipped
            | Self::BunResolutionsShadowedByOverrides
            | Self::NodeModulesMissing
            | Self::BoundariesNotConfigured
            | Self::RulePacksNotConfigured
            | Self::ExcludedByDefaultIgnore { .. }
            | Self::NoSourceFilesAnalyzed { .. }
            | Self::FileScoresUnavailable { .. }
            | Self::HotspotsSkipped { .. }
            | Self::ShallowClone { .. }
            | Self::UnpinnedClock
            | Self::OwnershipUnavailable { .. }
            | Self::TrendSnapshotUnreadable { .. }
            | Self::PluginConfigUnreadable { .. }
            | Self::PluginEffectNotModeled { .. }
            | Self::CoverageAutoDetected => false,
        }
    }

    /// Whether this diagnostic is recorded by the ANALYZE stage (the
    /// dependency-catalog and override detectors) rather than by workspace or
    /// source discovery. Analysis-stage diagnostics reach the registry through
    /// `record_workspace_diagnostics` after config load, so
    /// `stash_workspace_diagnostics` must preserve them across combined-mode's
    /// per-analysis config re-loads, and every analyze pass clears its previous
    /// entries before re-recording so a fixed cause drops out on the next run
    /// (issue #2366). The match is exhaustive on purpose: a new kind must be
    /// classified here before it compiles.
    ///
    /// Classify a kind `true` ONLY when a detector reachable from the dead-code
    /// analyze pass (`find_dead_code_full`) re-records it, because that pass is
    /// the single clear site. A kind recorded exclusively by another stage would
    /// be cleared by the next dead-code pass and never come back.
    #[must_use]
    pub const fn is_analysis_stage(&self) -> bool {
        match self {
            Self::MalformedPnpmWorkspaceYaml { .. }
            | Self::BunLockbOverrideResolutionSkipped
            | Self::BunLockOverrideResolutionSkipped
            | Self::BunResolutionsShadowedByOverrides
            | Self::BoundariesNotConfigured
            | Self::RulePacksNotConfigured => true,
            Self::UndeclaredWorkspace
            | Self::MalformedPackageJson { .. }
            | Self::GlobMatchedNoPackageJson { .. }
            | Self::MalformedTsconfig { .. }
            | Self::TsconfigReferenceDirMissing
            | Self::SkippedLargeFile { .. }
            | Self::SkippedMinifiedFile { .. }
            | Self::SkippedSourceDotdir
            | Self::SourceReadFailure { .. }
            | Self::SourceParseDegraded { .. }
            | Self::NodeModulesMissing
            | Self::ExcludedByDefaultIgnore { .. }
            | Self::NoSourceFilesAnalyzed { .. }
            | Self::FileScoresUnavailable { .. }
            | Self::HotspotsSkipped { .. }
            | Self::ShallowClone { .. }
            | Self::UnpinnedClock
            | Self::OwnershipUnavailable { .. }
            | Self::TrendSnapshotUnreadable { .. }
            | Self::PluginConfigUnreadable { .. }
            | Self::PluginEffectNotModeled { .. }
            | Self::CoverageAutoDetected => false,
        }
    }

    /// Whether this diagnostic is recorded by the HEALTH pipeline (scoring,
    /// churn, ownership, trend, coverage input resolution) rather than by
    /// workspace discovery, source discovery or the analyze stage.
    ///
    /// Health-stage diagnostics are appended to the registry after config
    /// load, so `stash_workspace_diagnostics` must preserve them across
    /// combined mode's per-analysis config re-loads, and the health run clears
    /// its previous entries before re-recording so a fixed CODEOWNERS drops out
    /// on the next run (issue #2689).
    ///
    /// They are deliberately NOT [`Self::is_analysis_stage`], although they
    /// share both of those properties. That predicate additionally means "the
    /// dead-code analyze pass re-records this", and the pass clears every kind
    /// answering it on entry. Health computes file scores by running that same
    /// pass, so a health-stage kind classified there would be wiped mid-run by
    /// the analysis it is reporting on.
    #[must_use]
    pub const fn is_health_stage(&self) -> bool {
        match self {
            Self::FileScoresUnavailable { .. }
            | Self::HotspotsSkipped { .. }
            | Self::ShallowClone { .. }
            | Self::UnpinnedClock
            | Self::OwnershipUnavailable { .. }
            | Self::TrendSnapshotUnreadable { .. }
            | Self::CoverageAutoDetected => true,
            Self::UndeclaredWorkspace
            | Self::MalformedPackageJson { .. }
            | Self::GlobMatchedNoPackageJson { .. }
            | Self::MalformedTsconfig { .. }
            | Self::TsconfigReferenceDirMissing
            | Self::MalformedPnpmWorkspaceYaml { .. }
            | Self::SkippedLargeFile { .. }
            | Self::SkippedMinifiedFile { .. }
            | Self::SkippedSourceDotdir
            | Self::SourceReadFailure { .. }
            | Self::SourceParseDegraded { .. }
            | Self::BunLockbOverrideResolutionSkipped
            | Self::BunLockOverrideResolutionSkipped
            | Self::BunResolutionsShadowedByOverrides
            | Self::NodeModulesMissing
            | Self::BoundariesNotConfigured
            | Self::RulePacksNotConfigured
            | Self::ExcludedByDefaultIgnore { .. }
            | Self::PluginConfigUnreadable { .. }
            | Self::PluginEffectNotModeled { .. }
            | Self::NoSourceFilesAnalyzed { .. } => false,
        }
    }

    /// Whether this diagnostic is recorded by the PLUGIN stage (framework
    /// plugins reading their own build configs) rather than by workspace
    /// discovery, source discovery, the analyze stage or the health pipeline.
    ///
    /// Plugin-stage diagnostics are recorded after config load, so
    /// `stash_workspace_diagnostics` must preserve them across combined mode's
    /// per-analysis config re-loads, and each plugin run replaces the previous
    /// run's set so a fixed config drops out on the next run (issue #2736).
    ///
    /// They are deliberately NOT [`Self::is_analysis_stage`], although they
    /// share both of those properties. That predicate additionally means "the
    /// dead-code analyze pass re-records this", and the pass clears every kind
    /// answering it on entry. Plugins run in the prelude of that same pass, so
    /// a plugin-stage kind classified there would be wiped inside the run that
    /// produced it.
    ///
    /// The match is exhaustive on purpose: a new kind must be classified here
    /// before it compiles.
    #[must_use]
    pub const fn is_plugin_stage(&self) -> bool {
        match self {
            Self::PluginConfigUnreadable { .. } | Self::PluginEffectNotModeled { .. } => true,
            Self::UndeclaredWorkspace
            | Self::MalformedPackageJson { .. }
            | Self::GlobMatchedNoPackageJson { .. }
            | Self::MalformedTsconfig { .. }
            | Self::TsconfigReferenceDirMissing
            | Self::MalformedPnpmWorkspaceYaml { .. }
            | Self::SkippedLargeFile { .. }
            | Self::SkippedMinifiedFile { .. }
            | Self::SkippedSourceDotdir
            | Self::SourceReadFailure { .. }
            | Self::SourceParseDegraded { .. }
            | Self::BunLockbOverrideResolutionSkipped
            | Self::BunLockOverrideResolutionSkipped
            | Self::BunResolutionsShadowedByOverrides
            | Self::NodeModulesMissing
            | Self::BoundariesNotConfigured
            | Self::RulePacksNotConfigured
            | Self::ExcludedByDefaultIgnore { .. }
            | Self::NoSourceFilesAnalyzed { .. }
            | Self::FileScoresUnavailable { .. }
            | Self::HotspotsSkipped { .. }
            | Self::ShallowClone { .. }
            | Self::UnpinnedClock
            | Self::OwnershipUnavailable { .. }
            | Self::TrendSnapshotUnreadable { .. }
            | Self::CoverageAutoDetected => false,
        }
    }
}

/// Render a byte count as a megabyte figure with one decimal place for
/// human-readable diagnostic messages (e.g. `12.3 MB`).
#[must_use]
fn format_size_mb(bytes: u64) -> String {
    #[expect(
        clippy::cast_precision_loss,
        reason = "display-only size figure; precision loss past 2^53 bytes is irrelevant"
    )]
    let mb = bytes as f64 / (1024.0 * 1024.0);
    format!("{mb:.1} MB")
}

/// A diagnostic about a workspace-discovery candidate.
///
/// The `message` field is a human-readable rendering derived from `kind`. It
/// always ends with a concrete next step ("fix the JSON syntax", "remove from
/// `workspaces`", "add to `ignorePatterns`") so first-time users have a path
/// forward.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct WorkspaceDiagnostic {
    /// Path to the directory or file that triggered the diagnostic.
    #[serde(serialize_with = "serde_path::serialize")]
    pub path: PathBuf,
    /// Kind discriminator with the typed payload.
    #[serde(flatten)]
    pub kind: WorkspaceDiagnosticKind,
    /// Human-readable rendering derived from `kind` + `path`. Always ends
    /// with a next-step hint.
    pub message: String,
    /// True when this diagnostic reports a run whose RESULTS are degraded:
    /// something the user installed, wrote, or expected did not reach the
    /// analysis. Projected from [`WorkspaceDiagnosticKind::warns_on_stderr`],
    /// which is the same classification that decides whether the CLI prints a
    /// stderr line, so a CI log built from this field and a local non-quiet run
    /// say the same thing.
    ///
    /// Omitted when false, which is what keeps every clean run byte-identical.
    /// The two unconfigured-check kinds answer false on purpose: they fire in
    /// the product's default state on every project that never opted into
    /// boundaries or rule packs, so warning on them would warn forever. So does
    /// `excluded-by-default-ignore`, which is designed behavior on generated
    /// output; the alarm for that case is `no-source-files-analyzed`.
    ///
    /// Read this instead of hardcoding a kind allowlist: a degrading kind added
    /// in a later release then reaches an unchanged consumer.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub degrades_analysis: bool,
}

impl WorkspaceDiagnostic {
    /// Construct a diagnostic with the message rendered from `kind` + `path`.
    ///
    /// `root` is used to produce project-relative paths in the message text
    /// AND inside the variant payload (e.g. the `error` field of
    /// `MalformedPackageJson` / `MalformedTsconfig` which embed the absolute
    /// file path from `PackageJson::load()`'s error text). Without the
    /// payload-side normalisation the embedded path would survive
    /// environment-specific differences (CI vs Docker vs local) because the
    /// post-serialisation `strip_root_prefix` only catches whole-string
    /// matches, not paths embedded mid-sentence.
    ///
    /// If `path` is not under `root` (e.g. canonicalisation crossed a
    /// symlink), the absolute path is emitted instead.
    ///
    /// `path` also loses any no-op `.` component, for the same reason the
    /// payload loses a glob's `./` prefix: one directory reached through two
    /// spellings of one glob must be one diagnostic.
    #[must_use]
    pub fn new(root: &Path, path: PathBuf, kind: WorkspaceDiagnosticKind) -> Self {
        let path = normalise_diagnostic_path(path);
        let kind = normalise_payload_paths(root, kind);
        let message = render_message(root, &path, &kind);
        let degrades_analysis = kind.warns_on_stderr();
        Self {
            path,
            kind,
            message,
            degrades_analysis,
        }
    }

    /// Return this diagnostic with `path` rewritten relative to `root`.
    ///
    /// `path` is stored absolute so callers can act on it. Every JSON envelope
    /// emits it project-relative instead: the analysis envelopes get there
    /// through the post-serialisation `strip_root_prefix` pass, which the
    /// `fallow workspaces` / `fallow list --workspaces` envelope and the MCP
    /// `project_info` tool never run, so those emitted the absolute path while
    /// the sibling `workspaces[].path` next to it was relative. They normalise
    /// at the typed layer with this method instead.
    ///
    /// Paths outside `root` (canonicalisation crossed a symlink) are left
    /// absolute, matching how [`Self::new`] renders the message.
    ///
    /// A diagnostic anchored at the root itself becomes `.`, not the empty
    /// path: an empty string is not a location, and the analysis envelopes'
    /// post-serialisation strip only removes a `root + separator` prefix, so a
    /// root-anchored path that stays absolute here leaks a host path.
    #[must_use]
    pub fn into_root_relative(mut self, root: &Path) -> Self {
        if let Ok(relative) = self.path.strip_prefix(root) {
            self.path = if relative.as_os_str().is_empty() {
                PathBuf::from(".")
            } else {
                relative.to_path_buf()
            };
        }
        self
    }
}

/// Rebuild `path` from its components so one directory has one spelling.
///
/// The dedupe key was never the problem: [`Path`] equality already ignores an
/// interior `.`, so `<root>/./pkgs/aaa` and `<root>/pkgs/aaa` are one key. The
/// stored bytes were. A workspace glob spelled `./pkgs/*` in `package.json`
/// expands to the first spelling and the same glob spelled `pkgs/*` in
/// `pnpm-workspace.yaml` expands to the second, and the two envelope families
/// make a project-relative path differently: the analysis envelopes strip the
/// root as a string (leaving `./pkgs/aaa`) while the workspace listing
/// envelope uses [`WorkspaceDiagnostic::into_root_relative`] (leaving
/// `pkgs/aaa`). Whichever
/// manifest happened to be read first then decided which shape every consumer
/// saw. Collapsing at construction gives them one answer (issue #2366).
///
/// A path that is already component-clean rebuilds to itself. Serialization
/// normalises separators, so the rebuild is wire-invisible on Windows.
fn normalise_diagnostic_path(path: PathBuf) -> PathBuf {
    let rebuilt: PathBuf = path.components().collect();
    if rebuilt.as_os_str() == path.as_os_str() {
        path
    } else {
        rebuilt
    }
}

/// Strip the project root from absolute paths embedded inside variant
/// payloads (the `error` field of malformed-config and source-read failures),
/// and drop a glob pattern's no-op `./` prefix.
///
/// Mirrors the per-platform `display()` byte sequence so the substring match
/// works on Windows too.
///
/// The pattern prefix matters because the payload is part of the dedupe key in
/// [`merge_workspace_diagnostics`]. A repository whose `package.json` declares
/// `"./apps/**"` and whose `pnpm-workspace.yaml` declares `apps/**` names one
/// glob twice, and without this both spellings would report every package-less
/// directory under `apps/` a second time (issue #2366).
fn normalise_payload_paths(root: &Path, kind: WorkspaceDiagnosticKind) -> WorkspaceDiagnosticKind {
    let root_str = root.display().to_string();
    let root_alt = root_str.replace('\\', "/");
    let normalise = |text: String| -> String {
        let stripped = text
            .replace(&format!("{root_str}/"), "")
            .replace(&format!("{root_alt}/"), "");
        stripped
            .replace(&format!("{root_str}\\"), "")
            .replace(&format!("{root_alt}\\"), "")
    };
    match kind {
        WorkspaceDiagnosticKind::MalformedPackageJson { error } => {
            WorkspaceDiagnosticKind::MalformedPackageJson {
                error: normalise(error),
            }
        }
        WorkspaceDiagnosticKind::MalformedTsconfig { error } => {
            WorkspaceDiagnosticKind::MalformedTsconfig {
                error: normalise(error),
            }
        }
        WorkspaceDiagnosticKind::SourceReadFailure { error } => {
            WorkspaceDiagnosticKind::SourceReadFailure {
                error: normalise(error),
            }
        }
        WorkspaceDiagnosticKind::FileScoresUnavailable { error } => {
            WorkspaceDiagnosticKind::FileScoresUnavailable {
                error: normalise(error),
            }
        }
        WorkspaceDiagnosticKind::OwnershipUnavailable { cause, error } => {
            WorkspaceDiagnosticKind::OwnershipUnavailable {
                cause,
                error: normalise(error),
            }
        }
        WorkspaceDiagnosticKind::TrendSnapshotUnreadable { error } => {
            WorkspaceDiagnosticKind::TrendSnapshotUnreadable {
                error: normalise(error),
            }
        }
        WorkspaceDiagnosticKind::GlobMatchedNoPackageJson { pattern } => {
            WorkspaceDiagnosticKind::GlobMatchedNoPackageJson {
                pattern: canonical_glob_pattern(pattern),
            }
        }
        other => other,
    }
}

/// Drop the leading `./` (or `.\`) a workspace glob may carry, so the same
/// pattern declared in two manifests is one payload.
///
/// A pattern that is nothing BUT the prefix (`"./"`, the root itself) keeps
/// its spelling: stripping it would report an empty `pattern` field and an
/// empty quoted glob in the warning text, which names no glob at all.
fn canonical_glob_pattern(pattern: String) -> String {
    for prefix in ["./", ".\\"] {
        if let Some(rest) = pattern.strip_prefix(prefix)
            && !rest.is_empty()
        {
            return rest.to_owned();
        }
    }
    pattern
}

/// Concatenate two diagnostic lists, keeping the first occurrence of each
/// `(kind, path)` pair and the order of `primary` followed by the entries only
/// `secondary` has.
///
/// The single place diagnostics from two observation points are folded
/// together: an engine session's own capture plus the process registry, and
/// the combined run's per-analysis lists (issue #2366). A combined run walks
/// the project once per analysis, and per-analysis `production` modes can make
/// those walks see different file sets, so no single observation point holds
/// everything the run recorded; the union does, and folding it the same way
/// everywhere is what keeps the CLI and the programmatic route answering
/// identically.
///
/// The key is the WHOLE kind, payload included, not its
/// [`id`](WorkspaceDiagnosticKind::id). Two entries can share a kind id and a
/// path and still be two distinct diagnostics: overlapping workspace globs
/// (`["packages/*", "packages/*/*"]`) each report the same package-less
/// directory with their own `pattern`, and the standalone envelopes report
/// both. An id-keyed fold silently dropped the second one.
#[must_use]
pub fn merge_workspace_diagnostics(
    primary: Vec<WorkspaceDiagnostic>,
    secondary: Vec<WorkspaceDiagnostic>,
) -> Vec<WorkspaceDiagnostic> {
    let mut merged = Vec::with_capacity(primary.len() + secondary.len());
    let mut seen: FxHashSet<(WorkspaceDiagnosticKind, PathBuf)> = FxHashSet::default();
    for diagnostic in primary.into_iter().chain(secondary) {
        let key = (diagnostic.kind.clone(), diagnostic.path.clone());
        if seen.insert(key) {
            merged.push(diagnostic);
        }
    }
    merged
}

/// Keep the first occurrence of each `(kind, path)` pair in one list.
///
/// The single-list form of [`merge_workspace_diagnostics`], applied where
/// diagnostics are produced rather than where two observation points are
/// folded: workspace discovery reads `package.json` `workspaces`,
/// `pnpm-workspace.yaml` `packages`, `deno.json` `workspace` and the root
/// `tsconfig.json` references additively, so a repository that declares one
/// glob in two of them reports every package-less directory under it twice.
/// Deduplicating at that source is what keeps the JSON envelopes, the
/// aggregated stderr warning and the process registry telling one story
/// (issue #2366).
#[must_use]
pub fn dedupe_workspace_diagnostics(
    diagnostics: Vec<WorkspaceDiagnostic>,
) -> Vec<WorkspaceDiagnostic> {
    merge_workspace_diagnostics(diagnostics, Vec::new())
}

/// The first segment of a glob that contains no glob metacharacter, so it
/// names a real directory rather than a wildcard.
///
/// Source discovery uses it to decide which directory a built-in ignore
/// pattern excluded a file "at"; `render_message` uses it to decide which
/// remedy is true for that pattern. The two have to agree, so the function
/// lives here rather than once per crate: a pattern with such a segment
/// (`**/dist/**`) is lifted by re-rooting inside the matched directory,
/// because the glob is matched against the path relative to the run root. A
/// pattern without one (`**/*.min.js`) matches on the file name and keeps
/// matching at every root.
#[must_use]
pub fn glob_first_literal_segment(pattern: &str) -> Option<&str> {
    pattern.split('/').find(|segment| {
        !segment.is_empty()
            && !segment.contains(['*', '?', '[', ']', '{', '}'])
            && *segment != "."
            && *segment != ".."
    })
}

/// The clause naming why a plugin could not read a config key in full, for one
/// `plugin-config-unreadable` reason token.
///
/// The token set is open, so an unrecognised token renders the general claim
/// rather than nothing: a diagnostic from a plugin added later still reads as a
/// sentence.
fn unreadable_situation(reason: &str) -> &'static str {
    match reason {
        "array-form" => "uses the array form, which is not read yet",
        "spread" => "spreads a value that is not statically readable",
        "unreadable-entries" => "has entries that hold no statically readable value",
        "not-object-literal" => "is not a static object literal",
        "unrecognized-call" => "is passed through a call that is not a known config wrapper",
        "import-target-unreadable" => "comes from an imported file that is not statically readable",
        "dynamic-argument" => "receives an argument that is not a static literal",
        _ => "could not be read statically",
    }
}

/// What an unread config key costs, and the configuration option that covers
/// the gap.
///
/// Keyed on the config KEY rather than on the plugin name, because one key is
/// read by several plugins: Module Federation `exposes` and `remotes` reach a
/// build from a standalone config file and inline from the webpack, rspack,
/// rsbuild and vite configs, and both the consequence and the remedy are the
/// same in all five. A key this build does not know falls back to the general
/// claim rather than borrowing another key's remedy, so a plugin added later
/// still renders a sentence that is true.
///
/// Two reasons change the remedy. An unrecognized call was read as a lower
/// bound, so only what the call adds is missing. An unreadable import target
/// holds config that is shared across files, so the remedy names the option
/// and does not ask for an object literal.
fn unreadable_key_consequence(key: &str, reason: &str) -> (&'static str, &'static str) {
    match (key, reason) {
        ("exposes", "unrecognized-call") => (
            "only the targets in the object literal it receives are registered as entry points",
            "Name any other exposed files in `dynamicallyLoaded`.",
        ),
        ("remotes", "unrecognized-call") => (
            "only the aliases in the object literal it receives are treated as provided by a \
             remote container",
            "Name any other aliases in `ignoreDependencies`.",
        ),
        ("exposes", "import-target-unreadable") => (
            "the targets that file declares are not registered as entry points",
            "Name the exposed files in `dynamicallyLoaded`.",
        ),
        ("remotes", "import-target-unreadable") => (
            "the aliases that file declares are not treated as provided by a remote container",
            "Name the aliases in `ignoreDependencies`.",
        ),
        ("registerRemotes", _) => (
            "the remotes it registers are not treated as provided by a remote container",
            "Name the remote aliases in `ignoreDependencies`, or pass the remote names as \
             string literals.",
        ),
        ("init" | "createInstance", _) => (
            "the remotes its options declare are not treated as provided by a remote container",
            "Name the remote aliases in `ignoreDependencies`, or pass `remotes` as an array of \
             objects with literal names.",
        ),
        ("loadRemote", _) => (
            "the remote it loads is not treated as provided by a remote container",
            "Name the remote alias in `ignoreDependencies`, or pass the request as a string \
             literal.",
        ),
        ("exposes", _) => (
            "the targets are not registered as entry points",
            "Name the exposed files in `dynamicallyLoaded`.",
        ),
        ("remotes", _) => (
            "the aliases are not treated as provided by a remote container",
            "Name the aliases in `ignoreDependencies`, or declare them as the keys of an object \
             literal, whose values may be computed.",
        ),
        _ => (
            "what it declares is not fully registered",
            "Declare the value as a static object literal.",
        ),
    }
}

fn render_message(root: &Path, path: &Path, kind: &WorkspaceDiagnosticKind) -> String {
    let display = display_relative(root, path);
    match kind {
        WorkspaceDiagnosticKind::UndeclaredWorkspace => format!(
            "Directory '{display}' contains package.json but is not declared as a workspace. \
             Add it to package.json workspaces or pnpm-workspace.yaml, or add it to ignorePatterns."
        ),
        WorkspaceDiagnosticKind::MalformedPackageJson { error } => format!(
            "Dropped workspace '{display}': package.json is not valid JSON ({error}). \
             Fix the JSON syntax or remove '{display}' from the workspaces pattern."
        ),
        WorkspaceDiagnosticKind::GlobMatchedNoPackageJson { pattern } => format!(
            "Glob '{pattern}' matched '{display}' but no package.json is present. \
             Add a package.json, narrow the pattern, or add '{display}' to ignorePatterns."
        ),
        WorkspaceDiagnosticKind::MalformedTsconfig { error } => format!(
            "tsconfig.json at '{display}' failed to parse ({error}); \
             project references will be ignored. Fix the JSON syntax."
        ),
        WorkspaceDiagnosticKind::TsconfigReferenceDirMissing => format!(
            "tsconfig.json references '{display}' but the directory does not exist. \
             Update or remove the reference, or restore the missing directory."
        ),
        WorkspaceDiagnosticKind::MalformedPnpmWorkspaceYaml { error } => format!(
            "'{display}' failed to parse ({error}); catalog and override entries \
             will be ignored. Fix the YAML syntax."
        ),
        WorkspaceDiagnosticKind::SkippedLargeFile { size_bytes } => format!(
            "Skipped '{display}' ({size}): exceeds the max file size limit. \
             Its imports and exports are not analyzed. Raise the limit with \
             --max-file-size <MB> (or FALLOW_MAX_FILE_SIZE), or add '{display}' \
             to ignorePatterns.",
            size = format_size_mb(*size_bytes)
        ),
        WorkspaceDiagnosticKind::SkippedMinifiedFile { size_bytes } => format!(
            "Skipped '{display}' ({size}): appears to be minified generated JavaScript. \
             Its imports and exports are not analyzed. Add '{display}' to ignorePatterns, \
             rename it with a .min.js suffix, or use --max-file-size 0 if this file \
             should be analyzed.",
            size = format_size_mb(*size_bytes)
        ),
        WorkspaceDiagnosticKind::SkippedSourceDotdir => format!(
            "Skipped hidden directory '{display}': it contains source files but hidden \
             directories are not traversed. Its imports and exports are not analyzed. \
             A file, export or dependency that only this directory uses can be reported as \
             unused. There is no config field that adds a directory to traversal. To stop \
             that false positive, add the file to entry, the export to ignoreExports or the \
             dependency to ignoreDependencies. To silence this message, \
             add '{display}/**' to ignorePatterns. fallow --root {display} analyzes only \
             that directory on its own and does not fix this run."
        ),
        WorkspaceDiagnosticKind::SourceReadFailure { error } => format!(
            "Could not read source '{display}' ({error}). Restore the file or its read permissions, \
             ensure it contains valid UTF-8 text, or add '{display}' to ignorePatterns."
        ),
        WorkspaceDiagnosticKind::SourceParseDegraded {
            error_count,
            panicked,
        } => {
            let outcome = if *panicked {
                "the parser stopped there"
            } else {
                "the parser recovered and continued"
            };
            format!(
                "Parsed '{display}' with {error_count} error(s); {outcome}. Imports, exports, and \
                 references it did not reach are missing from this run, so files and symbols it \
                 uses can be reported as unused. Fix the syntax, or ignore this if the file uses \
                 syntax newer than fallow's parser."
            )
        }
        WorkspaceDiagnosticKind::BunLockbOverrideResolutionSkipped => format!(
            "Skipped dependency-override resolution for '{display}': bun's legacy binary bun.lockb \
             sits next to it, fallow cannot read the binary format, and no parseable text lockfile \
             (bun.lock, pnpm-lock.yaml, package-lock.json, or npm-shrinkwrap.json) was found to \
             use instead, so unused-dependency-overrides findings are not reported. Run bun install \
             --save-text-lockfile (bun 1.2 or newer) to write a text bun.lock, or delete the stale \
             bun.lockb if this repository no longer uses bun."
        ),
        WorkspaceDiagnosticKind::BunLockOverrideResolutionSkipped => format!(
            "Skipped dependency-override resolution because '{display}' could not be parsed and \
             no readable pnpm or npm lockfile was available, so unused-dependency-overrides \
             findings are not reported. Run bun install to regenerate the text lockfile, then \
             rerun fallow."
        ),
        WorkspaceDiagnosticKind::BunResolutionsShadowedByOverrides => format!(
            "'{display}' declares both `overrides` and non-empty `resolutions`; bun applies \
             `overrides` and ignores `resolutions`. Move the intended pins into `overrides` or \
             remove the shadowed `resolutions` entries."
        ),
        WorkspaceDiagnosticKind::NodeModulesMissing => format!(
            "'{display}' does not exist. Package exports and conditional exports cannot be read, \
             framework plugins that activate on an installed package stay inactive, and \
             dependency classification degrades, so imports and dependencies can be \
             misreported. Run npm install / pnpm install / yarn / bun install first."
        ),
        WorkspaceDiagnosticKind::BoundariesNotConfigured => {
            "No architecture boundaries are configured, so the boundary detector did not run and \
             its violation counts are zero because nothing was measured. Add `boundaries` to the \
             config, or set `boundary-violation` to off to state that the check is not wanted."
                .to_string()
        }
        WorkspaceDiagnosticKind::RulePacksNotConfigured => {
            "No rule packs are configured, so the policy detector did not run and its violation \
             counts are zero because nothing was measured. Add `rulePacks` to the config, or set \
             `policy-violation` to off to state that the check is not wanted."
                .to_string()
        }
        WorkspaceDiagnosticKind::NoSourceFilesAnalyzed {
            excluded_file_count,
        } => {
            if *excluded_file_count == 0 {
                "No source files were analyzed, so every finding count this run reports is zero \
                 because nothing was measured. Check the analysis root, ignorePatterns, and any \
                 path or workspace filter this run applied."
                    .to_owned()
            } else {
                format!(
                    "No source files were analyzed. Fallow's built-in ignore patterns excluded \
                     {excluded_file_count} candidate files, so every finding count this run \
                     reports is zero because nothing was measured; run with --explain-skipped \
                     for the breakdown."
                )
            }
        }
        WorkspaceDiagnosticKind::FileScoresUnavailable { error } => format!(
            "Could not compute per-file health scores ({error}), so the score list is empty and \
             the scored-file count is 0 because nothing was measured rather than because the \
             project has nothing to score. Rerun with --no-cache, or scope the run to a \
             subdirectory to find the input that fails."
        ),
        WorkspaceDiagnosticKind::HotspotsSkipped { cause } => match cause.as_str() {
            "invalid-since" => "Hotspot analysis was skipped because --since could not be read \
                 as a time window, so the hotspots, churn and ownership sections report nothing \
                 rather than zero. Spell it as a duration such as 6m or 90d, or drop it to use \
                 the default window."
                .to_owned(),
            "no-commits" => "Hotspot analysis was skipped because the current branch has no \
                 commits yet, so the hotspots, churn and ownership sections report nothing \
                 rather than zero. Commit the project to give churn a history, or pass \
                 --churn-file with exported change history."
                .to_owned(),
            "churn-file-unreadable" => format!(
                "Hotspot analysis was skipped because the churn file '{display}' could no longer \
                 be read after it was validated, so the hotspots, churn and ownership sections \
                 report nothing rather than zero. Make sure nothing rewrites the file while \
                 fallow runs, and rerun."
            ),
            // The original single cause, whose wording predates the token and
            // is kept byte-identical: a consumer matching on this sentence is
            // reading the same run it always was.
            _ => "Hotspot analysis was skipped because no git repository was found at the \
                  project root, so the hotspots, churn and ownership sections report nothing \
                  rather than zero. Run fallow inside the repository, or pass --churn-file with \
                  exported change history."
                .to_owned(),
        },
        WorkspaceDiagnosticKind::ShallowClone {
            ownership_requested,
        } => {
            let ownership = if *ownership_requested {
                " Ownership signals are skewed too, because a shallow clone inflates \
                 single-author dominance."
            } else {
                ""
            };
            format!(
                "This is a shallow clone, so churn covers only the fetched history and every \
                 hotspot figure is incomplete.{ownership} Run git fetch --unshallow for the full \
                 history."
            )
        }
        WorkspaceDiagnosticKind::UnpinnedClock => {
            "No commit timestamp was available, so churn recency and ownership staleness were \
             measured against the wall clock and drift between runs over the same commit. Set \
             FALLOW_CLOCK_EPOCH to pin the run clock."
                .to_owned()
        }
        WorkspaceDiagnosticKind::OwnershipUnavailable { cause, error } => {
            if cause == "codeowners-parse-failed" {
                format!(
                    "Ownership signals are degraded: CODEOWNERS could not be parsed ({error}), \
                     so hotspot entries carry no declared owner. Fix the CODEOWNERS syntax, or \
                     drop --ownership for this run."
                )
            } else {
                format!(
                    "Ownership signals are degraded: health.ownership.botPatterns contains an \
                     invalid glob ({error}), so no author is classified as a bot and bot commits \
                     count towards ownership. Fix the pattern, or remove it from the config."
                )
            }
        }
        WorkspaceDiagnosticKind::TrendSnapshotUnreadable { error } => format!(
            "Skipped health snapshot '{display}' ({error}), so the trend is computed over fewer \
             snapshots than this project has on disk. Delete the unreadable file, or rewrite it \
             with fallow health --save-snapshot."
        ),
        WorkspaceDiagnosticKind::CoverageAutoDetected => format!(
            "Coverage was auto-detected at '{display}' rather than passed with --coverage, so the \
             CRAP scores depend on whichever coverage file is on disk at run time. Pass --coverage \
             '{display}' explicitly for reproducible scores."
        ),
        WorkspaceDiagnosticKind::PluginConfigUnreadable {
            plugin,
            key,
            reason,
        } => {
            let (consequence, advice) = unreadable_key_consequence(key, reason);
            format!(
                "Plugin '{plugin}': `{key}` in '{display}' {situation}, so {consequence}. {advice}",
                situation = unreadable_situation(reason)
            )
        }
        WorkspaceDiagnosticKind::PluginEffectNotModeled {
            plugin,
            key,
            reason,
        } => {
            // Two causes, one effect, one remedy. Each cause gets its own
            // sentence: the cause and the effect on the findings are separate
            // facts, and one sentence with two `so` clauses states neither fact
            // clearly.
            let effect = "`autoImports` kept the convention entry patterns for that surface, and \
                          fallow reports no unused file there. Write the setting as static \
                          literals, or remove the key to use the framework defaults.";
            if key.starts_with('#') {
                format!(
                    "Plugin '{plugin}': fallow cannot read which names '{display}' takes from \
                     `{key}`, so every name of `{key}` counts as used, and fallow reports no \
                     unused file for these names. Read each name with a member access such as \
                     `C.Card`, or import it by name."
                )
            } else if reason == "config-property-unreadable" {
                format!(
                    "Plugin '{plugin}': fallow cannot read a top-level property in '{display}', so \
                     it cannot classify the `{key}` surface. {effect}"
                )
            } else {
                format!(
                    "Plugin '{plugin}': fallow does not model the effect of `{key}` in \
                     '{display}'. {effect}"
                )
            }
        }
        WorkspaceDiagnosticKind::ExcludedByDefaultIgnore {
            pattern,
            file_count,
            directory_count,
        } => {
            // `path` is a location, and an empty string is not one: a built-in
            // that matched a file sitting directly at the analysis root
            // anchors at the root itself.
            let display = if display.is_empty() {
                ".".to_owned()
            } else {
                display
            };
            // The payload carries no directory list, so the message names the
            // one directory `path` anchors at. With several excluded
            // directories that is the largest group and NOT a majority, so the
            // sentence says which claim it is making and how many directories
            // it is leaving unnamed.
            let location = if *directory_count > 1 {
                format!(
                    "Skipped {file_count} source files across {directory_count} directories, \
                     the largest group under '{display}'"
                )
            } else if *file_count == 1 {
                format!("Skipped 1 source file under '{display}'")
            } else {
                format!("Skipped {file_count} source files under '{display}'")
            };
            let singular = *file_count == 1 && *directory_count <= 1;
            let (subject, effect) = if singular {
                ("it matches", "it imports, exports, or defines")
            } else {
                ("they match", "they import, export, or define")
            };
            // Only a directory-shaped built-in is lifted by re-rooting. Telling
            // a user with a `vendor/lib.min.js` to run `fallow --root vendor`
            // hands them a command that excludes the same file again.
            let remedy = if glob_first_literal_segment(pattern).is_some() {
                format!(
                    "Move first-party source out of the matched directory, or analyze that \
                     directory on its own with fallow --root {display}."
                )
            } else {
                "This pattern matches a file name rather than a directory, so re-running under \
                 a different --root excludes the same files again. Rename first-party source \
                 that only looks generated, dropping the '.min' or '.bundle' infix."
                    .to_owned()
            };
            format!(
                "{location}: {subject} fallow's built-in ignore pattern '{pattern}', so nothing \
                 {effect} is visible to this run. Built-in ignores cannot be switched off \
                 through ignorePatterns. {remedy}"
            )
        }
    }
}

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

    #[test]
    fn skipped_large_file_diagnostic_id_and_message() {
        let root = Path::new("/project");
        let diag = WorkspaceDiagnostic::new(
            root,
            root.join("src/vendor/app.bundle.js"),
            WorkspaceDiagnosticKind::SkippedLargeFile {
                size_bytes: 6 * 1024 * 1024,
            },
        );
        assert_eq!(diag.kind.id(), "skipped-large-file");
        assert!(
            diag.message.contains("src/vendor/app.bundle.js"),
            "message names the project-relative path: {}",
            diag.message
        );
        assert!(
            diag.message.contains("6.0 MB"),
            "message reports the size: {}",
            diag.message
        );
        assert!(
            diag.message.contains("--max-file-size"),
            "message names the override flag: {}",
            diag.message
        );
    }

    #[test]
    fn skipped_minified_file_diagnostic_id_and_message() {
        let root = Path::new("/project");
        let diag = WorkspaceDiagnostic::new(
            root,
            root.join("src/assets/index-abc123.js"),
            WorkspaceDiagnosticKind::SkippedMinifiedFile {
                size_bytes: 2 * 1024 * 1024,
            },
        );
        assert_eq!(diag.kind.id(), "skipped-minified-file");
        assert!(
            diag.message.contains("src/assets/index-abc123.js"),
            "message names the project-relative path: {}",
            diag.message
        );
        assert!(
            diag.message.contains("2.0 MB"),
            "message reports the size: {}",
            diag.message
        );
        assert!(
            diag.message.contains("--max-file-size 0"),
            "message names the opt-out: {}",
            diag.message
        );
    }

    #[test]
    fn skipped_source_dotdir_diagnostic_id_and_message() {
        let root = Path::new("/project");
        let diag = WorkspaceDiagnostic::new(
            root,
            root.join(".claude"),
            WorkspaceDiagnosticKind::SkippedSourceDotdir,
        );
        assert_eq!(diag.kind.id(), "skipped-source-dotdir");
        assert!(
            diag.message.contains(".claude"),
            "message names the project-relative path: {}",
            diag.message
        );
        assert!(
            diag.message
                .contains("Its imports and exports are not analyzed."),
            "message states the consequence: {}",
            diag.message
        );
        for remedy in [
            "add the file to entry",
            "the export to ignoreExports",
            "the dependency to ignoreDependencies",
        ] {
            assert!(
                diag.message.contains(remedy),
                "message names the remedy `{remedy}`: {}",
                diag.message
            );
        }
        assert!(
            diag.message
                .contains("fallow --root .claude analyzes only that directory")
                && diag.message.contains("does not fix this run"),
            "message must not imply that --root fixes this run: {}",
            diag.message
        );
        assert!(
            diag.message.contains("ignorePatterns"),
            "message names the silencing route: {}",
            diag.message
        );
        assert!(
            diag.message.contains("no config field"),
            "the message must say plainly that no config field traverses it: {}",
            diag.message
        );
        assert_eq!(
            serde_json::to_value(&diag).expect("serializes")["kind"],
            "skipped-source-dotdir",
            "id() must byte-match the serde kebab-case tag"
        );
    }

    #[cfg(feature = "schema")]
    #[test]
    fn workspace_diagnostic_schema_includes_skipped_source_dotdir() {
        let schema = schemars::schema_for!(WorkspaceDiagnostic);
        let json = serde_json::to_string(&schema).expect("schema serializes");
        assert!(json.contains("skipped-source-dotdir"));
    }

    #[test]
    fn source_read_failure_serializes_typed_error_payload() {
        let root = Path::new("/project");
        let diagnostic = WorkspaceDiagnostic::new(
            root,
            root.join("src/removed.ts"),
            WorkspaceDiagnosticKind::SourceReadFailure {
                error: "No such file or directory".to_string(),
            },
        );

        let json = serde_json::to_value(&diagnostic).expect("diagnostic serializes");
        assert_eq!(json["kind"], "source-read-failure");
        assert_eq!(
            json["path"],
            root.join("src/removed.ts")
                .display()
                .to_string()
                .replace('\\', "/")
        );
        assert_eq!(json["error"], "No such file or directory");
        assert!(
            json["message"]
                .as_str()
                .is_some_and(|message| message.contains("src/removed.ts"))
        );
    }

    #[cfg(feature = "schema")]
    #[test]
    fn workspace_diagnostic_schema_includes_source_read_failure() {
        let schema = schemars::schema_for!(WorkspaceDiagnostic);
        let json = serde_json::to_string(&schema).expect("schema serializes");
        assert!(json.contains("source-read-failure"));
        assert!(json.contains("error"));
    }

    #[test]
    fn bun_lockb_override_resolution_skipped_id_and_message() {
        let root = Path::new("/project");
        let diag = WorkspaceDiagnostic::new(
            root,
            root.join("package.json"),
            WorkspaceDiagnosticKind::BunLockbOverrideResolutionSkipped,
        );
        assert_eq!(diag.kind.id(), "bun-lockb-override-resolution-skipped");
        assert!(
            diag.message.contains("'package.json'"),
            "message names the project-relative manifest: {}",
            diag.message
        );
        assert!(
            diag.message.contains("no parseable text lockfile"),
            "message states the cause: {}",
            diag.message
        );
        assert!(
            !diag.message.contains("only bun.lockb"),
            "message must not claim bun.lockb is the only lockfile; yarn.lock or an unparseable \
             bun.lock may sit beside it: {}",
            diag.message
        );
        assert!(
            diag.message.contains("bun install --save-text-lockfile")
                && diag.message.contains("delete the stale bun.lockb"),
            "message ends with the text-lockfile next step and the stale-lockb alternative: {}",
            diag.message
        );
        let json = serde_json::to_value(&diag).expect("diagnostic serializes");
        assert_eq!(json["kind"], "bun-lockb-override-resolution-skipped");
    }

    #[test]
    fn bun_override_diagnostic_ids_and_messages_are_actionable() {
        let root = Path::new("/project");
        let malformed = WorkspaceDiagnostic::new(
            root,
            root.join("bun.lock"),
            WorkspaceDiagnosticKind::BunLockOverrideResolutionSkipped,
        );
        assert_eq!(malformed.kind.id(), "bun-lock-override-resolution-skipped");
        assert!(malformed.message.contains("regenerate"));

        let shadowed = WorkspaceDiagnostic::new(
            root,
            root.join("package.json"),
            WorkspaceDiagnosticKind::BunResolutionsShadowedByOverrides,
        );
        assert_eq!(shadowed.kind.id(), "bun-resolutions-shadowed-by-overrides");
        assert!(shadowed.message.contains("ignores `resolutions`"));
    }

    #[test]
    fn into_root_relative_strips_the_root_and_keeps_outside_paths_absolute() {
        let root = Path::new("/project");
        let inside = WorkspaceDiagnostic::new(
            root,
            root.join("packages/inner"),
            WorkspaceDiagnosticKind::UndeclaredWorkspace,
        )
        .into_root_relative(root);
        assert_eq!(inside.path, Path::new("packages/inner"));

        let outside = WorkspaceDiagnostic::new(
            root,
            PathBuf::from("/elsewhere/packages/inner"),
            WorkspaceDiagnosticKind::UndeclaredWorkspace,
        )
        .into_root_relative(root);
        assert_eq!(outside.path, Path::new("/elsewhere/packages/inner"));
    }

    #[test]
    fn analysis_stage_classification_covers_only_analyze_stage_kinds() {
        let analysis_stage = [
            WorkspaceDiagnosticKind::MalformedPnpmWorkspaceYaml {
                error: "bad yaml".to_owned(),
            },
            WorkspaceDiagnosticKind::BunLockbOverrideResolutionSkipped,
            WorkspaceDiagnosticKind::BunLockOverrideResolutionSkipped,
            WorkspaceDiagnosticKind::BunResolutionsShadowedByOverrides,
        ];
        for kind in &analysis_stage {
            assert!(
                kind.is_analysis_stage() && !kind.is_source_discovery(),
                "{} is recorded by the analyze stage only",
                kind.id()
            );
        }

        let other = [
            WorkspaceDiagnosticKind::UndeclaredWorkspace,
            WorkspaceDiagnosticKind::MalformedPackageJson {
                error: "trailing comma".to_owned(),
            },
            WorkspaceDiagnosticKind::GlobMatchedNoPackageJson {
                pattern: "packages/*".to_owned(),
            },
            WorkspaceDiagnosticKind::MalformedTsconfig {
                error: "unexpected token".to_owned(),
            },
            WorkspaceDiagnosticKind::TsconfigReferenceDirMissing,
            WorkspaceDiagnosticKind::SkippedLargeFile { size_bytes: 1 },
            WorkspaceDiagnosticKind::SkippedMinifiedFile { size_bytes: 1 },
            WorkspaceDiagnosticKind::SkippedSourceDotdir,
            WorkspaceDiagnosticKind::SourceReadFailure {
                error: "permission denied".to_owned(),
            },
        ];
        for kind in &other {
            assert!(
                !kind.is_analysis_stage(),
                "{} is a discovery kind, not an analyze-stage kind",
                kind.id()
            );
        }
    }

    #[test]
    fn merge_keeps_two_diagnostics_that_share_a_kind_id_and_path() {
        let root = Path::new("/project");
        let first = WorkspaceDiagnostic::new(
            root,
            root.join("packages/aaa"),
            WorkspaceDiagnosticKind::GlobMatchedNoPackageJson {
                pattern: "packages/*".to_owned(),
            },
        );
        let second = WorkspaceDiagnostic::new(
            root,
            root.join("packages/aaa"),
            WorkspaceDiagnosticKind::GlobMatchedNoPackageJson {
                pattern: "packages/a*".to_owned(),
            },
        );

        let merged =
            merge_workspace_diagnostics(vec![first.clone(), second.clone()], vec![first, second]);

        let patterns: Vec<String> = merged
            .iter()
            .map(|diagnostic| match &diagnostic.kind {
                WorkspaceDiagnosticKind::GlobMatchedNoPackageJson { pattern } => pattern.clone(),
                other => panic!("unexpected kind {}", other.id()),
            })
            .collect();
        assert_eq!(
            patterns,
            ["packages/*", "packages/a*"],
            "two overlapping globs report the same directory twice, with their own pattern; \
             the same entry seen from two observation points still folds to one"
        );
    }

    /// Issue #2366: a repository that declares one glob in two manifests
    /// (`"./apps/**"` in `package.json`, `apps/**` in `pnpm-workspace.yaml`)
    /// must not report every package-less directory under it twice now that the
    /// payload is part of the dedupe key.
    #[test]
    fn merge_folds_two_spellings_of_one_glob_into_one_diagnostic() {
        let root = Path::new("/project");
        let dotted = WorkspaceDiagnostic::new(
            root,
            root.join("apps/site/.next/cache"),
            WorkspaceDiagnosticKind::GlobMatchedNoPackageJson {
                pattern: "./apps/**".to_owned(),
            },
        );
        let bare = WorkspaceDiagnostic::new(
            root,
            root.join("apps/site/.next/cache"),
            WorkspaceDiagnosticKind::GlobMatchedNoPackageJson {
                pattern: "apps/**".to_owned(),
            },
        );
        assert_eq!(
            dotted.kind, bare.kind,
            "the no-op ./ prefix is normalised out of the recorded pattern"
        );
        assert!(
            dotted.message.contains("Glob 'apps/**'"),
            "the message renders the normalised pattern: {}",
            dotted.message
        );

        let merged = merge_workspace_diagnostics(vec![dotted], vec![bare]);
        assert_eq!(
            merged.len(),
            1,
            "one glob declared twice is one diagnostic: {merged:?}"
        );
    }

    /// A glob spelled exactly `"./"` (the project root itself) is the one
    /// pattern the prefix strip must leave alone: an empty `pattern` field
    /// names no glob, and the warning would quote nothing.
    #[test]
    fn new_keeps_a_root_only_glob_spelling_and_still_strips_a_real_prefix() {
        let root = Path::new("/project");
        let recorded = |pattern: &str| {
            let diagnostic = WorkspaceDiagnostic::new(
                root,
                root.join("pkgs"),
                WorkspaceDiagnosticKind::GlobMatchedNoPackageJson {
                    pattern: pattern.to_owned(),
                },
            );
            let WorkspaceDiagnosticKind::GlobMatchedNoPackageJson { pattern } = diagnostic.kind
            else {
                panic!("constructed a glob-matched-no-package-json diagnostic");
            };
            (pattern, diagnostic.message)
        };

        let (root_pattern, root_message) = recorded("./");
        assert_eq!(root_pattern, "./", "a root-only glob keeps its spelling");
        assert!(
            root_message.contains("Glob './'"),
            "the warning names the glob the manifest declared: {root_message}"
        );
        assert_eq!(recorded(".\\").0, ".\\");
        assert_eq!(recorded("./pkgs/*").0, "pkgs/*");
        assert_eq!(recorded(".\\pkgs\\*").0, "pkgs\\*");
    }

    /// Issue #2366, the path half of the same repository shape: expanding
    /// `./pkgs/*` joins the no-op `.` into every match, so the two manifests
    /// hand one directory to the diagnostic under two spellings. Both must
    /// store, render and serialise as the bare one, otherwise whichever
    /// manifest was read first decides whether the analysis envelopes print
    /// `./pkgs/aaa` while the workspace listing envelope prints `pkgs/aaa`.
    #[test]
    fn new_stores_one_spelling_for_a_directory_reached_through_a_dotted_glob() {
        let root = Path::new("/project");
        let dotted = WorkspaceDiagnostic::new(
            root,
            root.join("./pkgs/aaa"),
            WorkspaceDiagnosticKind::GlobMatchedNoPackageJson {
                pattern: "./pkgs/*".to_owned(),
            },
        );
        let bare = WorkspaceDiagnostic::new(
            root,
            root.join("pkgs/aaa"),
            WorkspaceDiagnosticKind::GlobMatchedNoPackageJson {
                pattern: "pkgs/*".to_owned(),
            },
        );

        let spelling = |diagnostic: &WorkspaceDiagnostic| {
            diagnostic.path.display().to_string().replace('\\', "/")
        };
        assert_eq!(
            spelling(&dotted),
            "/project/pkgs/aaa",
            "the stored path drops the no-op . component, which Path equality \
             hides but serialization does not"
        );
        assert_eq!(spelling(&dotted), spelling(&bare));
        assert_eq!(
            spelling(&dotted.clone().into_root_relative(root)),
            "pkgs/aaa"
        );

        let merged = merge_workspace_diagnostics(vec![dotted], vec![bare]);
        assert_eq!(
            merged.len(),
            1,
            "one directory reached through two spellings of one glob: {merged:?}"
        );
    }

    /// The single-list fold applied at workspace discovery keeps one entry per
    /// `(kind, path)` and leaves distinct payloads alone.
    #[test]
    fn dedupe_keeps_first_of_each_pair_and_every_distinct_payload() {
        let root = Path::new("/project");
        let glob = |pattern: &str, relative: &str| {
            WorkspaceDiagnostic::new(
                root,
                root.join(relative),
                WorkspaceDiagnosticKind::GlobMatchedNoPackageJson {
                    pattern: pattern.to_owned(),
                },
            )
        };

        let deduped = dedupe_workspace_diagnostics(vec![
            glob("pkgs/*", "pkgs/aaa"),
            glob("pkgs/*", "pkgs/bbb"),
            glob("./pkgs/*", "./pkgs/aaa"),
            glob("pkgs/a*", "pkgs/aaa"),
        ]);

        let reported: Vec<(String, String)> = deduped
            .iter()
            .map(|diagnostic| match &diagnostic.kind {
                WorkspaceDiagnosticKind::GlobMatchedNoPackageJson { pattern } => (
                    pattern.clone(),
                    diagnostic.path.display().to_string().replace('\\', "/"),
                ),
                other => panic!("unexpected kind {}", other.id()),
            })
            .collect();

        assert_eq!(
            reported,
            vec![
                ("pkgs/*".to_owned(), "/project/pkgs/aaa".to_owned()),
                ("pkgs/*".to_owned(), "/project/pkgs/bbb".to_owned()),
                ("pkgs/a*".to_owned(), "/project/pkgs/aaa".to_owned()),
            ],
            "the duplicate spelling folds away and the overlapping glob stays"
        );
    }

    /// The class `reachability_caveats[]` is computed from. Every kind here
    /// means the run never read a file that is part of the project, so its
    /// imports credit nothing and the modules it imports can be reported
    /// unused with a removal action on them. Classifying a kind `true` is the
    /// only wiring its findings need to inherit the caveat and the `fallow fix`
    /// withholding that follows it.
    #[test]
    fn source_never_analyzed_covers_every_file_the_run_did_not_read() {
        for kind in [
            WorkspaceDiagnosticKind::SkippedLargeFile { size_bytes: 1 },
            WorkspaceDiagnosticKind::SkippedMinifiedFile { size_bytes: 1 },
            WorkspaceDiagnosticKind::SkippedSourceDotdir,
            WorkspaceDiagnosticKind::SourceReadFailure {
                error: "permission denied".to_owned(),
            },
        ] {
            assert!(
                kind.source_never_analyzed(),
                "{} names a source file this run never read",
                kind.id()
            );
        }

        let degraded = WorkspaceDiagnosticKind::SourceParseDegraded {
            error_count: 3,
            panicked: false,
        };
        assert!(
            !degraded.source_never_analyzed(),
            "a degraded parse read the file, so it has a graph node and its reachability is \
             observable; the caveat pass narrows it instead of treating it as unread"
        );

        for kind in [
            WorkspaceDiagnosticKind::UndeclaredWorkspace,
            WorkspaceDiagnosticKind::MalformedPackageJson {
                error: "trailing comma".to_owned(),
            },
            WorkspaceDiagnosticKind::GlobMatchedNoPackageJson {
                pattern: "packages/*".to_owned(),
            },
            WorkspaceDiagnosticKind::MalformedTsconfig {
                error: "unexpected token".to_owned(),
            },
            WorkspaceDiagnosticKind::TsconfigReferenceDirMissing,
            WorkspaceDiagnosticKind::MalformedPnpmWorkspaceYaml {
                error: "bad indent".to_owned(),
            },
            WorkspaceDiagnosticKind::BunLockbOverrideResolutionSkipped,
            WorkspaceDiagnosticKind::BunLockOverrideResolutionSkipped,
            WorkspaceDiagnosticKind::BunResolutionsShadowedByOverrides,
            WorkspaceDiagnosticKind::NodeModulesMissing,
            WorkspaceDiagnosticKind::BoundariesNotConfigured,
            WorkspaceDiagnosticKind::RulePacksNotConfigured,
        ] {
            assert!(
                !kind.source_never_analyzed(),
                "{} says nothing about a source file's imports going unseen",
                kind.id()
            );
        }
    }

    #[test]
    fn source_walk_recorded_covers_only_the_kinds_a_walk_replaces() {
        for kind in [
            WorkspaceDiagnosticKind::SkippedLargeFile { size_bytes: 1 },
            WorkspaceDiagnosticKind::SkippedMinifiedFile { size_bytes: 1 },
            WorkspaceDiagnosticKind::SkippedSourceDotdir,
        ] {
            assert!(
                kind.is_source_walk_recorded() && kind.is_source_discovery(),
                "{} is written by the source walk",
                kind.id()
            );
        }

        let read_failure = WorkspaceDiagnosticKind::SourceReadFailure {
            error: "permission denied".to_owned(),
        };
        assert!(
            read_failure.is_source_discovery() && !read_failure.is_source_walk_recorded(),
            "the parse stage records source-read-failure after the walk, so it must keep \
             reaching sessions through the registry"
        );

        for kind in [
            WorkspaceDiagnosticKind::UndeclaredWorkspace,
            WorkspaceDiagnosticKind::TsconfigReferenceDirMissing,
            WorkspaceDiagnosticKind::BunLockbOverrideResolutionSkipped,
            WorkspaceDiagnosticKind::BunLockOverrideResolutionSkipped,
            WorkspaceDiagnosticKind::BunResolutionsShadowedByOverrides,
        ] {
            assert!(
                !kind.is_source_walk_recorded(),
                "{} is not written by the source walk",
                kind.id()
            );
        }
    }

    /// Issue #2638, the single most load-bearing classification in the new
    /// kind. Answering `true` here would attach `IncompleteFileAnalysis` and
    /// `IncompleteImportGraph` caveats to findings on nearly every project
    /// that keeps a non-gitignored `dist/` or `coverage/`, and make
    /// `fallow fix` withhold `delete-file` and `remove-export` project-wide.
    /// A built-in exclusion is designed behavior on generated output, not a
    /// degraded run.
    #[test]
    fn a_built_in_ignore_exclusion_is_not_a_file_the_run_failed_to_analyze() {
        let kind = WorkspaceDiagnosticKind::ExcludedByDefaultIgnore {
            pattern: "**/build/**".to_owned(),
            file_count: 3,
            directory_count: 1,
        };
        assert!(!kind.source_never_analyzed());
    }

    /// Issue #2638: these exclusions fire in the product's default state on
    /// most monorepos, so a default stderr line would be permanent noise that
    /// names no defect. The CLI prints a note under `--explain-skipped`
    /// instead.
    #[test]
    fn a_built_in_ignore_exclusion_does_not_warn_on_stderr_by_default() {
        let kind = WorkspaceDiagnosticKind::ExcludedByDefaultIgnore {
            pattern: "**/build/**".to_owned(),
            file_count: 3,
            directory_count: 1,
        };
        assert!(!kind.warns_on_stderr());
    }

    /// Issue #2638 plus issue #2366: the walk writes it, so it has to be
    /// classified as source-discovery (or combined mode's per-analysis config
    /// reloads wipe it before serialization) AND as walk-recorded (or a
    /// concurrent walk's tally is folded into another analysis's list).
    #[test]
    fn a_built_in_ignore_exclusion_is_walk_recorded_source_discovery() {
        let kind = WorkspaceDiagnosticKind::ExcludedByDefaultIgnore {
            pattern: "**/build/**".to_owned(),
            file_count: 3,
            directory_count: 1,
        };
        assert!(kind.is_source_discovery());
        assert!(kind.is_source_walk_recorded());
        assert!(!kind.is_analysis_stage());
        assert_eq!(kind.id(), "excluded-by-default-ignore");
    }

    /// Issue #2638: the message has to name the pattern the reader cannot see,
    /// the directory, and the only remedy that actually analyzes the tree.
    /// `ignorePatterns` is not that remedy: the compiled set unions, so it
    /// cannot negate a built-in.
    #[test]
    fn a_built_in_ignore_exclusion_message_names_the_pattern_and_the_root_remedy() {
        let root = Path::new("/project");
        let diag = WorkspaceDiagnostic::new(
            root,
            root.join("packages/web/build"),
            WorkspaceDiagnosticKind::ExcludedByDefaultIgnore {
                pattern: "**/build/**".to_owned(),
                file_count: 4,
                directory_count: 1,
            },
        );
        assert!(diag.message.contains("**/build/**"), "{}", diag.message);
        assert!(
            diag.message.contains("packages/web/build"),
            "{}",
            diag.message
        );
        assert!(
            diag.message.contains("fallow --root packages/web/build"),
            "the remedy is copy-pasteable: {}",
            diag.message
        );
        assert!(
            diag.message
                .contains("cannot be switched off through ignorePatterns"),
            "the message must not advertise a negation that does not exist: {}",
            diag.message
        );
    }

    /// One excluded file reads as one file, not as "1 source files".
    #[test]
    fn a_single_excluded_file_message_is_singular() {
        let root = Path::new("/project");
        let diag = WorkspaceDiagnostic::new(
            root,
            root.join("dist"),
            WorkspaceDiagnosticKind::ExcludedByDefaultIgnore {
                pattern: "**/dist/**".to_owned(),
                file_count: 1,
                directory_count: 1,
            },
        );
        assert!(
            diag.message
                .starts_with("Skipped 1 source file under 'dist'"),
            "{}",
            diag.message
        );
        assert!(diag.message.contains("it matches"), "{}", diag.message);
        assert!(
            diag.message
                .contains("nothing it imports, exports, or defines"),
            "the whole sentence agrees in number, not just its first clause: {}",
            diag.message
        );
    }

    /// The anchor directory is the largest group, never a majority: ten
    /// packages each holding one excluded file make every one of them "the
    /// largest", and a message claiming otherwise is false on exactly the flat
    /// monorepo shape issue #2638 is about.
    #[test]
    fn a_scattered_exclusion_names_the_largest_group_and_counts_the_directories() {
        let root = Path::new("/project");
        let diag = WorkspaceDiagnostic::new(
            root,
            root.join("packages/a/dist"),
            WorkspaceDiagnosticKind::ExcludedByDefaultIgnore {
                pattern: "**/dist/**".to_owned(),
                file_count: 10,
                directory_count: 10,
            },
        );
        assert!(
            diag.message.starts_with(
                "Skipped 10 source files across 10 directories, the largest group under \
                 'packages/a/dist'"
            ),
            "{}",
            diag.message
        );
        assert!(
            !diag.message.contains("the most of them"),
            "a max-of-group is not a majority: {}",
            diag.message
        );
    }

    /// A file-shaped built-in matches on the file name, so the `--root` remedy
    /// the directory-shaped patterns get would re-exclude the same file. The
    /// message must not print a command that provably does nothing.
    #[test]
    fn a_file_shaped_pattern_does_not_advertise_the_root_remedy() {
        let root = Path::new("/project");
        let diag = WorkspaceDiagnostic::new(
            root,
            root.join("vendor"),
            WorkspaceDiagnosticKind::ExcludedByDefaultIgnore {
                pattern: "**/*.min.js".to_owned(),
                file_count: 2,
                directory_count: 1,
            },
        );
        assert!(
            !diag.message.contains("fallow --root"),
            "the message explains why re-rooting fails, it does not prescribe it: {}",
            diag.message
        );
        assert!(
            diag.message.contains("matches a file name"),
            "the message says why: {}",
            diag.message
        );
        assert!(
            diag.message.contains("Rename"),
            "and names the remedy that does work: {}",
            diag.message
        );
    }

    /// A built-in that matched a file sitting directly at the analysis root
    /// anchors at the root, and an empty string is not a location.
    #[test]
    fn a_root_anchored_exclusion_renders_its_location_as_dot() {
        let root = Path::new("/project");
        let diag = WorkspaceDiagnostic::new(
            root,
            root.to_path_buf(),
            WorkspaceDiagnosticKind::ExcludedByDefaultIgnore {
                pattern: "**/*.min.js".to_owned(),
                file_count: 1,
                directory_count: 1,
            },
        );
        assert!(
            diag.message.starts_with("Skipped 1 source file under '.'"),
            "{}",
            diag.message
        );
    }

    #[test]
    fn glob_first_literal_segment_skips_wildcards_and_dot_components() {
        assert_eq!(glob_first_literal_segment("**/build/**"), Some("build"));
        assert_eq!(glob_first_literal_segment("./dist/**"), Some("dist"));
        assert_eq!(glob_first_literal_segment("**/*.min.js"), None);
        assert_eq!(glob_first_literal_segment("**/*.bundle.js"), None);
        assert_eq!(glob_first_literal_segment("**/{a,b}/**"), None);
    }

    #[test]
    fn format_size_mb_one_decimal() {
        assert_eq!(format_size_mb(0), "0.0 MB");
        assert_eq!(format_size_mb(5 * 1024 * 1024), "5.0 MB");
        assert_eq!(format_size_mb(1024 * 1024 + 512 * 1024), "1.5 MB");
    }

    #[test]
    fn undeclared_workspace_message_has_next_step() {
        let root = Path::new("/project");
        let diag = WorkspaceDiagnostic::new(
            root,
            root.join("packages/legacy"),
            WorkspaceDiagnosticKind::UndeclaredWorkspace,
        );
        assert_eq!(diag.kind.id(), "undeclared-workspace");
        assert!(diag.message.contains("packages/legacy"), "{}", diag.message);
        assert!(
            diag.message.contains("ignorePatterns"),
            "next-step hint preserved: {}",
            diag.message
        );
    }
    /// The seven health-pipeline kinds (issue #2689). Each is classified in
    /// four places, and getting one wrong is silent: an entry that answers
    /// `is_analysis_stage` is wiped by the dead-code pass the health run itself
    /// invokes, and one that answers `is_source_discovery` is preserved by the
    /// wrong mechanism.
    #[test]
    fn health_stage_kinds_are_classified_as_health_stage_and_nothing_else() {
        for kind in [
            WorkspaceDiagnosticKind::FileScoresUnavailable {
                error: "boom".to_owned(),
            },
            WorkspaceDiagnosticKind::HotspotsSkipped {
                cause: "not-a-repository".to_owned(),
            },
            WorkspaceDiagnosticKind::ShallowClone {
                ownership_requested: true,
            },
            WorkspaceDiagnosticKind::UnpinnedClock,
            WorkspaceDiagnosticKind::OwnershipUnavailable {
                cause: "codeowners-parse-failed".to_owned(),
                error: "boom".to_owned(),
            },
            WorkspaceDiagnosticKind::TrendSnapshotUnreadable {
                error: "boom".to_owned(),
            },
            WorkspaceDiagnosticKind::CoverageAutoDetected,
        ] {
            let id = kind.id();
            assert!(kind.is_health_stage(), "{id} must be health-stage");
            assert!(!kind.is_analysis_stage(), "{id} must not be analysis-stage");
            assert!(
                !kind.is_source_discovery(),
                "{id} must not be source-discovery"
            );
            assert!(
                !kind.is_source_walk_recorded(),
                "{id} must not be walk-recorded"
            );
            assert!(
                !kind.source_never_analyzed(),
                "{id} reports an input, not an unread source file"
            );
        }
    }

    /// Six of the seven report a result the run could not measure as asked;
    /// the coverage provenance entry does not, and a consumer sentence about a
    /// degraded run must not fire for it.
    #[test]
    fn only_the_coverage_provenance_kind_does_not_degrade_the_analysis() {
        assert!(
            WorkspaceDiagnosticKind::HotspotsSkipped {
                cause: "invalid-since".to_owned(),
            }
            .warns_on_stderr(),
            "a skipped hotspot section is a degraded result"
        );
        assert!(
            WorkspaceDiagnosticKind::UnpinnedClock.warns_on_stderr(),
            "a drifting measurement is a degraded result"
        );
        assert!(
            !WorkspaceDiagnosticKind::CoverageAutoDetected.warns_on_stderr(),
            "auto-detected coverage loaded fine and degraded nothing"
        );
    }

    /// Each skip cause carries its own remedy, and the original cause's wording
    /// is frozen: it shipped before the token existed, so a reader who matched
    /// on that sentence must still match on it.
    #[test]
    fn every_hotspot_skip_cause_renders_its_own_remedy() {
        let root = Path::new("/project");
        let skipped = |cause: &str, path: PathBuf| {
            WorkspaceDiagnostic::new(
                root,
                path,
                WorkspaceDiagnosticKind::HotspotsSkipped {
                    cause: cause.to_owned(),
                },
            )
        };

        let no_repo = skipped("not-a-repository", root.to_path_buf());
        assert_eq!(
            no_repo.message,
            "Hotspot analysis was skipped because no git repository was found at the project \
             root, so the hotspots, churn and ownership sections report nothing rather than \
             zero. Run fallow inside the repository, or pass --churn-file with exported change \
             history."
        );

        let bad_since = skipped("invalid-since", root.to_path_buf());
        assert!(
            bad_since.message.contains("--since")
                && bad_since.message.contains("6m or 90d")
                && !bad_since.message.contains("no git repository"),
            "a malformed window is respelled, not moved into a repository: {}",
            bad_since.message
        );

        let churn = skipped("churn-file-unreadable", root.join("build/churn.json"));
        assert!(
            churn.message.contains("'build/churn.json'") && churn.message.contains("rerun"),
            "the remedy names the file that changed under the run: {}",
            churn.message
        );

        let unborn = skipped("no-commits", root.to_path_buf());
        assert!(
            unborn.message.contains("no commits")
                && unborn.message.contains("--churn-file")
                && !unborn.message.contains("no git repository"),
            "a branch without a commit is told to commit, not to move: {}",
            unborn.message
        );

        for diagnostic in [&no_repo, &unborn, &bad_since, &churn] {
            assert!(
                diagnostic.degrades_analysis,
                "every skip leaves the hotspot sections unmeasured: {}",
                diagnostic.message
            );
        }
    }

    /// The message is the only prose a consumer renders, so each one must name
    /// the consequence and a next step rather than restate the kind.
    #[test]
    fn health_stage_messages_name_a_next_step() {
        let root = Path::new("/project");
        let shallow = WorkspaceDiagnostic::new(
            root,
            root.to_path_buf(),
            WorkspaceDiagnosticKind::ShallowClone {
                ownership_requested: true,
            },
        );
        assert!(
            shallow.message.contains("git fetch --unshallow"),
            "{}",
            shallow.message
        );
        assert!(
            shallow.message.contains("Ownership signals are skewed too"),
            "a run that asked for ownership is told what else it costs: {}",
            shallow.message
        );
        let without_ownership = WorkspaceDiagnostic::new(
            root,
            root.to_path_buf(),
            WorkspaceDiagnosticKind::ShallowClone {
                ownership_requested: false,
            },
        );
        assert!(
            !without_ownership.message.contains("Ownership"),
            "a run that did not ask for ownership is not told about it: {}",
            without_ownership.message
        );

        let coverage = WorkspaceDiagnostic::new(
            root,
            root.join("coverage/coverage-final.json"),
            WorkspaceDiagnosticKind::CoverageAutoDetected,
        );
        assert_eq!(coverage.kind.id(), "coverage-auto-detected");
        assert!(
            coverage
                .message
                .contains("--coverage 'coverage/coverage-final.json'"),
            "the remedy names the file that fed the score: {}",
            coverage.message
        );
        assert!(
            !coverage.degrades_analysis,
            "provenance is not a degraded run"
        );

        let ownership = WorkspaceDiagnostic::new(
            root,
            root.to_path_buf(),
            WorkspaceDiagnosticKind::OwnershipUnavailable {
                cause: "invalid-bot-pattern".to_owned(),
                error: "unclosed".to_owned(),
            },
        );
        assert!(
            ownership.message.contains("botPatterns"),
            "the two causes render different remedies: {}",
            ownership.message
        );
    }

    fn plugin_unreadable(key: &str, reason: &str) -> WorkspaceDiagnostic {
        WorkspaceDiagnostic::new(
            Path::new("/project"),
            PathBuf::from("/project/module-federation.config.ts"),
            WorkspaceDiagnosticKind::PluginConfigUnreadable {
                plugin: "module-federation".to_owned(),
                key: key.to_owned(),
                reason: reason.to_owned(),
            },
        )
    }

    fn plugin_not_modeled(key: &str, reason: &str) -> WorkspaceDiagnostic {
        WorkspaceDiagnostic::new(
            Path::new("/project"),
            PathBuf::from("/project/nuxt.config.ts"),
            WorkspaceDiagnosticKind::PluginEffectNotModeled {
                plugin: "nuxt".to_owned(),
                key: key.to_owned(),
                reason: reason.to_owned(),
            },
        )
    }

    /// The plugin stage is its own stage: classified there and nowhere else, so
    /// the stash preserve keeps it and no other stage's clear wipes it.
    #[test]
    fn plugin_stage_kinds_are_classified_as_plugin_stage_and_nothing_else() {
        for kind in [
            WorkspaceDiagnosticKind::PluginConfigUnreadable {
                plugin: "module-federation".to_owned(),
                key: "exposes".to_owned(),
                reason: "not-object-literal".to_owned(),
            },
            WorkspaceDiagnosticKind::PluginEffectNotModeled {
                plugin: "nuxt".to_owned(),
                key: "components".to_owned(),
                reason: "key-effect-not-modeled".to_owned(),
            },
        ] {
            let id = kind.id();
            assert!(kind.is_plugin_stage(), "{id} must be plugin-stage");
            assert!(!kind.is_analysis_stage(), "{id} must not be analysis-stage");
            assert!(!kind.is_health_stage(), "{id} must not be health-stage");
            assert!(
                !kind.is_source_discovery(),
                "{id} must not be source-discovery"
            );
            assert!(
                !kind.is_source_walk_recorded(),
                "{id} must not be walk-recorded"
            );
            assert!(
                !kind.source_never_analyzed(),
                "{id} reports a config file, not an unread source file"
            );
        }
        assert!(
            !WorkspaceDiagnosticKind::UnpinnedClock.is_plugin_stage(),
            "another stage's kind must not answer the plugin predicate"
        );
    }

    /// An unread declaration costs findings in both directions, so it degrades
    /// the analysis; an effect fallow does not model suppresses findings the
    /// user opted into and must not warn on every run forever.
    #[test]
    fn only_the_unreadable_plugin_config_degrades_the_analysis() {
        let unreadable = plugin_unreadable("exposes", "not-object-literal");
        assert!(
            unreadable.degrades_analysis,
            "an unread declaration did not reach the analysis: {}",
            unreadable.message
        );
        let not_modeled = plugin_not_modeled("components", "key-effect-not-modeled");
        assert!(
            !not_modeled.degrades_analysis,
            "the config was readable and the patterns stayed: {}",
            not_modeled.message
        );
    }

    /// The reason decides the remedy, so each token renders its own situation,
    /// and a token from a later release still renders a sentence.
    #[test]
    fn every_unreadable_reason_renders_its_own_situation() {
        let cases = [
            ("not-object-literal", "is not a static object literal"),
            ("array-form", "uses the array form"),
            ("spread", "spreads a value that is not statically readable"),
            (
                "unreadable-entries",
                "has entries that hold no statically readable value",
            ),
            (
                "unrecognized-call",
                "is passed through a call that is not a known config wrapper",
            ),
            (
                "import-target-unreadable",
                "comes from an imported file that is not statically readable",
            ),
            (
                "dynamic-argument",
                "receives an argument that is not a static literal",
            ),
        ];
        for (reason, expected) in cases {
            let diagnostic = plugin_unreadable("exposes", reason);
            assert!(
                diagnostic.message.contains(expected),
                "`{reason}` must render its own situation: {}",
                diagnostic.message
            );
        }
        let unknown = plugin_unreadable("exposes", "reason-from-a-later-release");
        assert!(
            unknown.message.contains("could not be read statically"),
            "an unrecognised token still renders a sentence: {}",
            unknown.message
        );
    }

    /// The payload carries no prose, so the remedy comes from the key: both
    /// Module Federation keys name the option that covers the gap, and the
    /// message names the config file the user must edit.
    #[test]
    fn unreadable_plugin_messages_name_the_config_file_and_the_option() {
        let exposes = plugin_unreadable("exposes", "not-object-literal");
        assert!(
            exposes
                .message
                .contains("`exposes` in 'module-federation.config.ts'")
                && exposes.message.contains("dynamicallyLoaded")
                && exposes.message.starts_with("Plugin 'module-federation':"),
            "{}",
            exposes.message
        );
        let remotes = plugin_unreadable("remotes", "spread");
        assert!(
            remotes.message.contains("ignoreDependencies"),
            "the two keys have different remedies: {}",
            remotes.message
        );
        let unknown_key = plugin_unreadable("shared", "not-object-literal");
        assert!(
            !unknown_key.message.contains("dynamicallyLoaded")
                && !unknown_key.message.contains("ignoreDependencies")
                && unknown_key
                    .message
                    .contains("Declare the value as a static object literal."),
            "a key with no documented consequence falls back to the general claim: {}",
            unknown_key.message
        );
        assert!(
            !exposes.message.contains('\n'),
            "the sentence travels into a CI annotation and stays on one line: {}",
            exposes.message
        );
    }

    /// An unrecognized call was read as a lower bound, and an unreadable import
    /// target holds config that is shared across files. Each renders its own
    /// consequence and a remedy that names the option, never an object literal.
    #[test]
    fn the_call_and_import_reasons_render_their_own_remedy() {
        let call = plugin_unreadable("exposes", "unrecognized-call");
        assert!(
            call.message
                .contains("only the targets in the object literal it receives")
                && call
                    .message
                    .contains("Name any other exposed files in `dynamicallyLoaded`."),
            "{}",
            call.message
        );
        let call = plugin_unreadable("remotes", "unrecognized-call");
        assert!(
            call.message
                .contains("Name any other aliases in `ignoreDependencies`."),
            "{}",
            call.message
        );
        for key in ["exposes", "remotes"] {
            let import = plugin_unreadable(key, "import-target-unreadable");
            assert!(
                !import.message.contains("object literal"),
                "an import target is not fixed by writing an object literal: {}",
                import.message
            );
        }
        let import = plugin_unreadable("exposes", "import-target-unreadable");
        assert!(
            import.message.contains("`dynamicallyLoaded`"),
            "{}",
            import.message
        );
    }

    /// A runtime call with a dynamic argument names the source file and the
    /// function, and its remedy names the option that covers the remote.
    #[test]
    fn a_dynamic_runtime_call_renders_its_own_remedy() {
        for (key, consequence) in [
            (
                "registerRemotes",
                "the remotes it registers are not treated as provided",
            ),
            (
                "loadRemote",
                "the remote it loads is not treated as provided",
            ),
            (
                "init",
                "the remotes its options declare are not treated as provided",
            ),
            (
                "createInstance",
                "the remotes its options declare are not treated as provided",
            ),
        ] {
            let diagnostic = plugin_unreadable(key, "dynamic-argument");
            assert!(
                diagnostic.message.contains(&format!("`{key}` in"))
                    && diagnostic.message.contains(consequence)
                    && diagnostic.message.contains("`ignoreDependencies`")
                    && !diagnostic.message.contains("object literal"),
                "{}",
                diagnostic.message
            );
        }
    }

    /// One config file can hold two unreadable keys, and the payload is what
    /// tells them apart: the fold keys on the whole kind, so both survive.
    #[test]
    fn two_unreadable_keys_in_one_file_are_two_diagnostics() {
        let merged = dedupe_workspace_diagnostics(vec![
            plugin_unreadable("exposes", "not-object-literal"),
            plugin_unreadable("remotes", "spread"),
        ]);
        assert_eq!(merged.len(), 2, "{merged:?}");
    }

    /// A surface whose own key fallow cannot model and a config file whose
    /// top-level property it cannot read need different remedies. The two tokens
    /// render different causes, and each cause states one fact per sentence.
    #[test]
    fn the_not_modeled_reasons_render_different_causes() {
        let key = plugin_not_modeled("components", "key-effect-not-modeled");
        assert!(
            key.message
                .contains("fallow does not model the effect of `components` in 'nuxt.config.ts'.")
                && key
                    .message
                    .contains("`autoImports` kept the convention entry patterns"),
            "{}",
            key.message
        );
        let property = plugin_not_modeled("imports", "config-property-unreadable");
        assert!(
            property.message.contains(
                "fallow cannot read a top-level property in 'nuxt.config.ts', so it cannot \
                 classify the `imports` surface. `autoImports` kept the convention entry patterns \
                 for that surface, and fallow reports no unused file there."
            ),
            "{}",
            property.message
        );
        assert_eq!(
            property.message.matches(", so ").count(),
            1,
            "one cause per sentence: {}",
            property.message
        );
    }

    /// A file that reads a whole virtual module names the file and the module,
    /// not a config key, and gives a remedy in the source, not in the config.
    #[test]
    fn an_unreadable_virtual_module_read_names_the_module_and_a_source_remedy() {
        let read = WorkspaceDiagnostic::new(
            Path::new("/project"),
            PathBuf::from("/project/app/lib/registry.ts"),
            WorkspaceDiagnosticKind::PluginEffectNotModeled {
                plugin: "nuxt".to_owned(),
                key: "#components".to_owned(),
                reason: "key-effect-not-modeled".to_owned(),
            },
        );
        assert!(
            read.message.contains(
                "fallow cannot read which names 'app/lib/registry.ts' takes from `#components`"
            ) && read.message.contains("member access")
                && !read.message.contains("entry patterns"),
            "{}",
            read.message
        );
    }
}