omena-query 0.2.0

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

use omena_parser::{
    ParsedAnimationFactKind, ParsedCssModuleComposesEdgeKind, ParsedExtendTargetFactKind,
    ParsedSassModuleEdgeFact, ParsedSassModuleEdgeFactKind, ParsedSelectorFactKind,
    ParsedVariableFactKind,
};
use omena_query_checker_orchestrator::{
    ModuleGraphEdgeV0, ModuleGraphV0, OutcomeMode, REPLICA_ENSEMBLE_FEATURE_GATE_V0,
    REPLICA_ENSEMBLE_LAYER_MARKER_V0, REPLICA_ENSEMBLE_SCHEMA_VERSION_V0, ReplicaSnapshotV0,
    ReportOptionsV0, ReportRecommendation, build_cross_file_inconsistency_report,
};
use omena_query_checker_orchestrator::{
    OmenaCheckerReplicaEnsembleInputV0, OmenaCheckerReplicaEnsembleReportInputV0,
    run_omena_query_checker_replica_ensemble_gate_v0,
};

use super::cascade_checker::collect_query_replica_ensemble_site_outcomes;
use super::cascade_checker::summarize_query_cascade_checker_diagnostics_with_deep_analysis;
use super::diagnostic_suppressions::OmenaStrictnessLevelV0;
use super::diagnostic_suppressions::apply_omena_query_style_diagnostic_suppressions;
use super::diagnostic_suppressions::parse_omena_query_style_strictness_level;
use super::parser_facade::collect_omena_query_omena_parser_style_facts_raw;
use super::*;

const LSP_DIAGNOSTIC_TAG_UNNECESSARY: u8 = 1;
const LSP_DIAGNOSTIC_TAG_DEPRECATED: u8 = 2;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OmenaQueryExternalModuleModeV0 {
    Ignored,
    Sif,
}

pub fn summarize_omena_query_missing_custom_property_diagnostics(
    style_uri: &str,
    source: &str,
    candidates: &[OmenaQueryStyleHoverCandidateV0],
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let declaration_names = candidates
        .iter()
        .filter(|candidate| candidate.kind == "customPropertyDeclaration")
        .map(|candidate| candidate.name.as_str())
        .collect::<BTreeSet<_>>();
    if declaration_names.is_empty() {
        return Vec::new();
    }

    // `var(--x, fallback)` references cannot be "missing" in any observable way — the
    // fallback guarantees a value — so suppress the lint per-reference. The fallback fact
    // range and the candidate range both derive from the same parser byte span via
    // `parser_range_for_byte_span`, so matching on the rendered range scopes the suppression
    // to the exact `var()` argument (a nested fallback-less `var(--b)` in
    // `var(--a, var(--b))` stays a live candidate).
    let dialect = omena_parser_dialect_for_style_path(style_uri);
    let facts = collect_omena_query_omena_parser_style_facts_raw(source, dialect);
    let fallback_ranges = facts
        .variables
        .iter()
        .filter(|fact| {
            fact.kind == ParsedVariableFactKind::CustomPropertyReference && fact.has_fallback
        })
        .map(|fact| {
            let byte_span = ParserByteSpanV0 {
                start: u32::from(fact.range.start()) as usize,
                end: u32::from(fact.range.end()) as usize,
            };
            (
                fact.name.clone(),
                parser_range_for_byte_span(source, byte_span),
            )
        })
        .collect::<BTreeSet<_>>();

    let insertion_range = end_of_source_range(source);
    candidates
        .iter()
        .filter(|candidate| {
            candidate.kind == "customPropertyReference"
                && !declaration_names.contains(candidate.name.as_str())
                && !fallback_ranges.contains(&(candidate.name.clone(), candidate.range))
        })
        .map(|candidate| OmenaQueryStyleDiagnosticV0 {
            code: "missingCustomProperty",
            severity: "warning",
            provenance: vec![
                "omena-parser.custom-property-facts",
                "omena-query.style-diagnostics",
            ],
            range: candidate.range,
            message: format!(
                "CSS custom property '{}' not found in indexed style tokens.",
                candidate.name
            ),
            tags: Vec::new(),
            create_custom_property: Some(OmenaQueryCreateCustomPropertyActionV0 {
                uri: style_uri.to_string(),
                range: insertion_range,
                new_text: format!("\n\n:root {{\n  {}: ;\n}}\n", candidate.name),
                property_name: candidate.name.clone(),
            }),
        })
        .collect()
}

pub fn summarize_omena_query_cascade_aware_style_diagnostics(
    style_uri: &str,
    source: &str,
    candidates: &[OmenaQueryStyleHoverCandidateV0],
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    summarize_omena_query_cascade_aware_style_diagnostics_with_deep_analysis(
        style_uri, source, candidates, false,
    )
}

/// Cascade-aware diagnostics with an explicit opt-in deep-analysis switch. With
/// `deep_analysis == false` (the default surface) only the product cascade gate
/// diagnostics are emitted; `deep_analysis == true` additionally surfaces the
/// rg-flow / categorical theory hints, deduplicated against `circularVar`.
pub fn summarize_omena_query_cascade_aware_style_diagnostics_with_deep_analysis(
    style_uri: &str,
    source: &str,
    candidates: &[OmenaQueryStyleHoverCandidateV0],
    deep_analysis: bool,
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let declarations_by_name = candidates
        .iter()
        .filter(|candidate| candidate.kind == "customPropertyDeclaration")
        .map(|candidate| (candidate.name.as_str(), candidate.range))
        .collect::<BTreeMap<_, _>>();

    let dialect = omena_parser_dialect_for_style_path(style_uri);
    let mut diagnostics =
        summarize_static_css_custom_property_fixed_point_from_source(source, dialect)
            .entries
            .into_iter()
            .filter(|entry| entry.guaranteed_invalid)
            .filter_map(|entry| {
                declarations_by_name
                    .get(entry.name.as_str())
                    .copied()
                    .map(|range| OmenaQueryStyleDiagnosticV0 {
                        code: "guaranteedInvalidCustomProperty",
                        severity: "warning",
                        provenance: vec![
                            "omena-transform-passes.custom-property-lfp",
                            "omena-query.cascade-aware-diagnostics",
                        ],
                        range,
                        message: format!(
                            "CSS custom property '{}' resolves to the guaranteed-invalid value.",
                            entry.name
                        ),
                        tags: Vec::new(),
                        create_custom_property: None,
                    })
            })
            .collect::<Vec<_>>();

    diagnostics.extend(
        summarize_query_cascade_checker_diagnostics_with_deep_analysis(
            style_uri,
            source,
            deep_analysis,
        ),
    );

    diagnostics
}

pub fn summarize_omena_query_missing_keyframes_diagnostics(
    style_uri: &str,
    source: &str,
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let dialect = omena_parser_dialect_for_style_path(style_uri);
    let facts = collect_omena_query_omena_parser_style_facts_raw(source, dialect);
    let declared_keyframes = facts
        .animations
        .iter()
        .filter(|animation| animation.kind == ParsedAnimationFactKind::KeyframesDeclaration)
        .map(|animation| animation.name.clone())
        .collect::<BTreeSet<_>>();
    let mut emitted = BTreeSet::new();

    facts
        .animations
        .into_iter()
        .filter(|animation| animation.kind == ParsedAnimationFactKind::AnimationNameReference)
        .filter(|animation| !declared_keyframes.contains(animation.name.as_str()))
        .filter_map(|animation| {
            let start: u32 = animation.range.start().into();
            let end: u32 = animation.range.end().into();
            let byte_span = ParserByteSpanV0 {
                start: start as usize,
                end: end as usize,
            };
            if !emitted.insert((animation.name.clone(), byte_span.start, byte_span.end)) {
                return None;
            }
            Some((animation, parser_range_for_byte_span(source, byte_span)))
        })
        .map(|(animation, range)| OmenaQueryStyleDiagnosticV0 {
            code: "missingKeyframes",
            severity: "warning",
            provenance: vec![
                "omena-parser.animation-facts",
                "omena-query.style-diagnostics",
            ],
            range,
            message: format!("@keyframes '{}' not found in this file.", animation.name),
            tags: Vec::new(),
            create_custom_property: None,
        })
        .collect()
}

pub fn summarize_omena_query_missing_sass_symbol_diagnostics(
    style_uri: &str,
    source: &str,
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let dialect = omena_parser_dialect_for_style_path(style_uri);
    let facts = collect_omena_query_omena_parser_style_facts_raw(source, dialect);
    let mut declarations = BTreeSet::<SassSymbolKey>::new();
    let mut emitted = BTreeSet::new();
    let mut diagnostics = Vec::new();

    for symbol in facts.sass_symbols {
        // Route the single-file key tuple through the `sass_symbol_key` chokepoint so the
        // hyphen/underscore fold (Sass treats `$a-b` and `$a_b` as the same identifier) is
        // applied here too, not only on the cross-file/workspace path. (#48)
        let key = sass_symbol_key(
            symbol.symbol_kind,
            symbol.namespace.clone(),
            symbol.name.clone(),
        );
        if omena_query_sass_symbol_fact_kind_is_declaration(symbol.kind) {
            declarations.insert(key);
            continue;
        }
        if !omena_query_sass_symbol_fact_kind_is_reference(symbol.kind) {
            continue;
        }
        if declarations.contains(&key) {
            continue;
        }
        if is_omena_query_sass_builtin_symbol_reference_resolved(
            &facts.sass_module_edges,
            symbol.symbol_kind,
            symbol.namespace.as_deref(),
            symbol.name.as_str(),
        ) {
            continue;
        }

        let start: u32 = symbol.range.start().into();
        let end: u32 = symbol.range.end().into();
        let byte_span = ParserByteSpanV0 {
            start: start as usize,
            end: end as usize,
        };
        if !emitted.insert((
            symbol.symbol_kind,
            symbol.namespace.clone(),
            symbol.name.clone(),
            byte_span.start,
            byte_span.end,
        )) {
            continue;
        }
        diagnostics.push(OmenaQueryStyleDiagnosticV0 {
            code: "missingSassSymbol",
            severity: "warning",
            provenance: vec![
                "omena-parser.sass-symbol-facts",
                "omena-query.style-diagnostics",
            ],
            range: parser_range_for_byte_span(source, byte_span),
            message: format!(
                "{} not found in this file.",
                format_query_sass_symbol_label(symbol.symbol_kind, symbol.name.as_str())
            ),
            tags: Vec::new(),
            create_custom_property: None,
        });
    }

    diagnostics
}

/// RFC-0007-E1 (#45): `@extend` target validation. dart-sass hard-errors on `@extend %nonexistent`
/// / `@extend .missing` (`"%nonexistent" does not exist`); omena was silent because the
/// `ScssExtendRule` target was parsed and discarded. The parser now captures each target as a
/// `ParsedExtendTargetFact` (kind + name + `!optional` flag + range); this rule mirrors
/// `missingSassSymbol`'s file-local structure: an `@extend` target that does not resolve to a
/// declared placeholder/class **in this file** is flagged.
///
/// Scope and non-over-correction:
/// - `!optional` targets are NEVER flagged — dart-sass permits a missing optional extend, and
///   omena already (correctly) emitted nothing for them, so the flag is honored here.
/// - A placeholder target is checked only against declared placeholders; a class target only
///   against declared classes (Sass keeps the two namespaces distinct).
/// - This is file-local (single-file surface), like the `missingSassSymbol` companion. A target
///   declared in another file reachable via `@use`/`@forward`/`@import` is NOT yet validated here,
///   so cross-file `@extend` resolution is out of scope for v0 (recorded as remaining) — that keeps
///   the rule from inventing a false positive for a placeholder defined in an imported partial.
pub fn summarize_omena_query_missing_extend_target_diagnostics(
    style_uri: &str,
    source: &str,
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let dialect = omena_parser_dialect_for_style_path(style_uri);
    if !matches!(
        dialect,
        OmenaParserStyleDialect::Scss | OmenaParserStyleDialect::Sass
    ) {
        return Vec::new();
    }

    let facts = collect_omena_query_omena_parser_style_facts_raw(source, dialect);
    if facts.extend_targets.is_empty() {
        return Vec::new();
    }

    let mut declared_placeholders = BTreeSet::new();
    let mut declared_classes = BTreeSet::new();
    for selector in &facts.selectors {
        match selector.kind {
            ParsedSelectorFactKind::Placeholder => {
                declared_placeholders.insert(selector.name.clone());
            }
            ParsedSelectorFactKind::Class => {
                declared_classes.insert(selector.name.clone());
            }
            ParsedSelectorFactKind::Id => {}
        }
    }

    let mut emitted = BTreeSet::new();
    let mut diagnostics = Vec::new();
    for target in &facts.extend_targets {
        // An optional extend (`@extend %x !optional`) is allowed to miss — never flag it.
        if target.optional {
            continue;
        }
        let (resolved, label) = match target.kind {
            ParsedExtendTargetFactKind::Placeholder => (
                declared_placeholders.contains(&target.name),
                format!("%{}", target.name),
            ),
            ParsedExtendTargetFactKind::Class => (
                declared_classes.contains(&target.name),
                format!(".{}", target.name),
            ),
        };
        if resolved {
            continue;
        }
        let start: u32 = target.range.start().into();
        let end: u32 = target.range.end().into();
        let byte_span = ParserByteSpanV0 {
            start: start as usize,
            end: end as usize,
        };
        if !emitted.insert((byte_span.start, byte_span.end)) {
            continue;
        }
        diagnostics.push(OmenaQueryStyleDiagnosticV0 {
            code: "missingExtendTarget",
            severity: "error",
            provenance: vec![
                "omena-parser.extend-target-facts",
                "omena-query.missing-extend-target-diagnostics",
            ],
            range: parser_range_for_byte_span(source, byte_span),
            message: format!(
                "@extend target '{label}' does not exist in this file. dart-sass rejects this as a hard error."
            ),
            tags: Vec::new(),
            create_custom_property: None,
        });
    }

    diagnostics
}

/// RFC-0007-E1 (#45) workspace variant: like the file-local rule, but a target is only flagged when
/// it is absent from the placeholders/classes declared in files **reachable from the target's
/// `@use`/`@forward`/`@import` import graph** (the target file plus its transitive module-graph
/// closure), so a cross-file `@extend` of a placeholder defined in an imported partial is never a
/// false positive — while an `@extend` of a placeholder that only exists in an UNRELATED,
/// non-imported file still fires (dart-sass only sees declarations the loaded modules bring into
/// scope, never the whole corpus). Optional extends are skipped.
fn summarize_omena_query_missing_extend_target_diagnostics_for_workspace(
    target_style_path: &str,
    style_sources: &[OmenaQueryStyleSourceInputV0],
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let Some(target) = style_sources
        .iter()
        .find(|source| source.style_path == target_style_path)
    else {
        return Vec::new();
    };
    let dialect = omena_parser_dialect_for_style_path(target_style_path);
    if !matches!(
        dialect,
        OmenaParserStyleDialect::Scss | OmenaParserStyleDialect::Sass
    ) {
        return Vec::new();
    }

    let target_facts =
        collect_omena_query_omena_parser_style_facts_raw(target.style_source.as_str(), dialect);
    if target_facts.extend_targets.is_empty() {
        return Vec::new();
    }

    // Resolve the import graph so visibility tracks only the modules the target actually loads,
    // not the whole corpus. `summarize_sass_module_cross_file_resolution` already gives us the
    // resolved edges; `collect_sass_module_graph_reachable_style_paths` walks them from the target.
    let style_source_refs = style_sources
        .iter()
        .map(|source| (source.style_path.as_str(), source.style_source.as_str()))
        .collect::<Vec<_>>();
    let style_fact_entries = collect_omena_query_style_fact_entries(style_source_refs.as_slice());
    let resolution = summarize_sass_module_cross_file_resolution(&style_fact_entries, &[]);
    let reachable_paths =
        collect_sass_module_graph_reachable_style_paths(target_style_path, &resolution);

    // Declared placeholders/classes from the target plus every file reachable through its
    // `@use`/`@forward`/`@import` graph. A placeholder declared only in an unrelated, non-imported
    // file is NOT in this set, so an `@extend` of it correctly fires (matching dart-sass scope).
    let mut declared_placeholders = BTreeSet::new();
    let mut declared_classes = BTreeSet::new();
    for source in style_sources {
        if !reachable_paths.contains(source.style_path.as_str()) {
            continue;
        }
        let facts = collect_omena_query_omena_parser_style_facts_raw(
            source.style_source.as_str(),
            omena_parser_dialect_for_style_path(source.style_path.as_str()),
        );
        for selector in facts.selectors {
            match selector.kind {
                ParsedSelectorFactKind::Placeholder => {
                    declared_placeholders.insert(selector.name);
                }
                ParsedSelectorFactKind::Class => {
                    declared_classes.insert(selector.name);
                }
                ParsedSelectorFactKind::Id => {}
            }
        }
    }

    let mut emitted = BTreeSet::new();
    let mut diagnostics = Vec::new();
    for extend_target in &target_facts.extend_targets {
        if extend_target.optional {
            continue;
        }
        let (resolved, label) = match extend_target.kind {
            ParsedExtendTargetFactKind::Placeholder => (
                declared_placeholders.contains(&extend_target.name),
                format!("%{}", extend_target.name),
            ),
            ParsedExtendTargetFactKind::Class => (
                declared_classes.contains(&extend_target.name),
                format!(".{}", extend_target.name),
            ),
        };
        if resolved {
            continue;
        }
        let start: u32 = extend_target.range.start().into();
        let end: u32 = extend_target.range.end().into();
        let byte_span = ParserByteSpanV0 {
            start: start as usize,
            end: end as usize,
        };
        if !emitted.insert((byte_span.start, byte_span.end)) {
            continue;
        }
        diagnostics.push(OmenaQueryStyleDiagnosticV0 {
            code: "missingExtendTarget",
            severity: "error",
            provenance: vec![
                "omena-parser.extend-target-facts",
                "omena-query.missing-extend-target-diagnostics",
            ],
            range: parser_range_for_byte_span(target.style_source.as_str(), byte_span),
            message: format!(
                "@extend target '{label}' does not exist in the visible Sass module graph. dart-sass rejects this as a hard error."
            ),
            tags: Vec::new(),
            create_custom_property: None,
        });
    }

    diagnostics
}

/// RFC-0007-E1 (#45): the set of in-graph style paths reachable from `target_style_path` through
/// the resolved `@use`/`@forward`/`@import` edges (the target itself plus its transitive module-graph
/// closure). Used to scope cross-file `@extend` visibility to the modules the target actually loads
/// rather than the whole corpus, so a placeholder declared only in an unrelated file is not
/// (wrongly) treated as visible. Cycle-safe: each path is visited at most once.
fn collect_sass_module_graph_reachable_style_paths<'a>(
    target_style_path: &'a str,
    resolution: &'a OmenaQuerySassModuleCrossFileResolutionV0,
) -> BTreeSet<&'a str> {
    let mut reachable = BTreeSet::new();
    let mut stack = vec![target_style_path];
    while let Some(current) = stack.pop() {
        if !reachable.insert(current) {
            continue;
        }
        for edge in resolution
            .edges
            .iter()
            .filter(|edge| edge.from_style_path == current && edge.status == "resolved")
        {
            if let Some(next) = edge.resolved_style_path.as_deref() {
                stack.push(next);
            }
        }
    }
    reachable
}

/// Surface the real cross-file replica-ensemble inconsistency diagnostic in the
/// workspace style path (#33 / L0 / L2).
///
/// When the target file's resolved `@use`/`@forward`/`@import` graph closure spans
/// two or more in-graph CSS modules, each module is treated as one *replica* of the
/// shared design surface and its REAL per-`(selector, property)` cascade winners are
/// extracted via `collect_query_replica_ensemble_site_outcomes` (genuine
/// `cascade_property` ranking over the parsed declarations — no fabricated
/// snapshots). `omena-ensemble`'s `build_cross_file_inconsistency_report` then
/// computes the replica overlap-Q distribution over the modules' winners and the
/// SBM detectability over the resolved module graph; the report's overlap statistics
/// (recommendation, `meanQ`, genuine disagreement-pair count) drive the registered
/// `replicaEnsembleInconsistency` checker rule through
/// `run_omena_query_checker_replica_ensemble_gate_v0`.
///
/// The diagnostic depends entirely on the overlap statistics over the real winners:
/// a workspace whose modules agree on every shared `(selector, property)` outcome
/// has `meanQ == 1.0`, zero disagreement pairs, and a `noActionNeeded`
/// recommendation, so the checker rule filters the report out and nothing is
/// surfaced; a workspace where two modules resolve a shared site to different
/// winning values drops `meanQ` below one and surfaces the diagnostic. The report is
/// whole-graph, so the single emitted diagnostic is anchored on the target file's
/// whole-file span.
fn summarize_omena_query_replica_ensemble_inconsistency_diagnostics_for_workspace(
    target_style_path: &str,
    style_sources: &[OmenaQueryStyleSourceInputV0],
    package_manifests: &[OmenaQueryStylePackageManifestV0],
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let Some(target) = style_sources
        .iter()
        .find(|source| source.style_path == target_style_path)
    else {
        return Vec::new();
    };

    let style_source_refs = style_sources
        .iter()
        .map(|source| (source.style_path.as_str(), source.style_source.as_str()))
        .collect::<Vec<_>>();
    let style_fact_entries = collect_omena_query_style_fact_entries(style_source_refs.as_slice());
    let resolution =
        summarize_sass_module_cross_file_resolution(&style_fact_entries, package_manifests);
    let reachable_paths =
        collect_sass_module_graph_reachable_style_paths(target_style_path, &resolution);

    // A single-module closure is not an ensemble: there is no second replica to
    // overlap against, so there is no cross-file inconsistency to surface.
    if reachable_paths.len() < 2 {
        return Vec::new();
    }

    // Build one replica per in-graph module from its REAL cascade winners. A module
    // that declares no comparable definite cascade site contributes an empty replica
    // (it cannot agree or disagree with anything), so drop it from the ensemble.
    let replicas = style_sources
        .iter()
        .filter(|source| reachable_paths.contains(source.style_path.as_str()))
        .filter_map(|source| {
            let sites = collect_query_replica_ensemble_site_outcomes(source.style_source.as_str());
            if sites.is_empty() {
                return None;
            }
            Some(ReplicaSnapshotV0 {
                schema_version: REPLICA_ENSEMBLE_SCHEMA_VERSION_V0,
                product: "omena-ensemble.replica-snapshot",
                layer_marker: REPLICA_ENSEMBLE_LAYER_MARKER_V0,
                feature_gate: REPLICA_ENSEMBLE_FEATURE_GATE_V0,
                path: source.style_path.clone(),
                sites,
            })
        })
        .collect::<Vec<_>>();

    // Fewer than two non-empty replicas => no shared cascade surface to compare.
    if replicas.len() < 2 {
        return Vec::new();
    }

    let module_graph = replica_ensemble_module_graph_from_resolution(
        target_style_path,
        &resolution,
        &reachable_paths,
        &replicas,
    );
    let report = build_cross_file_inconsistency_report(
        target_style_path,
        replicas.clone(),
        &module_graph,
        OutcomeMode::DefiniteOnly,
        ReportOptionsV0::default(),
        None,
    );

    // Genuine disagreement count: only replica pairs whose computed overlap-Q is
    // strictly below 1.0 actually disagree on a shared cascade outcome. (The report's
    // `top_disagreement_pairs` keeps the lowest-Q pairs even when every pair fully
    // agrees, so counting that list directly would fire on a consistent ensemble.)
    let genuine_disagreement_pair_count = report
        .top_disagreement_pairs
        .iter()
        .filter(|pair| pair.shared_site_count > 0 && pair.overlap_q < 1.0)
        .count();
    let recommendation = replica_ensemble_recommendation_name(report.recommendation);

    let gate =
        run_omena_query_checker_replica_ensemble_gate_v0(OmenaCheckerReplicaEnsembleInputV0 {
            reports: vec![OmenaCheckerReplicaEnsembleReportInputV0 {
                workspace_root: target_style_path.to_string(),
                recommendation: recommendation.to_string(),
                mean_q: report.distribution.mean_q,
                variance_q: report.distribution.variance_q,
                top_disagreement_pair_count: genuine_disagreement_pair_count,
            }],
        });
    if !gate.enforcement_passed {
        return Vec::new();
    }

    let whole_file_range = parser_range_for_byte_span(
        target.style_source.as_str(),
        ParserByteSpanV0 {
            start: 0,
            end: target.style_source.len(),
        },
    );

    gate.evaluations
        .into_iter()
        .map(|evaluation| {
            let mut provenance = vec![
                "omena-query-checker-orchestrator.replica-ensemble-gate",
                "omena-checker.replica-ensemble-rules",
                "omena-ensemble.cross-file-inconsistency-report",
                "omena-query.cross-file-replica-ensemble",
            ];
            provenance.extend(evaluation.mechanism_products.iter().copied());
            OmenaQueryStyleDiagnosticV0 {
                code: "replicaEnsembleInconsistency",
                severity: "hint",
                provenance,
                range: whole_file_range,
                message: evaluation.message,
                tags: Vec::new(),
                create_custom_property: None,
            }
        })
        .collect()
}

/// Build the replica-ensemble module graph from the target's resolved import graph:
/// nodes are the in-graph modules that contributed a non-empty replica, and edges
/// are the resolved `@use`/`@forward`/`@import` edges between those modules. This is
/// the real dependency structure the SBM detectability reasons over — not a
/// synthesized clique.
fn replica_ensemble_module_graph_from_resolution(
    workspace_root: &str,
    resolution: &OmenaQuerySassModuleCrossFileResolutionV0,
    reachable_paths: &BTreeSet<&str>,
    replicas: &[ReplicaSnapshotV0],
) -> ModuleGraphV0 {
    let nodes = replicas
        .iter()
        .map(|replica| replica.path.clone())
        .collect::<Vec<_>>();
    let node_set = nodes.iter().map(String::as_str).collect::<BTreeSet<_>>();

    let edges = resolution
        .edges
        .iter()
        .filter(|edge| edge.status == "resolved")
        .filter(|edge| reachable_paths.contains(edge.from_style_path.as_str()))
        .filter_map(|edge| {
            let to = edge.resolved_style_path.as_deref()?;
            if node_set.contains(edge.from_style_path.as_str()) && node_set.contains(to) {
                Some(ModuleGraphEdgeV0 {
                    schema_version: REPLICA_ENSEMBLE_SCHEMA_VERSION_V0,
                    product: "omena-ensemble.module-graph-edge",
                    layer_marker: REPLICA_ENSEMBLE_LAYER_MARKER_V0,
                    feature_gate: REPLICA_ENSEMBLE_FEATURE_GATE_V0,
                    from_module: edge.from_style_path.clone(),
                    to_module: to.to_string(),
                    edge_kind: "resolvedModuleEdge",
                })
            } else {
                None
            }
        })
        .collect::<Vec<_>>();

    ModuleGraphV0 {
        schema_version: REPLICA_ENSEMBLE_SCHEMA_VERSION_V0,
        product: "omena-ensemble.module-graph",
        layer_marker: REPLICA_ENSEMBLE_LAYER_MARKER_V0,
        feature_gate: REPLICA_ENSEMBLE_FEATURE_GATE_V0,
        workspace_root: workspace_root.to_string(),
        nodes,
        edges,
    }
}

fn replica_ensemble_recommendation_name(recommendation: ReportRecommendation) -> &'static str {
    match recommendation {
        ReportRecommendation::NoActionNeeded => "noActionNeeded",
        ReportRecommendation::InvestigateRsbBroken => "investigateRsbBroken",
        ReportRecommendation::UndetectablePhase => "undetectablePhase",
    }
}

pub fn summarize_omena_query_sass_import_deprecation_hints(
    style_uri: &str,
    source: &str,
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let dialect = omena_parser_dialect_for_style_path(style_uri);
    if !matches!(
        dialect,
        OmenaParserStyleDialect::Scss | OmenaParserStyleDialect::Sass
    ) {
        return Vec::new();
    }

    let facts = collect_omena_query_omena_parser_style_facts_raw(source, dialect);
    facts
        .sass_module_edges
        .into_iter()
        .filter(|edge| edge.kind == ParsedSassModuleEdgeFactKind::Import)
        // Sass deprecated `@import` only for Sass partials. CSS-form imports
        // (`url(...)`, `.css` targets, protocol/`//` URLs, media-qualified targets)
        // are explicitly kept and must NOT be flagged. Classify per-edge (each
        // comma-peer target is its own Import edge), so a partial that shares a
        // multi-target statement with a CSS import still warns. (RFC-0007 D1, #44)
        .filter(|edge| !edge.media_qualified && !sass_import_is_plain_css(edge.source.as_str()))
        .map(|edge| {
            let start: u32 = edge.range.start().into();
            let end: u32 = edge.range.end().into();
            OmenaQueryStyleDiagnosticV0 {
                code: "deprecatedSassImport",
                severity: "information",
                provenance: vec![
                    "omena-parser.sass-module-edges",
                    "omena-query.sass-import-deprecation-hints",
                ],
                range: parser_range_for_byte_span(
                    source,
                    ParserByteSpanV0 {
                        start: start as usize,
                        end: end as usize,
                    },
                ),
                message: "Sass @import is deprecated; prefer @use or @forward.".to_string(),
                tags: vec![LSP_DIAGNOSTIC_TAG_DEPRECATED],
                create_custom_property: None,
            }
        })
        .collect()
}

/// Classify an `@import` target as plain CSS, which Sass explicitly keeps (NOT
/// deprecated). Operates on the `source` already captured in the Import edge fact,
/// so cross-file resolution (the edge collector) is unaffected.
///
/// Detects the CSS-form imports that are recoverable from the edge fact alone:
/// - `url(...)` (unquoted url form, source retains the `url(` wrapper),
/// - a `.css` extension target,
/// - protocol (`scheme://`) or scheme-relative (`//host/...`) URLs.
///
/// The media-qualified form (`@import "foo" screen`) is now handled upstream via the
/// `media_qualified` flag on the Import edge (captured in the parser, where the
/// qualifier token is still available), so it is filtered out before this predicate
/// runs and does not need detecting here. (RFC-0007 D1, #44)
///
/// Necessary-not-sufficient: the quoted-url-without-`.css` form (`@import url("foo")`,
/// whose `url(...)` wrapper is lost during tokenization) remains NOT distinguishable
/// from a Sass partial at the edge-fact level, so it is still treated as a Sass-form
/// import here.
fn sass_import_is_plain_css(source: &str) -> bool {
    let trimmed = source.trim();
    let lower = trimmed.to_ascii_lowercase();
    // Unquoted `url(...)` form: the source still carries the `url(` prefix.
    if lower.starts_with("url(") {
        return true;
    }
    // Protocol (`https://`, `http://`, `data:`-less `scheme://`) and scheme-relative
    // (`//cdn.example/...`) URLs are always plain CSS.
    if lower.starts_with("//") || lower.contains("://") {
        return true;
    }
    // Explicit `.css` extension target.
    if lower.ends_with(".css") {
        return true;
    }
    false
}

pub fn summarize_omena_query_missing_sass_symbol_diagnostics_for_workspace(
    target_style_path: &str,
    style_sources: &[OmenaQueryStyleSourceInputV0],
    package_manifests: &[OmenaQueryStylePackageManifestV0],
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    summarize_omena_query_missing_sass_symbol_diagnostics_for_workspace_with_sifs(
        target_style_path,
        style_sources,
        package_manifests,
        &[],
    )
}

fn summarize_omena_query_missing_sass_symbol_diagnostics_for_workspace_with_sifs(
    target_style_path: &str,
    style_sources: &[OmenaQueryStyleSourceInputV0],
    package_manifests: &[OmenaQueryStylePackageManifestV0],
    external_sifs: &[OmenaQueryExternalSifInputV0],
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let Some(target) = style_sources
        .iter()
        .find(|source| source.style_path == target_style_path)
    else {
        return Vec::new();
    };
    let style_source_refs = style_sources
        .iter()
        .map(|source| (source.style_path.as_str(), source.style_source.as_str()))
        .collect::<Vec<_>>();
    let style_fact_entries = collect_omena_query_style_fact_entries(style_source_refs.as_slice());
    let facts_by_path = style_fact_entries
        .iter()
        .map(|entry| (entry.style_path.as_str(), &entry.facts))
        .collect::<BTreeMap<_, _>>();
    let resolution =
        summarize_sass_module_cross_file_resolution(&style_fact_entries, package_manifests);
    let visible_symbols = collect_visible_sass_symbol_keys(
        target_style_path,
        &facts_by_path,
        &resolution,
        external_sifs,
    );
    let facts = collect_omena_query_omena_parser_style_facts_raw(
        target.style_source.as_str(),
        omena_parser_dialect_for_style_path(target_style_path),
    );
    let mut emitted = BTreeSet::new();
    let mut diagnostics = Vec::new();

    for symbol in facts.sass_symbols {
        if !omena_query_sass_symbol_fact_kind_is_reference(symbol.kind) {
            continue;
        }
        let key = sass_symbol_key(
            symbol.symbol_kind,
            symbol.namespace.clone(),
            symbol.name.clone(),
        );
        if visible_symbols.contains(&key) {
            continue;
        }
        if is_omena_query_sass_builtin_symbol_reference_resolved(
            &facts.sass_module_edges,
            symbol.symbol_kind,
            symbol.namespace.as_deref(),
            symbol.name.as_str(),
        ) {
            continue;
        }

        let start: u32 = symbol.range.start().into();
        let end: u32 = symbol.range.end().into();
        let byte_span = ParserByteSpanV0 {
            start: start as usize,
            end: end as usize,
        };
        if !emitted.insert((
            symbol.symbol_kind,
            symbol.namespace.clone(),
            symbol.name.clone(),
            byte_span.start,
            byte_span.end,
        )) {
            continue;
        }
        diagnostics.push(OmenaQueryStyleDiagnosticV0 {
            code: "missingSassSymbol",
            severity: "warning",
            provenance: vec![
                "omena-parser.sass-symbol-facts",
                "omena-query.graph-aware-sass-diagnostics",
            ],
            range: parser_range_for_byte_span(target.style_source.as_str(), byte_span),
            message: format!(
                "{} not found in the visible Sass module graph.",
                format_query_sass_symbol_label(symbol.symbol_kind, symbol.name.as_str())
            ),
            tags: Vec::new(),
            create_custom_property: None,
        });
    }

    diagnostics
}

/// RFC-0007-E2 (#45): `@use`/`@forward` module cycles. dart-sass hard-errors on a module loop
/// (`a.scss: @use 'b'`; `b.scss: @use 'a'`) or a self-loop (`@use './self'`); omena was silent.
///
/// The cycle facts are ALREADY computed — `summarize_sass_module_cross_file_resolution` fills
/// `resolution.cycles` (with `cycle_detection_ready: true`), but no diagnostic ever read them.
/// This is pure last-mile consumer wiring: read the existing `cycles`, keep the ones whose path
/// includes the target file, and anchor one diagnostic per such cycle to the outgoing
/// `@use`/`@forward`/`@import` statement in the target that closes the loop.
///
/// Anchoring: each cycle `path` is a node list `[A, B, …, A]`; for the target `A` the next node is
/// the module it loads (`B`). We map back to the resolved edge `from == target && resolved == B`,
/// then to the parser fact carrying its source range, so the squiggle lands on the actual
/// `@use 'b'` statement rather than the whole file. A cycle where the target is not a participant
/// (only reachable *through* a cycle) emits nothing here — it is reported on the file that owns the
/// looping statement, so each cycle is surfaced exactly once per participating edge.
fn summarize_omena_query_sass_use_cycle_diagnostics_for_workspace(
    target_style_path: &str,
    style_sources: &[OmenaQueryStyleSourceInputV0],
    package_manifests: &[OmenaQueryStylePackageManifestV0],
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let Some(target) = style_sources
        .iter()
        .find(|source| source.style_path == target_style_path)
    else {
        return Vec::new();
    };
    let style_source_refs = style_sources
        .iter()
        .map(|source| (source.style_path.as_str(), source.style_source.as_str()))
        .collect::<Vec<_>>();
    let style_fact_entries = collect_omena_query_style_fact_entries(style_source_refs.as_slice());
    let resolution =
        summarize_sass_module_cross_file_resolution(&style_fact_entries, package_manifests);
    if resolution.cycles.is_empty() {
        return Vec::new();
    }

    // Parser facts for the target file: the resolution edges carry the loop topology but not source
    // ranges, so we re-derive the `@use`/`@forward`/`@import` statement span by matching the edge's
    // `source` text back to the fact that produced it.
    let target_facts = collect_omena_query_omena_parser_style_facts_raw(
        target.style_source.as_str(),
        omena_parser_dialect_for_style_path(target_style_path),
    );

    let mut emitted = BTreeSet::new();
    let mut diagnostics = Vec::new();

    for cycle in &resolution.cycles {
        // The target participates iff it appears in the loop node list.
        if !cycle.path.iter().any(|node| node == target_style_path) {
            continue;
        }
        // `RawAllPaths` emits every rotation of the same loop (`[a, b, a]` and `[b, a, b]`), so
        // dedupe on a rotation-invariant key before emitting, otherwise `a <-> b` would surface
        // twice on `a.scss`. The repeated closing node is dropped first, then we key on the
        // lexicographically-smallest rotation of the node ring.
        let canonical_cycle = canonical_sass_module_cycle(&cycle.path);
        // The next node after the target in the loop is the module the target loads to close it.
        // A self-loop (`@use './self'`) has the target as both the current and next node.
        let Some(next_module) = cycle
            .path
            .windows(2)
            .find(|window| window[0] == target_style_path)
            .map(|window| window[1].clone())
        else {
            continue;
        };
        // Find the resolved edge target -> next_module to recover the `@use`/`@forward` source text.
        let Some(loop_edge) = resolution.edges.iter().find(|edge| {
            edge.from_style_path == target_style_path
                && edge.resolved_style_path.as_deref() == Some(next_module.as_str())
        }) else {
            continue;
        };
        // Map back to the parser fact carrying the statement range (match on source text + kind).
        let Some(fact) = target_facts.sass_module_edges.iter().find(|fact| {
            fact.source == loop_edge.source
                && parsed_sass_module_edge_fact_kind_matches(fact.kind, loop_edge.edge_kind)
        }) else {
            continue;
        };
        let start: u32 = fact.range.start().into();
        let end: u32 = fact.range.end().into();
        let byte_span = ParserByteSpanV0 {
            start: start as usize,
            end: end as usize,
        };
        if !emitted.insert((byte_span.start, byte_span.end, canonical_cycle.clone())) {
            continue;
        }
        diagnostics.push(OmenaQueryStyleDiagnosticV0 {
            code: "sassUseCycle",
            severity: "error",
            provenance: vec![
                "omena-query.sass-module-cross-file-resolution",
                "omena-query.sass-use-cycle-diagnostics",
            ],
            range: parser_range_for_byte_span(target.style_source.as_str(), byte_span),
            message: format!(
                "Sass module loop: {}. dart-sass rejects this as a hard error.",
                render_sass_module_cycle_from(&canonical_cycle, target_style_path)
            ),
            tags: Vec::new(),
            create_custom_property: None,
        });
    }

    diagnostics
}

/// RFC-0007-E3 (#45): an unresolved Sass module reference to a **workspace-local** path.
/// dart-sass hard-errors on `@import './missing'` / `@use '../gone'` (file not found); omena was
/// silent — only `deprecatedSassImport` ever surfaced, and the `missingModule` rule existed only
/// for the JS/TS-imports-CSS-Modules direction.
///
/// The resolution facts are ALREADY computed: `summarize_sass_module_cross_file_resolution` marks
/// each edge `status == "unresolved"` (resolver kind `unresolved`), `"external"` (the resolver
/// kind `externalIgnored` for `sass:`/`http(s)://`), or `"resolved"`. We read the existing
/// `unresolved` edges and emit a `missingModule` diagnostic, but ONLY for relative/absolute
/// specifiers (`./`, `../`, `/`):
///
/// - A relative/absolute specifier is unambiguously a workspace-local file reference — it can never
///   be an `npm` package or a `sass:` builtin — so an unresolved one is a genuine file-not-found
///   error, matching dart-sass.
/// - A *bare* specifier (`'no-such-file'`, `'bootstrap'`) is left untouched: it is indistinguishable
///   at this layer from an external bare-package import that has no SIF in scope (the #32/#34
///   external-wiring known limitation, NOT an error in `Ignored` mode). Flagging it would regress
///   the external case, so bare unresolved partials stay deferred (reported as a remaining item).
/// - `status == "external"` edges (`sass:`/`http(s)://`) are never flagged.
///
/// Anchoring mirrors the use-cycle rule: re-derive the statement span from the parser
/// `sass_module_edges` fact whose `source` + kind match the resolution edge.
fn summarize_omena_query_unresolved_sass_import_diagnostics_for_workspace(
    target_style_path: &str,
    style_sources: &[OmenaQueryStyleSourceInputV0],
    package_manifests: &[OmenaQueryStylePackageManifestV0],
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let Some(target) = style_sources
        .iter()
        .find(|source| source.style_path == target_style_path)
    else {
        return Vec::new();
    };
    let style_source_refs = style_sources
        .iter()
        .map(|source| (source.style_path.as_str(), source.style_source.as_str()))
        .collect::<Vec<_>>();
    let style_fact_entries = collect_omena_query_style_fact_entries(style_source_refs.as_slice());
    let resolution =
        summarize_sass_module_cross_file_resolution(&style_fact_entries, package_manifests);

    let target_facts = collect_omena_query_omena_parser_style_facts_raw(
        target.style_source.as_str(),
        omena_parser_dialect_for_style_path(target_style_path),
    );

    let mut emitted = BTreeSet::new();
    let mut diagnostics = Vec::new();

    for edge in resolution.edges.iter().filter(|edge| {
        edge.from_style_path == target_style_path
            && edge.status == "unresolved"
            && sass_module_source_is_workspace_local(edge.source.as_str())
    }) {
        let Some(fact) = target_facts.sass_module_edges.iter().find(|fact| {
            fact.source == edge.source
                && parsed_sass_module_edge_fact_kind_matches(fact.kind, edge.edge_kind)
        }) else {
            continue;
        };
        let start: u32 = fact.range.start().into();
        let end: u32 = fact.range.end().into();
        let byte_span = ParserByteSpanV0 {
            start: start as usize,
            end: end as usize,
        };
        if !emitted.insert((byte_span.start, byte_span.end)) {
            continue;
        }
        diagnostics.push(OmenaQueryStyleDiagnosticV0 {
            code: "missingModule",
            severity: "error",
            provenance: vec![
                "omena-query.sass-module-cross-file-resolution",
                "omena-query.unresolved-sass-import-diagnostics",
            ],
            range: parser_range_for_byte_span(target.style_source.as_str(), byte_span),
            message: format!(
                "Cannot resolve Sass module '{}'. dart-sass rejects this as a hard error.",
                edge.source
            ),
            tags: Vec::new(),
            create_custom_property: None,
        });
    }

    diagnostics
}

/// A Sass module specifier is workspace-local — and so a genuine file-not-found error when it does
/// not resolve — iff it is relative (`./`, `../`) or root-absolute (`/`). Bare specifiers
/// (`'partial'`, `'pkg'`) are excluded: they cannot be distinguished here from an external
/// bare-package import with no SIF in scope (RFC-0007-E3, #45).
fn sass_module_source_is_workspace_local(source: &str) -> bool {
    let trimmed = source.trim();
    trimmed.starts_with("./") || trimmed.starts_with("../") || trimmed.starts_with('/')
}

fn parsed_sass_module_edge_fact_kind_matches(
    fact_kind: ParsedSassModuleEdgeFactKind,
    edge_kind: &str,
) -> bool {
    matches!(
        (fact_kind, edge_kind),
        (ParsedSassModuleEdgeFactKind::Use, "sassUse")
            | (ParsedSassModuleEdgeFactKind::Forward, "sassForward")
            | (ParsedSassModuleEdgeFactKind::Import, "sassImport")
    )
}

/// Reduce a cycle `path` (a node ring whose first and last entries repeat, e.g. `[a, b, a]`) to a
/// rotation-invariant key: drop the repeated closing node, then return the lexicographically
/// smallest rotation. Two rotations of the same loop (`[a, b, a]` / `[b, a, b]`) collapse to one
/// key, so each distinct loop is surfaced exactly once per anchoring edge. A self-loop `[a, a]`
/// reduces to `[a]`.
fn canonical_sass_module_cycle(path: &[String]) -> Vec<String> {
    let ring: &[String] = match path.split_last() {
        Some((last, head)) if Some(last) == path.first() && !head.is_empty() => head,
        _ => path,
    };
    if ring.is_empty() {
        return path.to_vec();
    }
    let len = ring.len();
    (0..len)
        .map(|offset| {
            (0..len)
                .map(|index| ring[(offset + index) % len].clone())
                .collect::<Vec<_>>()
        })
        .min()
        .unwrap_or_else(|| ring.to_vec())
}

/// Render a canonical cycle ring as a closed `start -> … -> start` path beginning at `start`, so
/// each participating file describes the loop from its own perspective. `start` is guaranteed to be
/// in the ring by the caller (the target participates in the cycle).
fn render_sass_module_cycle_from(canonical_cycle: &[String], start: &str) -> String {
    let len = canonical_cycle.len();
    let begin = canonical_cycle
        .iter()
        .position(|node| node == start)
        .unwrap_or(0);
    let mut ordered = (0..len)
        .map(|index| canonical_cycle[(begin + index) % len].clone())
        .collect::<Vec<_>>();
    // Re-close the ring so the loop reads `a -> b -> a` (or `a -> a` for a self-loop).
    ordered.push(canonical_cycle[begin].clone());
    ordered.join(" -> ")
}

pub fn summarize_omena_query_style_diagnostics_for_file(
    style_uri: &str,
    source: &str,
    candidates: &[OmenaQueryStyleHoverCandidateV0],
) -> OmenaQueryStyleDiagnosticsForFileV0 {
    summarize_omena_query_style_diagnostics_for_file_with_deep_analysis(
        style_uri, source, candidates, false,
    )
}

/// File-level diagnostics summary with an explicit opt-in deep-analysis switch.
/// `deep_analysis == false` (the default LSP/CLI surface) keeps only the product
/// cascade diagnostics; `deep_analysis == true` surfaces the rg-flow / categorical
/// theory hints, deduplicated against `circularVar`.
pub fn summarize_omena_query_style_diagnostics_for_file_with_deep_analysis(
    style_uri: &str,
    source: &str,
    candidates: &[OmenaQueryStyleHoverCandidateV0],
    deep_analysis: bool,
) -> OmenaQueryStyleDiagnosticsForFileV0 {
    let mut diagnostics =
        summarize_omena_query_missing_custom_property_diagnostics(style_uri, source, candidates);
    diagnostics.extend(
        summarize_omena_query_cascade_aware_style_diagnostics_with_deep_analysis(
            style_uri,
            source,
            candidates,
            deep_analysis,
        ),
    );
    diagnostics.extend(summarize_omena_query_missing_keyframes_diagnostics(
        style_uri, source,
    ));
    diagnostics.extend(summarize_omena_query_sass_import_deprecation_hints(
        style_uri, source,
    ));
    diagnostics.extend(summarize_omena_query_missing_sass_symbol_diagnostics(
        style_uri, source,
    ));
    diagnostics.extend(summarize_omena_query_missing_extend_target_diagnostics(
        style_uri, source,
    ));
    apply_omena_query_checker_product_gate_to_style_diagnostics(&mut diagnostics);
    let mut summary = OmenaQueryStyleDiagnosticsForFileV0 {
        schema_version: "0",
        product: "omena-query.diagnostics-for-file",
        file_uri: style_uri.to_string(),
        file_kind: "style",
        diagnostic_count: diagnostics.len(),
        diagnostics,
        ready_surfaces: vec![
            "missingCustomPropertyDiagnostics",
            "cascadeAwareDiagnostics",
            "missingKeyframesDiagnostics",
            "sassImportDeprecationHints",
            "missingSassSymbolDiagnostics",
            "missingExtendTargetDiagnostics",
            "checkerProductDiagnosticGate",
        ],
    };
    apply_omena_query_style_diagnostic_suppressions(source, &mut summary);
    summary
}

/// RFC-0007-F (#46): single-file `style-diagnostics` (no `--source`) used to skip composes-target
/// validation entirely, so a bare invocation and one with any unrelated `--source` produced
/// different diagnostics for the same file. This variant augments the single-file summary with the
/// composes outcomes that are fully resolvable without cross-file context — only `composes: x`
/// (Local edges) against the file's own selectors. Global edges produce nothing and External edges
/// (`composes: x from './other'`) are deliberately left to the `--source`-backed workspace path, so
/// no false `missingComposedSelector`/`missingComposedModule` is invented for an unseen sibling.
pub fn summarize_omena_query_style_diagnostics_for_file_with_local_composes(
    style_uri: &str,
    source: &str,
    candidates: &[OmenaQueryStyleHoverCandidateV0],
) -> OmenaQueryStyleDiagnosticsForFileV0 {
    summarize_omena_query_style_diagnostics_for_file_with_local_composes_and_deep_analysis(
        style_uri, source, candidates, false,
    )
}

/// Single-file (local composes) diagnostics summary with an explicit opt-in
/// deep-analysis switch. `deep_analysis == false` (the default surface) keeps only
/// the product cascade diagnostics; `deep_analysis == true` surfaces the rg-flow /
/// categorical theory hints, deduplicated against `circularVar`.
pub fn summarize_omena_query_style_diagnostics_for_file_with_local_composes_and_deep_analysis(
    style_uri: &str,
    source: &str,
    candidates: &[OmenaQueryStyleHoverCandidateV0],
    deep_analysis: bool,
) -> OmenaQueryStyleDiagnosticsForFileV0 {
    let mut summary = summarize_omena_query_style_diagnostics_for_file_with_deep_analysis(
        style_uri,
        source,
        candidates,
        deep_analysis,
    );
    let mut local_composes =
        summarize_omena_query_css_modules_local_composes_style_diagnostics(style_uri, source);
    apply_omena_query_checker_product_gate_to_style_diagnostics(&mut local_composes);
    if !local_composes.is_empty() {
        summary.diagnostics.extend(local_composes);
        push_omena_query_ready_surface(
            &mut summary.ready_surfaces,
            "cssModulesComposesResolutionDiagnostics",
        );
        // Re-run suppressions so the appended composes diagnostics honour the same inline directives.
        apply_omena_query_style_diagnostic_suppressions(source, &mut summary);
        summary.diagnostic_count = summary.diagnostics.len();
    }
    summary
}

pub fn summarize_omena_query_style_diagnostics_for_workspace_file(
    target_style_path: &str,
    style_sources: &[OmenaQueryStyleSourceInputV0],
    source_documents: &[OmenaQuerySourceDocumentInputV0],
    package_manifests: &[OmenaQueryStylePackageManifestV0],
    classname_transform: Option<&str>,
) -> Option<OmenaQueryStyleDiagnosticsForFileV0> {
    summarize_omena_query_style_diagnostics_for_workspace_file_with_external_mode(
        target_style_path,
        style_sources,
        source_documents,
        package_manifests,
        classname_transform,
        OmenaQueryExternalModuleModeV0::Ignored,
    )
}

pub fn summarize_omena_query_style_diagnostics_for_workspace_file_with_external_mode(
    target_style_path: &str,
    style_sources: &[OmenaQueryStyleSourceInputV0],
    source_documents: &[OmenaQuerySourceDocumentInputV0],
    package_manifests: &[OmenaQueryStylePackageManifestV0],
    classname_transform: Option<&str>,
    external_mode: OmenaQueryExternalModuleModeV0,
) -> Option<OmenaQueryStyleDiagnosticsForFileV0> {
    summarize_omena_query_style_diagnostics_for_workspace_file_with_external_mode_and_sifs(
        target_style_path,
        style_sources,
        source_documents,
        package_manifests,
        classname_transform,
        external_mode,
        &[],
    )
}

pub fn summarize_omena_query_style_diagnostics_for_workspace_file_with_external_mode_and_sifs(
    target_style_path: &str,
    style_sources: &[OmenaQueryStyleSourceInputV0],
    source_documents: &[OmenaQuerySourceDocumentInputV0],
    package_manifests: &[OmenaQueryStylePackageManifestV0],
    classname_transform: Option<&str>,
    external_mode: OmenaQueryExternalModuleModeV0,
    external_sifs: &[OmenaQueryExternalSifInputV0],
) -> Option<OmenaQueryStyleDiagnosticsForFileV0> {
    summarize_omena_query_style_diagnostics_for_workspace_file_with_external_mode_and_sifs_and_resolution_inputs(
        target_style_path,
        style_sources,
        source_documents,
        package_manifests,
        classname_transform,
        external_mode,
        external_sifs,
        &OmenaQueryStyleResolutionInputsV0 {
            package_manifests: package_manifests.to_vec(),
            ..Default::default()
        },
    )
}

/// Workspace-file style diagnostics variant that additionally carries the workspace's
/// tsconfig/bundler path mappings. RFC-0007-J (#50): the unused-selector usage collector resolves
/// source-document style imports through these mappings so an alias import (`@/styles/a.module.scss`)
/// is attributed to its real module — matching the reference/goto path — instead of leaving every
/// selector dimmed `unusedSelector`. Path mappings only affect alias resolution; with empty mappings
/// the behaviour is byte-for-byte the no-mappings entry above.
#[allow(clippy::too_many_arguments)]
pub fn summarize_omena_query_style_diagnostics_for_workspace_file_with_external_mode_and_sifs_and_resolution_inputs(
    target_style_path: &str,
    style_sources: &[OmenaQueryStyleSourceInputV0],
    source_documents: &[OmenaQuerySourceDocumentInputV0],
    package_manifests: &[OmenaQueryStylePackageManifestV0],
    classname_transform: Option<&str>,
    external_mode: OmenaQueryExternalModuleModeV0,
    external_sifs: &[OmenaQueryExternalSifInputV0],
    resolution_inputs: &OmenaQueryStyleResolutionInputsV0,
) -> Option<OmenaQueryStyleDiagnosticsForFileV0> {
    let target = style_sources
        .iter()
        .find(|source| source.style_path == target_style_path)?;
    let candidates =
        summarize_omena_query_style_hover_candidates(target_style_path, &target.style_source)?;
    let mut summary = summarize_omena_query_style_diagnostics_for_file(
        target_style_path,
        &target.style_source,
        candidates.candidates.as_slice(),
    );
    summary
        .diagnostics
        .retain(|diagnostic| diagnostic.code != "missingSassSymbol");
    // RFC-0007-E1 (#45): the file-local `missingExtendTarget` rule cannot see a placeholder/class
    // declared in another in-graph file reachable via `@use`/`@forward`/`@import`, so it would
    // false-positive on a cross-file `@extend`. In workspace mode we drop the file-local result and
    // re-emit only those whose target is also absent from EVERY other in-graph style source — a
    // conservative cross-file-aware pass that keeps a genuinely-missing target flagged while never
    // inventing a false positive for a target defined in an imported partial. (Single-file surface
    // keeps the file-local rule unchanged.)
    summary
        .diagnostics
        .retain(|diagnostic| diagnostic.code != "missingExtendTarget");
    summary.diagnostics.extend(
        summarize_omena_query_missing_extend_target_diagnostics_for_workspace(
            target_style_path,
            style_sources,
        ),
    );
    summary.diagnostics.extend(
        summarize_omena_query_missing_sass_symbol_diagnostics_for_workspace_with_sifs(
            target_style_path,
            style_sources,
            package_manifests,
            external_sifs,
        ),
    );
    summary.diagnostics.extend(
        summarize_omena_query_css_modules_resolution_style_diagnostics(
            target_style_path,
            &target.style_source,
            style_sources,
            package_manifests,
        ),
    );
    summary.diagnostics.extend(
        summarize_omena_query_sass_use_cycle_diagnostics_for_workspace(
            target_style_path,
            style_sources,
            package_manifests,
        ),
    );
    summary.diagnostics.extend(
        summarize_omena_query_unresolved_sass_import_diagnostics_for_workspace(
            target_style_path,
            style_sources,
            package_manifests,
        ),
    );
    summary.diagnostics.extend(
        summarize_omena_query_unused_selector_style_diagnostics_with_path_mappings(
            target_style_path,
            &target.style_source,
            style_sources,
            source_documents,
            package_manifests,
            classname_transform,
            resolution_inputs.bundler_path_mappings.as_slice(),
            resolution_inputs.tsconfig_path_mappings.as_slice(),
        ),
    );
    summary.diagnostics.extend(
        summarize_omena_query_replica_ensemble_inconsistency_diagnostics_for_workspace(
            target_style_path,
            style_sources,
            package_manifests,
        ),
    );
    summary.diagnostic_count = summary.diagnostics.len();
    push_omena_query_ready_surface(
        &mut summary.ready_surfaces,
        "cssModulesComposesResolutionDiagnostics",
    );
    push_omena_query_ready_surface(
        &mut summary.ready_surfaces,
        "cssModulesValueResolutionDiagnostics",
    );
    push_omena_query_ready_surface(&mut summary.ready_surfaces, "unusedSelectorDiagnostics");
    push_omena_query_ready_surface(&mut summary.ready_surfaces, "sassUseCycleDiagnostics");
    push_omena_query_ready_surface(
        &mut summary.ready_surfaces,
        "unresolvedSassImportDiagnostics",
    );
    push_omena_query_ready_surface(
        &mut summary.ready_surfaces,
        "missingExtendTargetDiagnostics",
    );
    push_omena_query_ready_surface(
        &mut summary.ready_surfaces,
        "graphAwareSassSymbolDiagnostics",
    );
    push_omena_query_ready_surface(
        &mut summary.ready_surfaces,
        "crossFileReplicaEnsembleDiagnostics",
    );
    if external_mode == OmenaQueryExternalModuleModeV0::Sif {
        // RFC 0004 #28 / #35: the file-scoped `@omena-strict: <level>` sigil dials the
        // external-boundary lattice behaviour. Absent/malformed sigil => `Standard`, which
        // keeps every branch below a no-op (byte-for-byte identical to the un-sigiled flow).
        let strictness = parse_omena_query_style_strictness_level(&target.style_source);
        let top_any_external_symbol_ranges =
            collect_omena_query_external_top_any_sass_symbol_ranges(
                target_style_path,
                style_sources,
                package_manifests,
                external_sifs,
            );
        if strictness.suppresses_top_any_external_symbols() {
            summary.diagnostics.retain(|diagnostic| {
                diagnostic.code != "missingSassSymbol"
                    || !top_any_external_symbol_ranges.contains(&diagnostic.range)
            });
        } else {
            // `Closed` (#35): `TopOpaque` everywhere — genuinely-unknown external symbols are no
            // longer suppressed and are escalated to `error` rather than left as warnings.
            for diagnostic in summary.diagnostics.iter_mut() {
                if diagnostic.code == "missingSassSymbol"
                    && top_any_external_symbol_ranges.contains(&diagnostic.range)
                {
                    diagnostic.severity = "error";
                }
            }
        }
        if strictness.emits_external_boundary_diagnostics() {
            summary
                .diagnostics
                .extend(summarize_omena_query_external_sif_boundary_diagnostics(
                    target_style_path,
                    style_sources,
                    package_manifests,
                    external_sifs,
                    strictness,
                ));
        }
        push_omena_query_ready_surface(
            &mut summary.ready_surfaces,
            "externalSifBoundaryDiagnostics",
        );
        push_omena_query_ready_surface(&mut summary.ready_surfaces, "strictnessSigilGating");
    }
    apply_omena_query_checker_product_gate_to_style_diagnostics(&mut summary.diagnostics);
    push_omena_query_ready_surface(&mut summary.ready_surfaces, "checkerProductDiagnosticGate");
    apply_omena_query_style_diagnostic_suppressions(&target.style_source, &mut summary);
    summary.diagnostic_count = summary.diagnostics.len();
    Some(summary)
}

fn collect_omena_query_external_top_any_sass_symbol_ranges(
    target_style_path: &str,
    style_sources: &[OmenaQueryStyleSourceInputV0],
    package_manifests: &[OmenaQueryStylePackageManifestV0],
    external_sifs: &[OmenaQueryExternalSifInputV0],
) -> BTreeSet<ParserRangeV0> {
    let Some(target) = style_sources
        .iter()
        .find(|source| source.style_path == target_style_path)
    else {
        return BTreeSet::new();
    };
    let style_source_refs = style_sources
        .iter()
        .map(|source| (source.style_path.as_str(), source.style_source.as_str()))
        .collect::<Vec<_>>();
    let style_fact_entries = collect_omena_query_style_fact_entries(style_source_refs.as_slice());
    let resolution =
        summarize_sass_module_cross_file_resolution(&style_fact_entries, package_manifests);
    let external_sources = resolution
        .edges
        .iter()
        .filter(|edge| edge.from_style_path == target_style_path)
        .filter(|edge| edge.status == "external")
        .map(|edge| edge.source.as_str())
        .collect::<BTreeSet<_>>();
    if external_sources.is_empty() {
        return BTreeSet::new();
    }

    let facts = collect_omena_query_omena_parser_style_facts_raw(
        target.style_source.as_str(),
        omena_parser_dialect_for_style_path(target_style_path),
    );
    // The protocol lattice is the single source of truth: a namespace is TopAny iff its
    // external edge classifies to a `top == TopAny` state (Missing/Partial/Stale). A
    // Resolved (TopOpaque) edge — i.e. one backed by a complete SIF — is *not* TopAny, so
    // its symbols stay subject to ordinary missing-symbol checking. (#34)
    let top_any_namespaces = facts
        .sass_module_edges
        .iter()
        .filter(|edge| external_sources.contains(edge.source.as_str()))
        .filter(|edge| {
            let sif = find_omena_query_external_sif(edge.source.as_str(), external_sifs);
            classify_external_boundary_state(edge, sif, &facts, external_sifs).top
                == OmenaResolverBoundaryTopV0::TopAny
        })
        .filter_map(|edge| match edge.kind {
            ParsedSassModuleEdgeFactKind::Use
                if edge.namespace_kind == Some("default")
                    || edge.namespace_kind == Some("alias") =>
            {
                edge.namespace.clone().map(Some)
            }
            ParsedSassModuleEdgeFactKind::Use if edge.namespace_kind == Some("wildcard") => {
                Some(None)
            }
            ParsedSassModuleEdgeFactKind::Import => Some(None),
            _ => None,
        })
        .collect::<BTreeSet<_>>();
    if top_any_namespaces.is_empty() {
        return BTreeSet::new();
    }

    facts
        .sass_symbols
        .into_iter()
        .filter(|symbol| omena_query_sass_symbol_fact_kind_is_reference(symbol.kind))
        .filter(|symbol| top_any_namespaces.contains(&symbol.namespace))
        .map(|symbol| {
            let start: u32 = symbol.range.start().into();
            let end: u32 = symbol.range.end().into();
            parser_range_for_byte_span(
                target.style_source.as_str(),
                ParserByteSpanV0 {
                    start: start as usize,
                    end: end as usize,
                },
            )
        })
        .collect()
}

/// Classify a single external (`status == "external"`) Sass module edge onto the
/// resolver's five-state boundary lattice (#34).
///
/// Four of the five states are derivable today, with no new transport:
/// - **Missing** — no local SIF artifact is in scope for the edge's canonical URL.
/// - **Stale** — a SIF is present but one of its declared dependency interface
///   hashes no longer matches the SIF actually in scope for that dependency.
/// - **Partial** — a SIF is present but only some of the symbols referenced through
///   this edge's namespace appear in its exported interface.
/// - **Resolved** — a SIF is present and every referenced symbol (or no symbol at
///   all) is covered by its exported interface.
///
/// The fifth state (`Unresolved`) is classified by the caller, not here: an unresolved edge
/// has no SIF lattice to reason over, so it folds through the resolver-error channel via
/// `omena_resolver_boundary_state_for_unresolved_reference_v0` (#34).
fn classify_external_boundary_state(
    edge: &ParsedSassModuleEdgeFact,
    sif: Option<&OmenaQueryExternalSifInputV0>,
    target_facts: &omena_parser::ParsedStyleFacts,
    external_sifs: &[OmenaQueryExternalSifInputV0],
) -> OmenaResolverBoundaryStateV0 {
    let Some(sif) = sif else {
        return OmenaResolverBoundaryStateV0::missing(
            None,
            "SIF mode requires a local SIF artifact for this external Sass module",
        );
    };

    let canonical_url = OmenaResolverCanonicalUrlV0 {
        url: edge.source.clone(),
    };

    // Stale: a declared dependency's recorded interface hash no longer agrees with the
    // SIF currently in scope for that dependency canonical URL.
    if let Some(dependency) = sif.sif.dependencies.iter().find(|dependency| {
        find_omena_query_external_sif(dependency.canonical_url.as_str(), external_sifs)
            .map(|dependency_sif| {
                dependency_sif.sif.fingerprints.interface_hash != dependency.interface_hash
            })
            .unwrap_or(false)
    }) {
        return OmenaResolverBoundaryStateV0::stale(
            canonical_url,
            format!(
                "external SIF dependency '{}' interface hash drifted from the lockfile-recorded hash",
                dependency.canonical_url
            ),
        );
    }

    // Partial vs Resolved: do all symbols referenced through this edge's namespace
    // appear in the SIF's exported interface?
    let exported = collect_sif_exported_sass_symbol_keys(&sif.sif);
    let mut referenced = 0usize;
    let mut covered = 0usize;
    for symbol in &target_facts.sass_symbols {
        if !omena_query_sass_symbol_fact_kind_is_reference(symbol.kind) {
            continue;
        }
        if !sass_symbol_reference_belongs_to_edge(edge, symbol.namespace.as_deref()) {
            continue;
        }
        referenced += 1;
        if exported.contains(&(symbol.symbol_kind, fold_sass_symbol_name(&symbol.name))) {
            covered += 1;
        }
    }

    if referenced > 0 && covered < referenced {
        return OmenaResolverBoundaryStateV0::partial(format!(
            "external SIF for '{}' exports only {}/{} referenced symbol(s)",
            edge.source, covered, referenced
        ));
    }

    OmenaResolverBoundaryStateV0::resolved(canonical_url)
}

/// Does a Sass symbol reference (with the given `@use` namespace) flow through `edge`?
///
/// Mirrors the namespace-binding rules already used by the visible-symbol collector:
/// a default/alias `@use` binds references under its namespace, while a wildcard
/// `@use` or an `@import`/`@forward` binds bare (namespace-less) references.
fn sass_symbol_reference_belongs_to_edge(
    edge: &ParsedSassModuleEdgeFact,
    reference_namespace: Option<&str>,
) -> bool {
    match edge.kind {
        ParsedSassModuleEdgeFactKind::Use
            if edge.namespace_kind == Some("default") || edge.namespace_kind == Some("alias") =>
        {
            edge.namespace.as_deref() == reference_namespace
        }
        ParsedSassModuleEdgeFactKind::Use if edge.namespace_kind == Some("wildcard") => {
            reference_namespace.is_none()
        }
        ParsedSassModuleEdgeFactKind::Import | ParsedSassModuleEdgeFactKind::Forward => {
            reference_namespace.is_none()
        }
        _ => false,
    }
}

fn summarize_omena_query_external_sif_boundary_diagnostics(
    target_style_path: &str,
    style_sources: &[OmenaQueryStyleSourceInputV0],
    package_manifests: &[OmenaQueryStylePackageManifestV0],
    external_sifs: &[OmenaQueryExternalSifInputV0],
    strictness: OmenaStrictnessLevelV0,
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let Some(target) = style_sources
        .iter()
        .find(|source| source.style_path == target_style_path)
    else {
        return Vec::new();
    };
    let style_source_refs = style_sources
        .iter()
        .map(|source| (source.style_path.as_str(), source.style_source.as_str()))
        .collect::<Vec<_>>();
    let style_fact_entries = collect_omena_query_style_fact_entries(style_source_refs.as_slice());
    let resolution =
        summarize_sass_module_cross_file_resolution(&style_fact_entries, package_manifests);
    // Every external edge is now classified on the real lattice — including ones that
    // *do* have a SIF in scope (the `.is_none()` pre-filter is gone, #34). Missing edges
    // warn; Stale/Partial edges warn with distinct codes; Resolved edges emit nothing.
    let external_sources = resolution
        .edges
        .iter()
        .filter(|edge| edge.from_style_path == target_style_path)
        .filter(|edge| edge.status == "external")
        .map(|edge| edge.source.as_str())
        .collect::<BTreeSet<_>>();
    // The fifth state (`Unresolved`, #34): an edge whose canonical URL the resolver could
    // not canonicalize at all (`status == "unresolved"`). The resolver-error channel now
    // reaches this layer through `omena_resolver_boundary_state_for_unresolved_reference_v0`.
    // We only adopt the *bare* unresolved edges here: workspace-local unresolved specifiers
    // (`./`, `../`, `/`) are already a hard `missingModule` error elsewhere, so re-flagging
    // them as a boundary state would double-emit. Bare unresolved edges (`'bootstrap'` with
    // no SIF in scope) are the ones the boundary diagnostic previously left silent.
    let unresolved_sources = resolution
        .edges
        .iter()
        .filter(|edge| edge.from_style_path == target_style_path)
        .filter(|edge| edge.status == "unresolved")
        .filter(|edge| !sass_module_source_is_workspace_local(edge.source.as_str()))
        .map(|edge| edge.source.as_str())
        .collect::<BTreeSet<_>>();
    if external_sources.is_empty() && unresolved_sources.is_empty() {
        return Vec::new();
    }

    let facts = collect_omena_query_omena_parser_style_facts_raw(
        target.style_source.as_str(),
        omena_parser_dialect_for_style_path(target_style_path),
    );
    let mut emitted = BTreeSet::new();
    let mut diagnostics = Vec::new();
    for edge in &facts.sass_module_edges {
        let is_external = external_sources.contains(edge.source.as_str());
        let is_unresolved = unresolved_sources.contains(edge.source.as_str());
        if !is_external && !is_unresolved {
            continue;
        }
        if !emitted.insert((edge.kind, edge.source.clone())) {
            continue;
        }
        // An unresolved edge folds through the resolver-error channel onto the `Unresolved`
        // boundary state; an external edge is classified against the SIF lattice (#34).
        let state = if is_unresolved {
            omena_resolver_boundary_state_for_unresolved_reference_v0(edge.source.as_str())
        } else {
            let sif = find_omena_query_external_sif(edge.source.as_str(), external_sifs);
            classify_external_boundary_state(edge, sif, &facts, external_sifs)
        };
        let (code, default_severity) = match state.state {
            // A fully-resolved boundary has no diagnostic to emit.
            OmenaResolverBoundaryStateKindV0::Resolved => continue,
            OmenaResolverBoundaryStateKindV0::Stale => ("staleExternalSif", "warning"),
            OmenaResolverBoundaryStateKindV0::Partial => ("partialExternalSif", "information"),
            OmenaResolverBoundaryStateKindV0::Missing => ("missingExternalSif", "warning"),
            OmenaResolverBoundaryStateKindV0::Unresolved => {
                ("unresolvedExternalReference", "warning")
            }
        };
        // The strictness sigil (#35) multiplies into the severity decision: `Strict`/`Closed`
        // escalate the boundary to `error`; `Standard`/`Relaxed` pass the default through.
        let severity = strictness.boundary_severity(default_severity);
        let start: u32 = edge.range.start().into();
        let end: u32 = edge.range.end().into();
        diagnostics.push(OmenaQueryStyleDiagnosticV0 {
            code,
            severity,
            provenance: vec![
                "omena-resolver.boundary-state",
                "omena-query.external-sif-boundary-diagnostics",
            ],
            range: parser_range_for_byte_span(
                target.style_source.as_str(),
                ParserByteSpanV0 {
                    start: start as usize,
                    end: end as usize,
                },
            ),
            message: format!(
                "External Sass module '{}' is {} ({}); {}",
                edge.source,
                state.state_name,
                state.top_name,
                external_boundary_remediation_hint(state.state)
            ),
            tags: Vec::new(),
            create_custom_property: None,
        });
    }
    diagnostics
}

/// Per-state remediation hint appended to the boundary diagnostic message.
fn external_boundary_remediation_hint(state: OmenaResolverBoundaryStateKindV0) -> &'static str {
    match state {
        OmenaResolverBoundaryStateKindV0::Missing => {
            "generate or provide a SIF artifact, or use --external ignored."
        }
        OmenaResolverBoundaryStateKindV0::Stale => {
            "regenerate the SIF/lockfile so its dependency interface hashes match."
        }
        OmenaResolverBoundaryStateKindV0::Partial => {
            "some referenced symbols are absent from the SIF interface; regenerate the SIF or fix the reference."
        }
        OmenaResolverBoundaryStateKindV0::Unresolved => {
            "the resolver cannot canonicalize this reference; fix the specifier or add it to the workspace."
        }
        OmenaResolverBoundaryStateKindV0::Resolved => "",
    }
}

type SassSymbolKey = (&'static str, Option<String>, String);

/// Fold the Sass-identifier name component so `_` and `-` compare equal.
///
/// Sass treats `$a-b` and `$a_b` (and likewise mixin/function names) as the *same*
/// identifier, so the symbol key must canonicalize the name before lookup; otherwise
/// a reference spelled `$ns-token` is flagged missing against a `$ns_token` definition
/// (and vice versa). Only the name is folded — the namespace (`@use` alias) is matched
/// elsewhere, and CSS custom properties (`--a-b` ≠ `--a_b`) never flow through this key
/// space, so they are untouched. (#48)
fn fold_sass_symbol_name(name: &str) -> String {
    name.replace('_', "-")
}

fn sass_symbol_key(
    symbol_kind: &'static str,
    namespace: Option<String>,
    name: String,
) -> SassSymbolKey {
    let folded = fold_sass_symbol_name(&name);
    (symbol_kind, namespace, folded)
}

fn collect_visible_sass_symbol_keys(
    target_style_path: &str,
    facts_by_path: &BTreeMap<&str, &OmenaQueryOmenaParserStyleFactsV0>,
    resolution: &OmenaQuerySassModuleCrossFileResolutionV0,
    external_sifs: &[OmenaQueryExternalSifInputV0],
) -> BTreeSet<SassSymbolKey> {
    let mut visible = BTreeSet::new();
    if let Some(facts) = facts_by_path.get(target_style_path) {
        visible.extend(
            own_sass_symbol_declaration_keys(facts)
                .into_iter()
                .map(|(symbol_kind, name)| sass_symbol_key(symbol_kind, None, name)),
        );
    }

    for edge in resolution
        .edges
        .iter()
        .filter(|edge| edge.from_style_path == target_style_path)
    {
        let exported = if let Some(module_name) = sass_builtin_module_name(edge.source.as_str()) {
            builtin_sass_symbol_exports(module_name)
        } else if edge.status == "resolved" {
            let mut visiting = BTreeSet::new();
            edge.resolved_style_path
                .as_deref()
                .map(|path| {
                    collect_exported_sass_symbol_keys(
                        path,
                        facts_by_path,
                        resolution,
                        external_sifs,
                        &mut visiting,
                    )
                })
                .unwrap_or_default()
        } else if edge.status == "external" {
            find_omena_query_external_sif(edge.source.as_str(), external_sifs)
                .map(|sif| collect_sif_exported_sass_symbol_keys(&sif.sif))
                .unwrap_or_default()
        } else {
            BTreeSet::new()
        };

        match edge.edge_kind {
            "sassUse"
                if edge.namespace_kind == Some("default")
                    || edge.namespace_kind == Some("alias") =>
            {
                if let Some(namespace) = edge.namespace.clone() {
                    visible.extend(exported.into_iter().map(|(symbol_kind, name)| {
                        sass_symbol_key(symbol_kind, Some(namespace.clone()), name)
                    }));
                }
            }
            "sassUse" if edge.namespace_kind == Some("wildcard") => {
                visible.extend(
                    exported
                        .into_iter()
                        .map(|(symbol_kind, name)| sass_symbol_key(symbol_kind, None, name)),
                );
            }
            "sassImport" => {
                visible.extend(
                    exported
                        .into_iter()
                        .map(|(symbol_kind, name)| sass_symbol_key(symbol_kind, None, name)),
                );
            }
            _ => {}
        }
    }

    visible
}

fn collect_exported_sass_symbol_keys(
    style_path: &str,
    facts_by_path: &BTreeMap<&str, &OmenaQueryOmenaParserStyleFactsV0>,
    resolution: &OmenaQuerySassModuleCrossFileResolutionV0,
    external_sifs: &[OmenaQueryExternalSifInputV0],
    visiting: &mut BTreeSet<String>,
) -> BTreeSet<(&'static str, String)> {
    if !visiting.insert(style_path.to_string()) {
        return BTreeSet::new();
    }

    let mut exported = facts_by_path
        .get(style_path)
        .map(|facts| own_sass_symbol_declaration_keys(facts))
        .unwrap_or_default();

    for edge in resolution
        .edges
        .iter()
        .filter(|edge| edge.from_style_path == style_path)
        .filter(|edge| edge.edge_kind == "sassForward" || edge.edge_kind == "sassImport")
    {
        let module_exports =
            if let Some(module_name) = sass_builtin_module_name(edge.source.as_str()) {
                builtin_sass_symbol_exports(module_name)
            } else if edge.status == "resolved" {
                edge.resolved_style_path
                    .as_deref()
                    .map(|path| {
                        collect_exported_sass_symbol_keys(
                            path,
                            facts_by_path,
                            resolution,
                            external_sifs,
                            visiting,
                        )
                    })
                    .unwrap_or_default()
            } else if edge.status == "external" {
                find_omena_query_external_sif(edge.source.as_str(), external_sifs)
                    .map(|sif| collect_sif_exported_sass_symbol_keys(&sif.sif))
                    .unwrap_or_default()
            } else {
                BTreeSet::new()
            };

        for (symbol_kind, name) in module_exports {
            if !sass_forward_visibility_allows(edge, symbol_kind, name.as_str()) {
                continue;
            }
            let exported_name = if edge.edge_kind == "sassForward" {
                apply_sass_forward_prefix(edge.forward_prefix.as_deref(), name.as_str())
            } else {
                name
            };
            exported.insert((symbol_kind, exported_name));
        }
    }

    visiting.remove(style_path);
    exported
}

fn own_sass_symbol_declaration_keys(
    facts: &OmenaQueryOmenaParserStyleFactsV0,
) -> BTreeSet<(&'static str, String)> {
    facts
        .sass_symbol_facts
        .iter()
        .filter(|fact| is_omena_query_sass_symbol_declaration_kind(fact.kind))
        .map(|fact| (fact.symbol_kind, fact.name.clone()))
        .collect()
}

fn collect_sif_exported_sass_symbol_keys(
    sif: &omena_sif::OmenaSifV1,
) -> BTreeSet<(&'static str, String)> {
    let mut exported = BTreeSet::new();
    exported.extend(sif.exports.variables.iter().map(|variable| {
        (
            "variable",
            variable.name.trim_start_matches('$').to_string(),
        )
    }));
    exported.extend(
        sif.exports
            .mixins
            .iter()
            .map(|mixin| ("mixin", mixin.name.clone())),
    );
    exported.extend(
        sif.exports
            .functions
            .iter()
            .map(|function| ("function", function.name.clone())),
    );
    exported
}

fn find_omena_query_external_sif<'a>(
    canonical_url: &str,
    external_sifs: &'a [OmenaQueryExternalSifInputV0],
) -> Option<&'a OmenaQueryExternalSifInputV0> {
    external_sifs.iter().find(|input| {
        input.canonical_url == canonical_url || input.sif.canonical_url == canonical_url
    })
}

fn sass_forward_visibility_allows(
    edge: &OmenaQuerySassModuleEdgeResolutionV0,
    symbol_kind: &'static str,
    name: &str,
) -> bool {
    let prefixed = apply_sass_forward_prefix(edge.forward_prefix.as_deref(), name);
    let matches_filter = |filter_name: &String| {
        filter_name == name
            || filter_name == prefixed.as_str()
            || filter_name.trim_start_matches('$') == name
            || filter_name.trim_start_matches('$') == prefixed.as_str()
            || (symbol_kind != "variable" && filter_name.trim_start_matches('@') == name)
    };
    match edge.visibility_filter_kind {
        Some("show") => edge.visibility_filter_names.iter().any(matches_filter),
        Some("hide") => !edge.visibility_filter_names.iter().any(matches_filter),
        _ => true,
    }
}

fn apply_sass_forward_prefix(prefix: Option<&str>, name: &str) -> String {
    match prefix {
        Some(prefix) if prefix.contains('*') => prefix.replace('*', name),
        Some(prefix) => format!("{prefix}{name}"),
        None => name.to_string(),
    }
}

fn is_omena_query_sass_builtin_symbol_reference_resolved(
    edges: &[omena_parser::ParsedSassModuleEdgeFact],
    symbol_kind: &'static str,
    namespace: Option<&str>,
    name: &str,
) -> bool {
    edges
        .iter()
        .filter(|edge| edge.kind == ParsedSassModuleEdgeFactKind::Use)
        .filter_map(|edge| {
            sass_builtin_module_name(edge.source.as_str()).map(|module| (edge, module))
        })
        .any(|(edge, module)| {
            let namespace_matches =
                match (namespace, edge.namespace_kind, edge.namespace.as_deref()) {
                    (Some(reference_namespace), Some("default" | "alias"), Some(use_namespace)) => {
                        reference_namespace == use_namespace
                    }
                    (None, Some("wildcard"), _) => true,
                    _ => false,
                };
            namespace_matches && sass_builtin_module_has_symbol(module, symbol_kind, name)
        })
}

fn sass_builtin_module_name(source: &str) -> Option<&str> {
    source.strip_prefix("sass:")
}

fn builtin_sass_symbol_exports(module: &str) -> BTreeSet<(&'static str, String)> {
    let mut exports = BTreeSet::new();
    for name in sass_builtin_module_function_names(module) {
        exports.insert(("function", (*name).to_string()));
    }
    for name in sass_builtin_module_mixin_names(module) {
        exports.insert(("mixin", (*name).to_string()));
    }
    for name in sass_builtin_module_variable_names(module) {
        exports.insert(("variable", (*name).to_string()));
    }
    exports
}

fn sass_builtin_module_has_symbol(module: &str, symbol_kind: &'static str, name: &str) -> bool {
    match symbol_kind {
        "function" => sass_builtin_module_function_names(module).contains(&name),
        "mixin" => sass_builtin_module_mixin_names(module).contains(&name),
        "variable" => sass_builtin_module_variable_names(module).contains(&name),
        _ => false,
    }
}

fn sass_builtin_module_function_names(module: &str) -> &'static [&'static str] {
    match module {
        "color" => &[
            "adjust",
            "alpha",
            "blue",
            "channel",
            "change",
            "complement",
            "desaturate",
            "fade-in",
            "fade-out",
            "grayscale",
            "green",
            "hsl",
            "hsla",
            "hue",
            "ie-hex-str",
            "invert",
            "is-legacy",
            "is-missing",
            "is-powerless",
            "lighten",
            "lightness",
            "mix",
            "opacify",
            "opacity",
            "red",
            "same",
            "saturate",
            "saturation",
            "scale",
            "space",
            "to-gamut",
            "to-space",
            "transparentize",
        ],
        "math" => &[
            "abs",
            "acos",
            "asin",
            "atan",
            "atan2",
            "ceil",
            "clamp",
            "compatible",
            "cos",
            "div",
            "floor",
            "hypot",
            "is-unitless",
            "log",
            "max",
            "min",
            "percentage",
            "pow",
            "random",
            "round",
            "sin",
            "sqrt",
            "tan",
            "unit",
        ],
        "list" => &[
            "append",
            "index",
            "is-bracketed",
            "join",
            "length",
            "separator",
            "set-nth",
            "slash",
            "nth",
            "zip",
        ],
        "map" => &[
            "deep-merge",
            "deep-remove",
            "get",
            "has-key",
            "keys",
            "merge",
            "remove",
            "set",
            "values",
        ],
        "string" => &[
            "index",
            "insert",
            "length",
            "quote",
            "slice",
            "split",
            "to-lower-case",
            "to-upper-case",
            "unique-id",
            "unquote",
        ],
        "selector" => &[
            "append",
            "extend",
            "is-superselector",
            "nest",
            "parse",
            "replace",
            "simple-selectors",
            "unify",
        ],
        "meta" => &[
            "accepts-content",
            "calc-args",
            "calc-name",
            "call",
            "content-exists",
            "feature-exists",
            "function-exists",
            "get-function",
            // `meta.get-mixin` is a real `sass:meta` function added in Sass 1.77. (#44 D2)
            "get-mixin",
            "global-variable-exists",
            "inspect",
            "keywords",
            "mixin-exists",
            "module-functions",
            "module-mixins",
            "module-variables",
            "type-of",
            "variable-exists",
        ],
        _ => &[],
    }
}

fn sass_builtin_module_mixin_names(module: &str) -> &'static [&'static str] {
    match module {
        // `meta.apply` is a real `sass:meta` mixin added in Sass 1.77. (#44 D2)
        "meta" => &["apply", "load-css"],
        _ => &[],
    }
}

fn sass_builtin_module_variable_names(module: &str) -> &'static [&'static str] {
    match module {
        "math" => &["e", "epsilon", "max-safe-integer", "min-safe-integer", "pi"],
        _ => &[],
    }
}

/// RFC-0007-F (#46): composes-target validation restricted to outcomes that are fully resolvable
/// from a single file with no cross-file `--source` context. Only `composes: x` / `composes: x, y`
/// (Local edges) target the file's own selectors and can be checked here; `composes: x from global`
/// (Global edges) reference no concrete selector and produce nothing; `composes: x from './other'`
/// (External edges) require the sibling module's facts, which a single-file invocation does not have,
/// so they are deliberately skipped to avoid a false `missingComposedSelector`/`missingComposedModule`.
/// @value imports are always cross-file and are likewise excluded.
pub fn summarize_omena_query_css_modules_local_composes_style_diagnostics(
    target_style_path: &str,
    target_source: &str,
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let dialect = omena_parser_dialect_for_style_path(target_style_path);
    let target_facts = collect_omena_query_omena_parser_style_facts_raw(target_source, dialect);
    let target_class_names = target_facts
        .selectors
        .iter()
        .filter(|selector| selector.kind == ParsedSelectorFactKind::Class)
        .map(|selector| selector.name.as_str())
        .collect::<BTreeSet<_>>();
    let mut diagnostics = Vec::new();

    for edge in target_facts.css_module_composes_edges {
        // Global edges resolve to no concrete selector; External edges need cross-file facts.
        // Both are outside the single-file-resolvable surface, so only Local edges are validated.
        if edge.kind != ParsedCssModuleComposesEdgeKind::Local {
            continue;
        }
        let start: u32 = edge.range.start().into();
        let end: u32 = edge.range.end().into();
        let range = parser_range_for_byte_span(
            target_source,
            ParserByteSpanV0 {
                start: start as usize,
                end: end as usize,
            },
        );
        for target_name in edge.target_names {
            if target_class_names.contains(target_name.as_str()) {
                continue;
            }
            diagnostics.push(OmenaQueryStyleDiagnosticV0 {
                code: "missingComposedSelector",
                severity: "warning",
                provenance: vec![
                    "omena-parser.css-modules-composes-facts",
                    "omena-query.css-modules-resolution-diagnostics",
                ],
                range,
                message: format!(
                    "Selector '.{}' not found in this file for composes.",
                    target_name
                ),
                tags: Vec::new(),
                create_custom_property: None,
            });
        }
    }

    diagnostics
}

pub fn summarize_omena_query_css_modules_resolution_style_diagnostics(
    target_style_path: &str,
    target_source: &str,
    style_sources: &[OmenaQueryStyleSourceInputV0],
    package_manifests: &[OmenaQueryStylePackageManifestV0],
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let style_source_refs = style_sources
        .iter()
        .map(|source| (source.style_path.as_str(), source.style_source.as_str()))
        .collect::<Vec<_>>();
    let style_fact_entries = collect_omena_query_style_fact_entries(style_source_refs.as_slice());
    let available_style_paths = style_fact_entries
        .iter()
        .map(|entry| entry.style_path.as_str())
        .collect::<BTreeSet<_>>();
    let facts_by_path = style_fact_entries
        .iter()
        .map(|entry| (entry.style_path.as_str(), entry.facts.clone()))
        .collect::<BTreeMap<_, _>>();
    let dialect = omena_parser_dialect_for_style_path(target_style_path);
    let target_facts = collect_omena_query_omena_parser_style_facts_raw(target_source, dialect);
    let mut diagnostics = Vec::new();

    for edge in target_facts.css_module_composes_edges {
        if edge.kind == ParsedCssModuleComposesEdgeKind::Global {
            continue;
        }
        let start: u32 = edge.range.start().into();
        let end: u32 = edge.range.end().into();
        let range = parser_range_for_byte_span(
            target_source,
            ParserByteSpanV0 {
                start: start as usize,
                end: end as usize,
            },
        );
        let target_style = if edge.kind == ParsedCssModuleComposesEdgeKind::External {
            let Some(source) = edge.import_source.as_deref() else {
                continue;
            };
            let Some(resolved_style_path) = resolve_style_module_source(
                target_style_path,
                source,
                &available_style_paths,
                package_manifests,
            ) else {
                diagnostics.push(OmenaQueryStyleDiagnosticV0 {
                    code: "missingComposedModule",
                    severity: "warning",
                    provenance: vec![
                        "omena-parser.css-modules-composes-facts",
                        "omena-resolver.style-module-resolution",
                    ],
                    range,
                    message: format!("Cannot resolve composed CSS Module '{}'.", source),
                    tags: Vec::new(),
                    create_custom_property: None,
                });
                continue;
            };
            resolved_style_path
        } else {
            target_style_path.to_string()
        };
        let target_class_names = facts_by_path
            .get(target_style.as_str())
            .map(|facts| facts.class_selector_names.as_slice())
            .unwrap_or(&[])
            .iter()
            .map(String::as_str)
            .collect::<BTreeSet<_>>();

        for target_name in edge.target_names {
            if target_class_names.contains(target_name.as_str()) {
                continue;
            }
            let message = if let Some(source) = edge.import_source.as_deref() {
                format!(
                    "Selector '.{}' not found in composed module '{}'.",
                    target_name, source
                )
            } else {
                format!(
                    "Selector '.{}' not found in this file for composes.",
                    target_name
                )
            };
            diagnostics.push(OmenaQueryStyleDiagnosticV0 {
                code: "missingComposedSelector",
                severity: "warning",
                provenance: vec![
                    "omena-parser.css-modules-composes-facts",
                    "omena-query.css-modules-resolution-diagnostics",
                ],
                range,
                message,
                tags: Vec::new(),
                create_custom_property: None,
            });
        }
    }

    let mut reported_missing_value_modules = BTreeSet::new();
    for edge in target_facts.css_module_value_import_edges {
        let start: u32 = edge.range.start().into();
        let end: u32 = edge.range.end().into();
        let range = parser_range_for_byte_span(
            target_source,
            ParserByteSpanV0 {
                start: start as usize,
                end: end as usize,
            },
        );
        let Some(resolved_style_path) = resolve_style_module_source(
            target_style_path,
            &edge.import_source,
            &available_style_paths,
            package_manifests,
        ) else {
            if reported_missing_value_modules.insert(edge.import_source.clone()) {
                diagnostics.push(OmenaQueryStyleDiagnosticV0 {
                    code: "missingValueModule",
                    severity: "warning",
                    provenance: vec![
                        "omena-parser.css-modules-value-facts",
                        "omena-resolver.style-module-resolution",
                    ],
                    range,
                    message: format!(
                        "Cannot resolve imported @value module '{}'.",
                        edge.import_source
                    ),
                    tags: Vec::new(),
                    create_custom_property: None,
                });
            }
            continue;
        };
        let target_value_names = facts_by_path
            .get(resolved_style_path.as_str())
            .map(|facts| facts.css_module_value_definition_names.as_slice())
            .unwrap_or(&[])
            .iter()
            .map(String::as_str)
            .collect::<BTreeSet<_>>();
        if target_value_names.contains(edge.remote_name.as_str()) {
            continue;
        }
        let message = if edge.local_name == edge.remote_name {
            format!(
                "@value '{}' not found in '{}'.",
                edge.remote_name, edge.import_source
            )
        } else {
            format!(
                "@value '{}' not found in '{}' for local binding '{}'.",
                edge.remote_name, edge.import_source, edge.local_name
            )
        };
        diagnostics.push(OmenaQueryStyleDiagnosticV0 {
            code: "missingImportedValue",
            severity: "warning",
            provenance: vec![
                "omena-parser.css-modules-value-facts",
                "omena-query.css-modules-resolution-diagnostics",
            ],
            range,
            message,
            tags: Vec::new(),
            create_custom_property: None,
        });
    }

    diagnostics
}

pub fn summarize_omena_query_unused_selector_style_diagnostics(
    target_style_path: &str,
    target_source: &str,
    style_sources: &[OmenaQueryStyleSourceInputV0],
    source_documents: &[OmenaQuerySourceDocumentInputV0],
    package_manifests: &[OmenaQueryStylePackageManifestV0],
    classname_transform: Option<&str>,
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    summarize_omena_query_unused_selector_style_diagnostics_with_path_mappings(
        target_style_path,
        target_source,
        style_sources,
        source_documents,
        package_manifests,
        classname_transform,
        &[],
        &[],
    )
}

#[allow(clippy::too_many_arguments)]
pub fn summarize_omena_query_unused_selector_style_diagnostics_with_path_mappings(
    target_style_path: &str,
    target_source: &str,
    style_sources: &[OmenaQueryStyleSourceInputV0],
    source_documents: &[OmenaQuerySourceDocumentInputV0],
    package_manifests: &[OmenaQueryStylePackageManifestV0],
    classname_transform: Option<&str>,
    bundler_path_mappings: &[OmenaResolverBundlerPathAliasMappingV0],
    tsconfig_path_mappings: &[OmenaResolverTsconfigPathMappingV0],
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    if source_documents.is_empty() {
        return Vec::new();
    }

    let style_source_refs = style_sources
        .iter()
        .map(|source| (source.style_path.as_str(), source.style_source.as_str()))
        .collect::<Vec<_>>();
    let style_fact_entries = collect_omena_query_style_fact_entries(style_source_refs.as_slice());
    let available_style_paths = style_fact_entries
        .iter()
        .map(|entry| entry.style_path.as_str())
        .collect::<BTreeSet<_>>();
    let facts_by_path = style_fact_entries
        .iter()
        .map(|entry| (entry.style_path.as_str(), entry.facts.clone()))
        .collect::<BTreeMap<_, _>>();
    let aliases_by_path = collect_classname_transform_aliases(&facts_by_path, classname_transform);
    let (mut used_selectors, unresolved_dynamic_usage, has_unresolved_style_import) =
        collect_omena_query_source_selector_usage_by_style(
            &available_style_paths,
            source_documents,
            package_manifests,
            &aliases_by_path,
            bundler_path_mappings,
            tsconfig_path_mappings,
        );
    if unresolved_dynamic_usage.contains(target_style_path) {
        return Vec::new();
    }
    // RFC-0007-J (#50): when a source document imports a style module via a specifier we cannot
    // resolve (e.g. a workspace alias `@/styles/a.module.scss` with no tsconfig/bundler path
    // mapping wired in), we do not know which module its `cx('foo')`/`styles.foo` references point
    // at — so we cannot prove any selector is unused. References/goto stay lenient with that
    // ambiguity; the negative assertion (`unusedSelector`) must be conservative to match, instead
    // of dimming every selector in the file. Treat such documents as "possibly using" and skip the
    // lint for this target rather than emitting a wall of false positives.
    if has_unresolved_style_import {
        return Vec::new();
    }

    let composes_graph = collect_css_modules_composes_adjacency(
        &facts_by_path,
        &available_style_paths,
        package_manifests,
    );
    propagate_omena_query_composes_usage(&composes_graph, &mut used_selectors);

    let dialect = omena_parser_dialect_for_style_path(target_style_path);
    let target_facts = collect_omena_query_omena_parser_style_facts_raw(target_source, dialect);
    let used_in_target = used_selectors
        .get(target_style_path)
        .cloned()
        .unwrap_or_default();
    let mut emitted = BTreeSet::new();

    target_facts
        .selectors
        .into_iter()
        .filter(|selector| selector.kind == ParsedSelectorFactKind::Class)
        .filter(|selector| !used_in_target.contains(selector.name.as_str()))
        .filter_map(|selector| {
            let start: u32 = selector.range.start().into();
            let end: u32 = selector.range.end().into();
            if !emitted.insert(selector.name.clone()) {
                return None;
            }
            Some(OmenaQueryStyleDiagnosticV0 {
                code: "unusedSelector",
                severity: "hint",
                provenance: vec![
                    "omena-parser.selector-facts",
                    "omena-query.source-selector-usage",
                ],
                range: parser_range_for_byte_span(
                    target_source,
                    ParserByteSpanV0 {
                        start: start as usize,
                        end: end as usize,
                    },
                ),
                message: format!("Selector '.{}' is declared but never used.", selector.name),
                tags: vec![LSP_DIAGNOSTIC_TAG_UNNECESSARY],
                create_custom_property: None,
            })
        })
        .collect()
}

fn collect_omena_query_source_selector_usage_by_style(
    available_style_paths: &BTreeSet<&str>,
    source_documents: &[OmenaQuerySourceDocumentInputV0],
    package_manifests: &[OmenaQueryStylePackageManifestV0],
    aliases_by_path: &BTreeMap<String, BTreeMap<String, BTreeSet<String>>>,
    bundler_path_mappings: &[OmenaResolverBundlerPathAliasMappingV0],
    tsconfig_path_mappings: &[OmenaResolverTsconfigPathMappingV0],
) -> (BTreeMap<String, BTreeSet<String>>, BTreeSet<String>, bool) {
    let mut used_selectors = BTreeMap::<String, BTreeSet<String>>::new();
    let mut unresolved_dynamic_usage = BTreeSet::<String>::new();
    // RFC-0007-J (#50): tracks whether any document imports a style-like specifier we failed to
    // resolve (an unwired workspace alias). Such a document's selector usages cannot be attributed
    // to a concrete module, so the caller treats the file as "possibly used" instead of dimming
    // every selector.
    let mut has_unresolved_style_import = false;

    for document in source_documents {
        let imports = summarize_omena_query_source_import_declarations_for_source_language(
            document.source_path.as_str(),
            &document.source_source,
            None,
        );
        let mut imported_style_bindings = Vec::new();
        let mut classnames_bind_bindings = Vec::new();
        for import in imports.imports {
            if import.specifier == "classnames/bind" {
                classnames_bind_bindings.push(import.binding);
                continue;
            }
            let Some(style_path) = resolve_style_module_source_with_path_mappings(
                &document.source_path,
                &import.specifier,
                available_style_paths,
                package_manifests,
                bundler_path_mappings,
                tsconfig_path_mappings,
            ) else {
                if specifier_targets_style_module(&import.specifier) {
                    has_unresolved_style_import = true;
                }
                continue;
            };
            imported_style_bindings.push(OmenaQuerySourceImportedStyleBindingV0 {
                binding: import.binding,
                style_uri: style_path,
            });
        }
        if imported_style_bindings.is_empty() {
            continue;
        }

        let index = summarize_omena_query_source_syntax_index_for_source_language(
            document.source_path.as_str(),
            &document.source_source,
            None,
            imported_style_bindings,
            classnames_bind_bindings,
        );
        for reference in index.selector_references {
            let Some(target_style_path) = reference.target_style_uri else {
                continue;
            };
            let Some(selector_name) = reference.selector_name.or_else(|| {
                source_reference_text_selector_name(&document.source_source, reference.byte_span)
            }) else {
                unresolved_dynamic_usage.insert(target_style_path);
                continue;
            };
            let used_for_style = used_selectors.entry(target_style_path.clone()).or_default();
            if let Some(canonical_names) = aliases_by_path
                .get(target_style_path.as_str())
                .and_then(|aliases| aliases.get(selector_name.as_str()))
            {
                used_for_style.extend(canonical_names.iter().cloned());
            } else {
                used_for_style.insert(selector_name);
            }
        }
    }

    (
        used_selectors,
        unresolved_dynamic_usage,
        has_unresolved_style_import,
    )
}

/// Whether an import specifier names a CSS-family style module (so failing to resolve it is a
/// style-resolution gap worth treating conservatively, RFC-0007-J #50) rather than an ordinary
/// JS/TS dependency. A query string or hash on the specifier (e.g. `?inline`) is ignored.
fn specifier_targets_style_module(specifier: &str) -> bool {
    let path = specifier
        .split(['?', '#'])
        .next()
        .unwrap_or(specifier)
        .to_ascii_lowercase();
    path.ends_with(".css")
        || path.ends_with(".scss")
        || path.ends_with(".sass")
        || path.ends_with(".less")
}

fn collect_classname_transform_aliases(
    facts_by_path: &BTreeMap<&str, OmenaQueryOmenaParserStyleFactsV0>,
    classname_transform: Option<&str>,
) -> BTreeMap<String, BTreeMap<String, BTreeSet<String>>> {
    let mut aliases_by_path = BTreeMap::<String, BTreeMap<String, BTreeSet<String>>>::new();
    for (style_path, facts) in facts_by_path {
        let aliases = aliases_by_path
            .entry((*style_path).to_string())
            .or_default();
        for selector_name in &facts.class_selector_names {
            for alias in classname_transform_aliases(selector_name.as_str(), classname_transform) {
                aliases
                    .entry(alias)
                    .or_default()
                    .insert(selector_name.clone());
            }
        }
    }
    aliases_by_path
}

fn classname_transform_aliases(name: &str, classname_transform: Option<&str>) -> Vec<String> {
    match classname_transform.unwrap_or("asIs") {
        "camelCase" => keep_original_plus_transformed(name, to_ascii_camel_case(name)),
        "camelCaseOnly" => vec![to_ascii_camel_case(name)],
        "dashes" => keep_original_plus_transformed(name, dashes_to_ascii_camel(name)),
        "dashesOnly" => vec![dashes_to_ascii_camel(name)],
        _ => vec![name.to_string()],
    }
}

fn keep_original_plus_transformed(name: &str, transformed: String) -> Vec<String> {
    if transformed == name {
        vec![name.to_string()]
    } else {
        vec![name.to_string(), transformed]
    }
}

fn dashes_to_ascii_camel(name: &str) -> String {
    transform_ascii_separated_name(name, |byte| byte == b'-')
}

fn to_ascii_camel_case(name: &str) -> String {
    transform_ascii_separated_name(name, |byte| byte == b'-' || byte == b'_' || byte == b' ')
}

fn transform_ascii_separated_name(name: &str, is_separator: impl Fn(u8) -> bool) -> String {
    let mut output = String::with_capacity(name.len());
    let mut capitalize_next = false;
    for byte in name.bytes() {
        if is_separator(byte) {
            capitalize_next = true;
            continue;
        }
        if capitalize_next {
            output.push((byte as char).to_ascii_uppercase());
            capitalize_next = false;
            continue;
        }
        output.push(byte as char);
    }
    output
}

fn propagate_omena_query_composes_usage(
    composes_graph: &BTreeMap<CssModulesComposesNode, BTreeSet<CssModulesComposesNode>>,
    used_selectors: &mut BTreeMap<String, BTreeSet<String>>,
) {
    let mut used_nodes = used_selectors
        .iter()
        .flat_map(|(style_path, selectors)| {
            selectors
                .iter()
                .map(|selector_name| CssModulesComposesNode {
                    style_path: style_path.clone(),
                    selector_name: selector_name.clone(),
                })
        })
        .collect::<BTreeSet<_>>();

    let mut changed = true;
    while changed {
        changed = false;
        for (owner, targets) in composes_graph {
            if !used_nodes.contains(owner) {
                continue;
            }
            for target in targets {
                if used_nodes.insert(target.clone()) {
                    used_selectors
                        .entry(target.style_path.clone())
                        .or_default()
                        .insert(target.selector_name.clone());
                    changed = true;
                }
            }
        }
    }
}

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

    #[test]
    fn sass_import_is_plain_css_classifies_css_forms() {
        // CSS-form imports Sass explicitly KEEPS (must NOT be flagged).
        assert!(sass_import_is_plain_css("url(theme.css)"));
        assert!(sass_import_is_plain_css("url(theme.scss)")); // unquoted url is always CSS
        assert!(sass_import_is_plain_css("vendor.css"));
        assert!(sass_import_is_plain_css("VENDOR.CSS")); // case-insensitive
        assert!(sass_import_is_plain_css("//cdn.example/x.css"));
        assert!(sass_import_is_plain_css("https://x.com/y.css"));
        assert!(sass_import_is_plain_css("http://x.com/y")); // protocol URL, no .css
    }

    #[test]
    fn sass_import_is_plain_css_keeps_partials_flaggable() {
        // Over-correction guard: genuine Sass-form partials must STILL be classified
        // as Sass imports (i.e. NOT plain CSS), so the deprecation hint still fires.
        assert!(!sass_import_is_plain_css("partial"));
        assert!(!sass_import_is_plain_css("./legacy"));
        assert!(!sass_import_is_plain_css("foundation/buttons"));
        assert!(!sass_import_is_plain_css("legacy")); // bare partial name
    }

    #[test]
    fn media_qualified_import_is_not_deprecated() {
        // RFC-0007-D1 (#44): `@import "foo" screen` and `@import "foo" (min-width: ...)`
        // are kept as plain CSS by Sass; the media qualifier must suppress the hint.
        let screen = summarize_omena_query_sass_import_deprecation_hints(
            "theme.scss",
            "@import \"foo\" screen;",
        );
        assert!(
            screen.is_empty(),
            "media-qualified (Ident) @import must NOT warn deprecatedSassImport, got {screen:?}"
        );
        let feature = summarize_omena_query_sass_import_deprecation_hints(
            "theme.scss",
            "@import \"foo\" (min-width: 100px);",
        );
        assert!(
            feature.is_empty(),
            "media-feature-qualified @import must NOT warn deprecatedSassImport, got {feature:?}"
        );
    }

    #[test]
    fn bare_partial_import_still_deprecated() {
        // Over-correction guard: a genuine Sass-form `@import 'partial'` (no media, no
        // url, no `.css`) MUST still warn deprecatedSassImport.
        let diagnostics =
            summarize_omena_query_sass_import_deprecation_hints("theme.scss", "@import 'partial';");
        assert_eq!(
            diagnostics.len(),
            1,
            "bare Sass partial @import must still warn, got {diagnostics:?}"
        );
        assert_eq!(diagnostics[0].code, "deprecatedSassImport");
    }

    #[test]
    fn media_qualified_comma_peer_classifies_per_target() {
        // `@import "a", "b" screen`: only `"b"` is media-qualified; `"a"` stays a Sass
        // partial and must still warn. Per-target classification, not per-statement.
        let diagnostics = summarize_omena_query_sass_import_deprecation_hints(
            "theme.scss",
            "@import \"a\", \"b\" screen;",
        );
        assert_eq!(
            diagnostics.len(),
            1,
            "exactly the bare partial peer must warn, got {diagnostics:?}"
        );
    }

    /// Durable CI drift check: pin the full `sass:meta` module surface against a
    /// known-good Sass 1.77 member set. If a future edit adds or removes a member
    /// (or the upstream module surface changes and we update one site but not the
    /// pinned set), this fails loudly instead of silently rotting. (#44 D2)
    ///
    /// Functions and mixins are tracked separately because Sass distinguishes them
    /// (`meta.get-mixin` is a function returning a mixin reference; `meta.apply` is a
    /// mixin invoked via `@include`).
    #[test]
    fn sass_meta_allowlist_matches_pinned_1_77_surface() {
        let pinned_functions: BTreeSet<&str> = [
            "accepts-content",
            "calc-args",
            "calc-name",
            "call",
            "content-exists",
            "feature-exists",
            "function-exists",
            "get-function",
            "get-mixin",
            "global-variable-exists",
            "inspect",
            "keywords",
            "mixin-exists",
            "module-functions",
            "module-mixins",
            "module-variables",
            "type-of",
            "variable-exists",
        ]
        .into_iter()
        .collect();
        let pinned_mixins: BTreeSet<&str> = ["apply", "load-css"].into_iter().collect();

        let actual_functions: BTreeSet<&str> = sass_builtin_module_function_names("meta")
            .iter()
            .copied()
            .collect();
        let actual_mixins: BTreeSet<&str> = sass_builtin_module_mixin_names("meta")
            .iter()
            .copied()
            .collect();

        assert_eq!(
            actual_functions, pinned_functions,
            "sass:meta function allowlist drifted from pinned Sass 1.77 surface; \
             update both the allowlist and this pinned set together"
        );
        assert_eq!(
            actual_mixins, pinned_mixins,
            "sass:meta mixin allowlist drifted from pinned Sass 1.77 surface; \
             update both the allowlist and this pinned set together"
        );
    }

    // RFC-0007-F (#46): single-file local-composes validation.

    #[test]
    fn local_composes_flags_real_same_file_typo() {
        // True positive: `composes: missing` references a class that does not exist in this
        // file. With no cross-file context, this is fully resolvable and MUST be flagged.
        let source = ".base { color: red; }\n.button { composes: missing; }\n";
        let diagnostics = summarize_omena_query_css_modules_local_composes_style_diagnostics(
            "/tmp/foo.module.scss",
            source,
        );
        assert_eq!(diagnostics.len(), 1, "expected one missingComposedSelector");
        assert_eq!(diagnostics[0].code, "missingComposedSelector");
        assert!(
            diagnostics[0].message.contains("not found in this file"),
            "message should reference same-file resolution, got: {}",
            diagnostics[0].message
        );
    }

    #[test]
    fn local_composes_keeps_resolvable_target_silent() {
        // A local composes target that DOES exist in the file must NOT be flagged.
        let source = ".base { color: red; }\n.button { composes: base; }\n";
        let diagnostics = summarize_omena_query_css_modules_local_composes_style_diagnostics(
            "/tmp/foo.module.scss",
            source,
        );
        assert!(
            diagnostics.is_empty(),
            "resolvable local composes target should not be flagged, got: {diagnostics:?}"
        );
    }

    #[test]
    fn local_composes_does_not_flag_external_target_without_source() {
        // Over-correction guard: `composes: x from './other'` is an External edge that needs the
        // sibling module's facts. In single-file mode we have no access to `./other`, so we must
        // NOT invent a missingComposedSelector/missingComposedModule for it.
        let source = ".button { composes: shared from './other.module.scss'; color: blue; }\n";
        let diagnostics = summarize_omena_query_css_modules_local_composes_style_diagnostics(
            "/tmp/foo.module.scss",
            source,
        );
        assert!(
            diagnostics.is_empty(),
            "external composes target must not be flagged without cross-file source, got: {diagnostics:?}"
        );
    }

    #[test]
    fn local_composes_does_not_flag_global_target() {
        // `composes: x from global` references no concrete selector and must produce nothing.
        let source = ".button { composes: someGlobal from global; color: blue; }\n";
        let diagnostics = summarize_omena_query_css_modules_local_composes_style_diagnostics(
            "/tmp/foo.module.scss",
            source,
        );
        assert!(
            diagnostics.is_empty(),
            "global composes target must not be flagged, got: {diagnostics:?}"
        );
    }

    #[test]
    fn single_file_summary_includes_local_composes_typo() -> Result<(), String> {
        // The CLI bare path (`style-diagnostics foo` with no --source) routes through this
        // wrapper. A real same-file composes typo must surface even without --source, closing
        // the invocation-mode inconsistency the issue describes.
        let style_uri = "/tmp/foo.module.scss";
        let source = ".base { color: red; }\n.button { composes: missing; }\n";
        let candidates = summarize_omena_query_style_hover_candidates(style_uri, source)
            .ok_or("hover candidates")?;
        let summary = summarize_omena_query_style_diagnostics_for_file_with_local_composes(
            style_uri,
            source,
            candidates.candidates.as_slice(),
        );
        assert!(
            summary
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.code == "missingComposedSelector"),
            "bare single-file summary should surface the local composes typo, got: {:?}",
            summary.diagnostics
        );
        assert_eq!(summary.diagnostic_count, summary.diagnostics.len());
        Ok(())
    }

    #[test]
    fn single_file_summary_does_not_flag_external_composes() -> Result<(), String> {
        // Over-correction guard at the wrapper level: a clean file whose only composes target is
        // cross-file must stay free of composes diagnostics in single-file mode.
        let style_uri = "/tmp/foo.module.scss";
        let source = ".button { composes: shared from './other.module.scss'; color: blue; }\n";
        let candidates = summarize_omena_query_style_hover_candidates(style_uri, source)
            .ok_or("hover candidates")?;
        let summary = summarize_omena_query_style_diagnostics_for_file_with_local_composes(
            style_uri,
            source,
            candidates.candidates.as_slice(),
        );
        assert!(
            !summary.diagnostics.iter().any(|diagnostic| {
                diagnostic.code == "missingComposedSelector"
                    || diagnostic.code == "missingComposedModule"
            }),
            "external composes target must not be flagged in single-file mode, got: {:?}",
            summary.diagnostics
        );
        Ok(())
    }
}