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
use std::collections::{BTreeMap, BTreeSet};

use omena_cascade::{
    CascadeDeclaration, CascadeKey, CascadeLevel, CascadeValue, LayerRank, Specificity,
    cascade_property, parse_simple_selector_signature,
};
use omena_query_checker_orchestrator::{
    OmenaCheckerCascadeDeclarationInputV0, OmenaCheckerCascadeInputV0,
    OmenaCheckerCategoricalInputV0, OmenaCheckerCategoricalPrimitiveRolePairInputV0,
    OmenaCheckerCategoricalRoleMappingInputV0, OmenaCheckerCustomPropertyInputV0,
    OmenaCheckerRgFlowCouplingInputV0, OmenaCheckerRgFlowCouplingSpaceInputV0,
    OmenaCheckerRgFlowInputV0, OmenaCheckerSmtInputV0, OmenaCheckerSmtObligationInputV0,
    checker_cascade_primitive_role_catalog_v0, run_omena_query_checker_cascade_gate_v0,
    run_omena_query_checker_categorical_gate_v0, run_omena_query_checker_rg_flow_gate_v0,
    run_omena_query_checker_smt_gate_v0,
};
use omena_query_checker_orchestrator::{
    REPLICA_ENSEMBLE_FEATURE_GATE_V0, REPLICA_ENSEMBLE_LAYER_MARKER_V0,
    REPLICA_ENSEMBLE_SCHEMA_VERSION_V0, ReplicaSiteOutcomeV0, site as replica_ensemble_site,
};
use omena_query_transform_runner::expand_css_nested_selector;

use super::{
    OmenaQueryStyleDiagnosticV0, ParserByteSpanV0, ParserRangeV0,
    omena_parser_dialect_for_style_path, parser_range_for_byte_span,
    summarize_static_css_custom_property_fixed_point_from_source,
};

const LSP_DIAGNOSTIC_TAG_UNNECESSARY: u8 = 1;

/// Cascade checker surface with an explicit deep-analysis switch.
///
/// The default surface entry passes `deep_analysis == false`: the rg-flow +
/// categorical *theory* diagnostics are opt-in deep-analysis hints, so the
/// default LSP/CLI surface keeps only the product cascade diagnostics (e.g.
/// `circularVar`).
///
/// `deep_analysis == false` (the default) emits only the product cascade gate
/// diagnostics. `deep_analysis == true` additionally surfaces the opt-in rg-flow
/// (`rgFlowRelevantOperator`) and categorical
/// (`categoricalCascadeEvidenceInconsistency`) theory hints — but those hints are
/// *deduplicated* against the product `circularVar` warning: on a single
/// custom-property reference cycle the product chain already emits a `circularVar`
/// warning over the cyclic declarations, so the two whole-file-ranged theory hints
/// that key off the same `has_reference_cycle` predicate would be a redundant
/// triple-fire. When a theory hint's range overlaps a range where `circularVar`
/// already fired, the hint is folded into that `circularVar` diagnostic's
/// provenance instead of surfacing a second/third diagnostic, so a lone var cycle
/// yields exactly one diagnostic.
pub(super) fn summarize_query_cascade_checker_diagnostics_with_deep_analysis(
    style_uri: &str,
    source: &str,
    deep_analysis: bool,
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let (checker_input, declaration_ranges, custom_property_ranges) =
        collect_query_checker_cascade_input(style_uri, source);
    let mut diagnostics = Vec::new();

    // Theory diagnostics are produced eagerly only when deep-analysis is on; the
    // default surface skips the (whole-file-ranged, non-actionable) theory hints
    // entirely so the LSP/CLI output stays clean.
    let (rg_flow_diagnostics, categorical_diagnostics, smt_diagnostics) = if deep_analysis {
        (
            summarize_query_rg_flow_coupling_diagnostics(source, &checker_input.custom_properties),
            summarize_query_categorical_cascade_evidence_diagnostics(
                source,
                &checker_input.custom_properties,
            ),
            summarize_query_smt_cascade_obligation_diagnostics(
                source,
                &checker_input.declarations,
                &declaration_ranges,
            ),
        )
    } else {
        (Vec::new(), Vec::new(), Vec::new())
    };

    let gate = run_omena_query_checker_cascade_gate_v0(checker_input);
    if !gate.enforcement_passed {
        return vec![OmenaQueryStyleDiagnosticV0 {
            code: "checkerDiagnosticGateFailed",
            severity: "warning",
            provenance: vec![
                "omena-query-checker-orchestrator.cascade-gate",
                "omena-query.cascade-checker",
            ],
            range: parser_range_for_byte_span(
                source,
                ParserByteSpanV0 {
                    start: 0,
                    end: source.len(),
                },
            ),
            message: "Checker diagnostic gate rejected unregistered rule output.".to_string(),
            tags: Vec::new(),
            create_custom_property: None,
        }];
    }

    // Build the product cascade gate diagnostics first so the `circularVar`
    // ranges are known before the theory hints are deduplicated against them.
    for evaluation in gate.evaluations {
        if evaluation.rule_code_name == "iacvt-prone"
            && evaluation
                .custom_property_names
                .iter()
                .all(|name| !custom_property_ranges.contains_key(name))
        {
            continue;
        }
        let range = evaluation
            .declaration_ids
            .iter()
            .find_map(|declaration_id| declaration_ranges.get(declaration_id).copied())
            .or_else(|| {
                evaluation
                    .custom_property_names
                    .iter()
                    .find_map(|name| custom_property_ranges.get(name).copied())
            })
            .unwrap_or_else(|| {
                parser_range_for_byte_span(
                    source,
                    ParserByteSpanV0 {
                        start: 0,
                        end: source.len(),
                    },
                )
            });
        let mut provenance = vec![
            "omena-query-checker-orchestrator.cascade-gate",
            "omena-checker.cascade-rules",
            "omena-query.cascade-checker",
        ];
        provenance.extend(evaluation.mechanism_products.iter().copied());
        diagnostics.push(OmenaQueryStyleDiagnosticV0 {
            code: query_cascade_checker_code(evaluation.rule_code_name),
            severity: query_cascade_checker_diagnostic_severity(evaluation.rule_code_name),
            provenance,
            range,
            message: evaluation.message,
            tags: query_cascade_checker_diagnostic_tags(evaluation.rule_code_name),
            create_custom_property: None,
        });
    }

    if deep_analysis {
        deduplicate_query_theory_hints_against_circular_var(
            &mut diagnostics,
            rg_flow_diagnostics,
            categorical_diagnostics,
        );
        // The SMT cascade-violation diagnostics are anchored on the specific
        // longhand declaration that breaks the combination obligation (not the
        // whole-file span the rg-flow/categorical hints use), so they are a
        // distinct, actionable diagnostic and are appended directly rather than
        // deduplicated against `circularVar`.
        diagnostics.extend(smt_diagnostics);
    }

    diagnostics
}

/// Fold the opt-in rg-flow / categorical theory hints into the product
/// `circularVar` diagnostics on any range where `circularVar` already fired,
/// instead of surfacing a redundant second/third whole-file-ranged hint.
///
/// On a single custom-property reference cycle the product chain emits one
/// `circularVar` warning anchored on the cyclic declaration, while both theory
/// hints key off the same `has_reference_cycle` predicate and re-detect the same
/// cycle. Surfacing all three is a triple-fire, so each theory hint whose range
/// overlaps an already-fired `circularVar` range is suppressed and its
/// `omena-checker.*` provenance label is merged into the matching `circularVar`
/// diagnostic (preserving the audit trail that the theory mechanism ran without
/// emitting a duplicate squiggle). A theory hint that does *not* overlap any
/// `circularVar` range (e.g. a genuinely acyclic high-gain hub, if a deeper
/// producer is later wired) is kept as a distinct diagnostic.
fn deduplicate_query_theory_hints_against_circular_var(
    diagnostics: &mut Vec<OmenaQueryStyleDiagnosticV0>,
    theory_hints: impl IntoIterator<Item = OmenaQueryStyleDiagnosticV0>,
    extra_theory_hints: impl IntoIterator<Item = OmenaQueryStyleDiagnosticV0>,
) {
    let circular_var_ranges = diagnostics
        .iter()
        .filter(|diagnostic| diagnostic.code == "circularVar")
        .map(|diagnostic| diagnostic.range)
        .collect::<BTreeSet<_>>();

    for hint in theory_hints.into_iter().chain(extra_theory_hints) {
        // A whole-file-ranged theory hint (start-of-file origin) covers the
        // cyclic declaration that `circularVar` already flagged, so treat
        // "circularVar fired anywhere" as the dedup trigger and fold the hint's
        // provenance into every `circularVar` diagnostic. A hint with an exact
        // matching range is likewise deduplicated.
        let overlaps = !circular_var_ranges.is_empty()
            && (circular_var_ranges.contains(&hint.range)
                || query_theory_hint_range_is_whole_file(&hint.range));
        if overlaps {
            for diagnostic in diagnostics
                .iter_mut()
                .filter(|diagnostic| diagnostic.code == "circularVar")
            {
                for label in hint.provenance.iter().copied() {
                    if !diagnostic.provenance.contains(&label) {
                        diagnostic.provenance.push(label);
                    }
                }
            }
        } else {
            diagnostics.push(hint);
        }
    }
}

/// A theory hint is whole-file-ranged when it starts at the document origin; the
/// rg-flow / categorical hints are always emitted over the whole-file span, so a
/// hint starting at line/char 0 is treated as covering any in-file `circularVar`.
fn query_theory_hint_range_is_whole_file(range: &ParserRangeV0) -> bool {
    range.start.line == 0 && range.start.character == 0
}

/// Surface the real RG-flow coupling-Jacobian-spectrum diagnostic in the query
/// style path.
///
/// The coupling space is extracted from the parsed custom-property dependency
/// graph: the `before` state is the raw declared structure, and the `after`
/// state adds the custom properties that participate in a reference cycle,
/// those that resolve to the guaranteed-invalid value, and an acyclic fan-out
/// pressure term for high-gain custom-property hubs. A diverging stylesheet
/// (growing cyclic / guaranteed-invalid / high-gain coupling) drives the
/// spectral radius above one through `estimate_coupling_jacobian_spectrum_v0`,
/// so the gate emits `rg-flow-relevant-operator`. A settled stylesheet keeps
/// `before == after`, the spectral radius is zero, and nothing is surfaced.
fn summarize_query_rg_flow_coupling_diagnostics(
    source: &str,
    custom_properties: &[OmenaCheckerCustomPropertyInputV0],
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let Some(flow) = query_rg_flow_coupling_for_custom_properties(custom_properties) else {
        return Vec::new();
    };

    let gate =
        run_omena_query_checker_rg_flow_gate_v0(OmenaCheckerRgFlowInputV0 { flows: vec![flow] });
    if !gate.enforcement_passed {
        return Vec::new();
    }

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

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

/// Surface the real categorical cascade primitive-to-role functor diagnostic in
/// the query style path.
///
/// The role mapping models the categorical witness role each exercised cascade
/// primitive plays. The cascade-ranking primitive (`cascade_property`) is
/// supposed to be the cosheaf-colimit witness: the least-fixed-point ranking of
/// every custom property converges to a single computed value. When the parsed
/// custom-property reference graph contains a cycle the ranking colimit cannot
/// converge, so the ranking primitive is forced to play a *second*, conflicting
/// categorical role in the same stylesheet. The functor then has one object
/// (`cascade_property`) mapped to two distinct role objects, which is not a
/// well-defined function on objects: `apply_cascade_role_mapping_functor_v0`
/// rejects the mapping and the gate surfaces
/// `categoricalCascadeEvidenceInconsistency`.
///
/// A stylesheet whose custom-property graph is acyclic maps every primitive to
/// exactly one canonical role, the functor accepts the mapping, and nothing is
/// surfaced. The diagnostic therefore depends on the functor verdict over the
/// actual reference graph, not on a literal: replacing the verdict with a
/// constant would either fire on every stylesheet or none.
fn summarize_query_categorical_cascade_evidence_diagnostics(
    source: &str,
    custom_properties: &[OmenaCheckerCustomPropertyInputV0],
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let Some(mapping) = query_categorical_role_mapping_for_cascade(custom_properties) else {
        return Vec::new();
    };

    let gate = run_omena_query_checker_categorical_gate_v0(OmenaCheckerCategoricalInputV0 {
        mappings: vec![mapping],
    });
    if !gate.enforcement_passed {
        return Vec::new();
    }

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

    gate.evaluations
        .into_iter()
        .map(|evaluation| {
            let mut provenance = vec![
                "omena-query-checker-orchestrator.categorical-gate",
                "omena-checker.categorical-rules",
                "omena-query.cascade-checker",
            ];
            provenance.extend(evaluation.mechanism_products.iter().copied());
            OmenaQueryStyleDiagnosticV0 {
                code: "categoricalCascadeEvidenceInconsistency",
                severity: "hint",
                provenance,
                range: whole_file_range,
                message:
                    "Cascade custom-property ranking forms a reference cycle, so the categorical \
                     cosheaf-colimit witness for the cascade-ranking primitive is not functorial: \
                     the ranking primitive plays conflicting categorical roles in this stylesheet."
                        .to_string(),
                tags: Vec::new(),
                create_custom_property: None,
            }
        })
        .collect()
}

/// Surface the real SMT cascade proof-obligation diagnostic in the query style
/// path.
///
/// The obligation is the canonical *box-shorthand combination* obligation, built
/// from a real parsed signal: when a single selector declares the complete
/// canonical longhand quartet of a known box shorthand (e.g. `margin-top` …
/// `margin-left`), combining those four longhands into the `margin` shorthand is
/// a cascade-sensitive rewrite. The obligation encodes the rewrite's
/// preconditions as `require:name=bool` literals derived from the parsed
/// declarations (supported shorthand, canonical top/right/bottom/left order, no
/// `!important` longhand, no empty value, adjacent source order). The gate runs
/// the genuine `evaluate_omena_checker_smt_rules` mechanism, which discharges the
/// conjunction through the active SMT backend. The default product build remains
/// solver-free and uses the propositional `StubSmtBackendV0`; opt-in `smt-z3`
/// builds route this same product gate through z3. A malformed quartet (e.g. an
/// `!important` longhand or a non-adjacent source order) makes the conjunction
/// `Unsat`, so the backend rejects the proof obligation and the gate surfaces
/// `cascade.smt-violation`. A well-formed quartet is `Sat` and nothing is
/// surfaced.
///
/// The diagnostic therefore depends on the solver verdict over the parsed facts:
/// replacing the backend verdict with a constant would either fire on every
/// quartet or none, breaking the satisfiable/unsatisfiable split.
fn summarize_query_smt_cascade_obligation_diagnostics(
    source: &str,
    declarations: &[OmenaCheckerCascadeDeclarationInputV0],
    declaration_ranges: &BTreeMap<String, ParserRangeV0>,
) -> Vec<OmenaQueryStyleDiagnosticV0> {
    let obligations = query_smt_box_shorthand_obligations(declarations);
    if obligations.is_empty() {
        return Vec::new();
    }

    // Remember which declaration anchors each obligation so an emitted violation
    // can be ranged on the offending longhand rather than the whole file.
    let anchor_ranges = obligations
        .iter()
        .filter_map(|(obligation, anchor_declaration_id)| {
            declaration_ranges
                .get(anchor_declaration_id)
                .copied()
                .map(|range| (obligation.obligation_id.clone(), range))
        })
        .collect::<BTreeMap<_, _>>();

    let gate = run_omena_query_checker_smt_gate_v0(OmenaCheckerSmtInputV0 {
        obligations: obligations
            .into_iter()
            .map(|(obligation, _)| obligation)
            .collect(),
    });
    if !gate.enforcement_passed {
        return Vec::new();
    }

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

    gate.evaluations
        .into_iter()
        .map(|evaluation| {
            let range = anchor_ranges
                .get(&evaluation.obligation_id)
                .copied()
                .unwrap_or(whole_file_range);
            let mut provenance = vec![
                "omena-query-checker-orchestrator.smt-gate",
                "omena-checker.smt-rules",
                "omena-query.cascade-checker",
            ];
            provenance.extend(evaluation.mechanism_products.iter().copied());
            OmenaQueryStyleDiagnosticV0 {
                code: "cascadeSmtViolation",
                severity: "warning",
                provenance,
                range,
                message:
                    "Box-shorthand combination proof obligation is unsatisfiable: these longhands \
                     cannot be safely combined into the shorthand without changing the cascade \
                     outcome."
                        .to_string(),
                tags: Vec::new(),
                create_custom_property: None,
            }
        })
        .collect()
}

/// Build the SMT box-shorthand combination obligations the parsed stylesheet
/// exercises.
///
/// A selector that declares the full canonical longhand quartet of a known box
/// shorthand is a flatten/combination candidate. The returned obligation encodes
/// the cascade-safety preconditions as `require:name=bool` literals mirroring
/// `omena-smt`'s `canonical_box_shorthand_combination_input_v0`, derived from the
/// actual parsed longhand declarations. Each obligation is paired with the
/// declaration id of the first longhand that *breaks* a precondition (or the
/// quartet's first longhand when every precondition holds) so an emitted
/// violation can be ranged precisely.
///
/// Returns an empty vector when the stylesheet declares no complete box-shorthand
/// quartet (no combination obligation to discharge).
fn query_smt_box_shorthand_obligations(
    declarations: &[OmenaCheckerCascadeDeclarationInputV0],
) -> Vec<(OmenaCheckerSmtObligationInputV0, String)> {
    let mut obligations = Vec::new();

    let mut by_selector = BTreeMap::<&str, Vec<&OmenaCheckerCascadeDeclarationInputV0>>::new();
    for declaration in declarations {
        by_selector
            .entry(declaration.selector.as_str())
            .or_default()
            .push(declaration);
    }

    for (selector, selector_declarations) in by_selector {
        for (shorthand, expected_longhands) in query_smt_box_shorthand_longhand_quartets() {
            // Pick the first declaration of each expected longhand, preserving the
            // canonical top/right/bottom/left expectation order.
            let mut quartet = Vec::with_capacity(expected_longhands.len());
            for expected in expected_longhands {
                let Some(declaration) = selector_declarations
                    .iter()
                    .copied()
                    .find(|declaration| declaration.property == *expected)
                else {
                    break;
                };
                quartet.push(declaration);
            }
            if quartet.len() != expected_longhands.len() {
                // Selector does not declare the complete canonical quartet, so it
                // is not a combination candidate for this shorthand.
                continue;
            }

            let canonical_order = quartet
                .iter()
                .zip(expected_longhands.iter())
                .all(|(declaration, expected)| declaration.property == *expected);
            let no_important = quartet.iter().all(|declaration| !declaration.important);
            let no_empty_value = quartet
                .iter()
                .all(|declaration| !declaration.value.trim().is_empty());
            let adjacent_source_order = quartet
                .windows(2)
                .all(|pair| pair[1].source_order == pair[0].source_order + 1);

            let canonical_terms = vec![
                "require:supported-shorthand-property=true".to_string(),
                format!("require:canonical-longhand-quartet={canonical_order}"),
                format!("require:no-important-longhand={no_important}"),
                format!("require:no-empty-longhand-value={no_empty_value}"),
                format!("require:adjacent-source-order={adjacent_source_order}"),
            ];

            // Anchor on the first longhand that breaks a precondition so the
            // squiggle lands on the offending declaration; fall back to the
            // quartet's first longhand when nothing is broken.
            let anchor_declaration_id = quartet
                .iter()
                .find(|declaration| declaration.important || declaration.value.trim().is_empty())
                .map(|declaration| declaration.declaration_id.clone())
                .unwrap_or_else(|| quartet[0].declaration_id.clone());

            obligations.push((
                OmenaCheckerSmtObligationInputV0 {
                    obligation_id: format!(
                        "stylesheet://{selector}::{shorthand}-shorthand-combination"
                    ),
                    l1_primitive: "boxShorthandCombination".to_string(),
                    canonical_terms,
                },
                anchor_declaration_id,
            ));
        }
    }

    obligations
}

/// The canonical top/right/bottom/left longhand quartets for the box shorthands
/// `omena-smt` proves combinable, mirroring `smt_box_shorthand_longhands_v0`.
fn query_smt_box_shorthand_longhand_quartets() -> Vec<(&'static str, [&'static str; 4])> {
    vec![
        (
            "margin",
            ["margin-top", "margin-right", "margin-bottom", "margin-left"],
        ),
        (
            "padding",
            [
                "padding-top",
                "padding-right",
                "padding-bottom",
                "padding-left",
            ],
        ),
        (
            "border-color",
            [
                "border-top-color",
                "border-right-color",
                "border-bottom-color",
                "border-left-color",
            ],
        ),
        (
            "border-style",
            [
                "border-top-style",
                "border-right-style",
                "border-bottom-style",
                "border-left-style",
            ],
        ),
        (
            "border-width",
            [
                "border-top-width",
                "border-right-width",
                "border-bottom-width",
                "border-left-width",
            ],
        ),
        (
            "scroll-margin",
            [
                "scroll-margin-top",
                "scroll-margin-right",
                "scroll-margin-bottom",
                "scroll-margin-left",
            ],
        ),
        (
            "scroll-padding",
            [
                "scroll-padding-top",
                "scroll-padding-right",
                "scroll-padding-bottom",
                "scroll-padding-left",
            ],
        ),
    ]
}

/// Build the cascade primitive-to-role mapping for the parsed stylesheet.
///
/// The baseline is the cascade engine's canonical primitive-to-role catalog: the
/// full repertoire of cascade primitives (ranking, layer/scope flattening,
/// shorthand combination, static `@supports` evaluation) that the stylesheet's
/// ranking participates in, each in its single canonical role. This baseline is
/// functorial, so a stylesheet whose custom-property ranking converges produces
/// an accepted verdict and no diagnostic.
///
/// When any declared custom property participates in a reference cycle, the
/// least-fixed-point ranking colimit cannot converge. The cascade-ranking
/// primitive can therefore no longer serve as its canonical cosheaf-colimit
/// witness, so it is given a conflicting second role. With the ranking primitive
/// now mapped to two distinct role objects, the functor object mapping is
/// many-valued, `apply_cascade_role_mapping_functor_v0` cannot witness
/// composition, and the verdict is rejected.
///
/// Returns `None` when the stylesheet declares no custom properties (no ranking
/// colimit obligation to witness).
fn query_categorical_role_mapping_for_cascade(
    custom_properties: &[OmenaCheckerCustomPropertyInputV0],
) -> Option<OmenaCheckerCategoricalRoleMappingInputV0> {
    if custom_properties.is_empty() {
        return None;
    }

    let declared = custom_properties
        .iter()
        .map(|property| property.name.as_str())
        .collect::<BTreeSet<_>>();
    let dependencies = custom_properties
        .iter()
        .map(|property| {
            (
                property.name.as_str(),
                property
                    .dependencies
                    .iter()
                    .map(String::as_str)
                    .filter(|dependency| declared.contains(dependency))
                    .collect::<BTreeSet<_>>(),
            )
        })
        .collect::<BTreeMap<_, _>>();
    let has_reference_cycle = declared
        .iter()
        .any(|name| query_custom_property_in_reference_cycle(name, &dependencies));

    let mut primitive_role_pairs = Vec::new();

    if has_reference_cycle {
        // Conflicting second role for the ranking primitive, placed before the
        // canonical catalog: a non-convergent ranking colimit cannot be the
        // cosheaf-colimit witness, so the functor object mapping becomes
        // many-valued and the verdict is rejected.
        primitive_role_pairs.push(OmenaCheckerCategoricalPrimitiveRolePairInputV0 {
            primitive_name: "cascade_property".to_string(),
            categorical_role: "cascade-ranking non-convergent witness".to_string(),
        });
    }

    primitive_role_pairs.extend(checker_cascade_primitive_role_catalog_v0().into_iter().map(
        |(primitive_name, categorical_role)| OmenaCheckerCategoricalPrimitiveRolePairInputV0 {
            primitive_name: primitive_name.to_string(),
            categorical_role: categorical_role.to_string(),
        },
    ));

    Some(OmenaCheckerCategoricalRoleMappingInputV0 {
        mapping_id: "stylesheet://cascade-primitive-role-evidence".to_string(),
        primitive_role_pairs,
    })
}

/// Derive the `(primitive_name, categorical_role)` pairs the parsed stylesheet's
/// custom-property ranking exercises, for the cascade-at-position categorical
/// evidence attachment. Shares the reference-cycle detection with the diagnostic
/// path so both observe the same functor verdict.
pub(super) fn query_exercised_cascade_primitive_role_pairs_from_source(
    source: &str,
) -> Vec<(String, String)> {
    let (checker_input, _, _) = collect_query_checker_cascade_input("query://categorical", source);
    match query_categorical_role_mapping_for_cascade(&checker_input.custom_properties) {
        Some(mapping) => mapping
            .primitive_role_pairs
            .into_iter()
            .map(|pair| (pair.primitive_name, pair.categorical_role))
            .collect(),
        None => Vec::new(),
    }
}

fn query_rg_flow_coupling_for_custom_properties(
    custom_properties: &[OmenaCheckerCustomPropertyInputV0],
) -> Option<OmenaCheckerRgFlowCouplingInputV0> {
    if custom_properties.is_empty() {
        return None;
    }

    let declared = custom_properties
        .iter()
        .map(|property| property.name.as_str())
        .collect::<BTreeSet<_>>();
    let dependencies = custom_properties
        .iter()
        .map(|property| {
            (
                property.name.as_str(),
                property
                    .dependencies
                    .iter()
                    .map(String::as_str)
                    .filter(|dependency| declared.contains(dependency))
                    .collect::<BTreeSet<_>>(),
            )
        })
        .collect::<BTreeMap<_, _>>();

    let k_env = custom_properties.len();
    let k_decl = custom_properties
        .iter()
        .filter(|property| {
            property
                .dependencies
                .iter()
                .any(|dependency| declared.contains(dependency.as_str()))
        })
        .count();
    let k_cycle = declared
        .iter()
        .filter(|name| query_custom_property_in_reference_cycle(name, &dependencies))
        .count();
    let k_dirty = custom_properties
        .iter()
        .filter(|property| property.guaranteed_invalid)
        .count();
    let acyclic_high_gain_pressure = if k_cycle == 0 {
        query_acyclic_high_gain_coupling_pressure(&dependencies)
    } else {
        0
    };
    let after_k_decl = k_decl.saturating_add(acyclic_high_gain_pressure);

    Some(OmenaCheckerRgFlowCouplingInputV0 {
        workspace_path: "stylesheet://custom-property-coupling".to_string(),
        before: OmenaCheckerRgFlowCouplingSpaceInputV0 {
            k_env,
            k_decl,
            k_cycle: 0,
            k_dirty: 0,
        },
        after: OmenaCheckerRgFlowCouplingSpaceInputV0 {
            k_env,
            k_decl: after_k_decl,
            k_cycle,
            k_dirty,
        },
    })
}

fn query_acyclic_high_gain_coupling_pressure(
    dependencies: &BTreeMap<&str, BTreeSet<&str>>,
) -> usize {
    let mut fanout_by_dependency = BTreeMap::<&str, usize>::new();
    for edges in dependencies.values() {
        for dependency in edges {
            *fanout_by_dependency.entry(*dependency).or_default() += 1;
        }
    }

    fanout_by_dependency
        .values()
        .filter(|count| **count >= 3)
        .map(|count| count.saturating_mul(count.saturating_sub(1)) / 2)
        .sum()
}

fn query_custom_property_in_reference_cycle(
    start: &str,
    dependencies: &BTreeMap<&str, BTreeSet<&str>>,
) -> bool {
    let mut stack = dependencies
        .get(start)
        .map(|edges| edges.iter().copied().collect::<Vec<_>>())
        .unwrap_or_default();
    let mut visited = BTreeSet::new();
    while let Some(node) = stack.pop() {
        if node == start {
            return true;
        }
        if !visited.insert(node) {
            continue;
        }
        if let Some(edges) = dependencies.get(node) {
            stack.extend(edges.iter().copied());
        }
    }
    false
}

fn query_cascade_checker_code(code: &'static str) -> &'static str {
    match code {
        "unreachable-declaration" => "unreachableDeclaration",
        "dead-cascade-layer" => "deadCascadeLayer",
        "iacvt-prone" => "iacvtProne",
        "circular-var" => "circularVar",
        "unspecified-cascade-tie" => "unspecifiedCascadeTie",
        "designer-intent-inconsistency" => "designerIntentInconsistency",
        _ => "cascadeAware",
    }
}

fn query_cascade_checker_diagnostic_severity(code: &'static str) -> &'static str {
    match code {
        "unreachable-declaration" | "dead-cascade-layer" | "designer-intent-inconsistency" => {
            "hint"
        }
        _ => "warning",
    }
}

fn query_cascade_checker_diagnostic_tags(code: &'static str) -> Vec<u8> {
    match code {
        "unreachable-declaration" | "dead-cascade-layer" => {
            vec![LSP_DIAGNOSTIC_TAG_UNNECESSARY]
        }
        _ => Vec::new(),
    }
}

fn collect_query_checker_cascade_input(
    style_uri: &str,
    source: &str,
) -> (
    OmenaCheckerCascadeInputV0,
    BTreeMap<String, ParserRangeV0>,
    BTreeMap<String, ParserRangeV0>,
) {
    let declarations = collect_query_checker_cascade_declarations(source);
    let declaration_ranges = declarations
        .iter()
        .map(|declaration| {
            (
                declaration.input.declaration_id.clone(),
                parser_range_for_byte_span(source, declaration.byte_span),
            )
        })
        .collect::<BTreeMap<_, _>>();
    let dialect = omena_parser_dialect_for_style_path(style_uri);
    let guaranteed_invalid_custom_properties =
        summarize_static_css_custom_property_fixed_point_from_source(source, dialect)
            .entries
            .into_iter()
            .filter(|entry| entry.guaranteed_invalid)
            .map(|entry| entry.name)
            .collect::<BTreeSet<_>>();
    let mut custom_properties_by_name =
        BTreeMap::<String, (BTreeSet<String>, bool, ParserByteSpanV0)>::new();

    for declaration in &declarations {
        if !declaration.input.property.starts_with("--") {
            continue;
        }
        let entry = custom_properties_by_name
            .entry(declaration.input.property.clone())
            .or_insert_with(|| {
                (
                    BTreeSet::new(),
                    guaranteed_invalid_custom_properties.contains(&declaration.input.property),
                    declaration.byte_span,
                )
            });
        entry.1 |= guaranteed_invalid_custom_properties.contains(&declaration.input.property);
        for dependency in collect_query_var_references_in_value(&declaration.input.value) {
            entry.0.insert(dependency);
        }
    }

    let custom_property_ranges = custom_properties_by_name
        .iter()
        .map(|(name, (_, _, byte_span))| {
            (name.clone(), parser_range_for_byte_span(source, *byte_span))
        })
        .collect::<BTreeMap<_, _>>();
    let custom_properties = custom_properties_by_name
        .into_iter()
        .map(
            |(name, (dependencies, guaranteed_invalid, _))| OmenaCheckerCustomPropertyInputV0 {
                name,
                dependencies: dependencies.into_iter().collect(),
                guaranteed_invalid,
            },
        )
        .collect::<Vec<_>>();

    (
        OmenaCheckerCascadeInputV0 {
            declarations: declarations
                .into_iter()
                .map(|declaration| declaration.input)
                .collect(),
            custom_properties,
        },
        declaration_ranges,
        custom_property_ranges,
    )
}

/// Compute the REAL per-`(selector, property)` cascade winners a parsed
/// stylesheet produces, projected as replica-ensemble site outcomes.
///
/// This is the cross-file replica-ensemble's per-file input: each in-graph CSS
/// module is one replica, and its "site outcomes" are the winning value of every
/// `(selector, property)` it declares. The winners are not literals — they are
/// computed by the genuine `cascade_property` ranking over the parsed
/// declarations: declarations are grouped by `(selector, property)`, each is
/// assigned a real `CascadeKey` (author-important vs author-normal level, real
/// `@layer` rank, real selector specificity from `parse_simple_selector_signature`,
/// and source order), and the lexicographic cascade key picks the winner. The
/// winning declaration's value is carried as the outcome identity (via the
/// `CascadeDeclaration.id`), so two replicas *agree* on a site iff their winning
/// value for that `(selector, property)` is identical, and *disagree* iff their
/// cascades resolve to different values. No replica snapshot is fabricated.
///
/// Custom-property declarations (`--*`) are excluded: their winner is a token
/// whose meaning depends on the whole-graph fixed point, not a directly
/// comparable per-file value.
pub(super) fn collect_query_replica_ensemble_site_outcomes(
    source: &str,
) -> Vec<ReplicaSiteOutcomeV0> {
    let declarations = collect_query_checker_cascade_declarations(source);

    // Group the parsed declarations by their `(selector, property)` cascade site.
    let mut by_site: BTreeMap<(String, String), Vec<CascadeDeclaration>> = BTreeMap::new();
    for declaration in &declarations {
        let property = declaration.input.property.as_str();
        if property.starts_with("--") {
            continue;
        }
        let cascade_declaration = query_cascade_declaration_from_input(&declaration.input);
        by_site
            .entry((
                declaration.input.selector.clone(),
                declaration.input.property.clone(),
            ))
            .or_default()
            .push(cascade_declaration);
    }

    by_site
        .into_iter()
        .filter_map(|((selector, property), site_declarations)| {
            let outcome = cascade_property(site_declarations, &property);
            // Only definite winners are comparable across replicas; an
            // `Inherit`/`Top`/`RankedSet` site carries no concrete per-file value to
            // overlap on, and `DefiniteOnly` projection would drop it anyway.
            if !matches!(outcome, omena_cascade::CascadeOutcome::Definite { .. }) {
                return None;
            }
            Some(ReplicaSiteOutcomeV0 {
                schema_version: REPLICA_ENSEMBLE_SCHEMA_VERSION_V0,
                product: "omena-ensemble.replica-site-outcome",
                layer_marker: REPLICA_ENSEMBLE_LAYER_MARKER_V0,
                feature_gate: REPLICA_ENSEMBLE_FEATURE_GATE_V0,
                site: replica_ensemble_site(selector, property),
                outcome,
                provenance: None,
            })
        })
        .collect()
}

/// Lift a parsed cascade declaration onto an `omena-cascade` `CascadeDeclaration`
/// with a real cascade key. The winning value is carried as the declaration `id`
/// so the replica-overlap projection (`definite:<id>`) keys agreement on the
/// resolved value rather than a per-file synthetic identifier.
fn query_cascade_declaration_from_input(
    input: &OmenaCheckerCascadeDeclarationInputV0,
) -> CascadeDeclaration {
    let level = if input.important {
        CascadeLevel::AuthorImportant
    } else {
        CascadeLevel::AuthorNormal
    };
    let layer_rank = LayerRank(input.layer_order.unwrap_or(0));
    let specificity = parse_simple_selector_signature(&input.selector)
        .map(|signature| signature.specificity)
        .unwrap_or(Specificity::ZERO);
    let value = input.value.trim().to_string();

    CascadeDeclaration {
        id: value.clone(),
        property: input.property.clone(),
        value: CascadeValue::Literal(value),
        key: CascadeKey::new(level, layer_rank, 0, specificity, input.source_order),
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct QueryCheckerCascadeDeclaration {
    input: OmenaCheckerCascadeDeclarationInputV0,
    byte_span: ParserByteSpanV0,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct QueryCheckerCascadeScope {
    condition_context: Vec<String>,
    layer_name: Option<String>,
    layer_order: Option<i32>,
}

fn collect_query_checker_cascade_declarations(source: &str) -> Vec<QueryCheckerCascadeDeclaration> {
    let mut declarations = Vec::new();
    let mut layer_orders = BTreeMap::new();
    let mut next_layer_order = 0i32;
    collect_query_checker_cascade_blocks(
        source,
        0,
        source.len(),
        None,
        Vec::new(),
        None,
        None,
        &mut layer_orders,
        &mut next_layer_order,
        &mut declarations,
    );
    declarations
}

#[allow(clippy::too_many_arguments)]
fn collect_query_checker_cascade_blocks(
    source: &str,
    start: usize,
    end: usize,
    parent_selector: Option<String>,
    condition_context: Vec<String>,
    layer_name: Option<String>,
    layer_order: Option<i32>,
    layer_orders: &mut BTreeMap<String, i32>,
    next_layer_order: &mut i32,
    declarations: &mut Vec<QueryCheckerCascadeDeclaration>,
) {
    let mut index = start;
    while let Some(open_index) = find_query_top_level_byte(source, index, end, b'{') {
        let Some(close_index) = matching_query_block_end(source, open_index, end) else {
            break;
        };
        let prelude_start = query_prelude_start(source, start, open_index);
        let prelude = source[prelude_start..open_index].trim();
        let body_start = open_index + 1;

        if let Some(layer) = query_layer_name_from_prelude(prelude) {
            let order = *layer_orders.entry(layer.clone()).or_insert_with(|| {
                let order = *next_layer_order;
                *next_layer_order += 1;
                order
            });
            collect_query_checker_cascade_blocks(
                source,
                body_start,
                close_index,
                parent_selector.clone(),
                condition_context.clone(),
                Some(layer),
                Some(order),
                layer_orders,
                next_layer_order,
                declarations,
            );
        } else if let Some(at_root_selector) = query_at_root_selector_from_prelude(prelude) {
            // RFC-0007-E4 (#45): `@at-root <selector> { … }` resets the cascade context to the
            // document root and applies `<selector>` as the new context — the inner block's
            // declarations belong to `<selector>`, NOT to the enclosing parent. The walker
            // previously hit the generic `@`-rule arm below, which kept `parent_selector` and
            // recursed without ever recording the block's declarations against a selector, so a
            // nested `@at-root .b { … }` was dropped from cascade analysis (the bare
            // `@at-root { … }` block form already worked because its inner `.b` is a plain
            // selector rule). We re-root by clearing `parent_selector` (root context) and treating
            // the trailing selector list exactly like an ordinary nested rule: emit its direct
            // declarations and recurse for any further nesting.
            let mut canonical_members = Vec::new();
            for member in split_query_selector_list(&at_root_selector) {
                let canonical_selector = canonical_query_checker_selector(None, &member);
                if !canonical_members.contains(&canonical_selector) {
                    canonical_members.push(canonical_selector);
                }
            }

            for canonical_selector in canonical_members {
                collect_query_checker_direct_declarations(
                    source,
                    body_start,
                    close_index,
                    &canonical_selector,
                    QueryCheckerCascadeScope {
                        condition_context: condition_context.clone(),
                        layer_name: layer_name.clone(),
                        layer_order,
                    },
                    declarations,
                );
                collect_query_checker_cascade_blocks(
                    source,
                    body_start,
                    close_index,
                    Some(canonical_selector),
                    condition_context.clone(),
                    layer_name.clone(),
                    layer_order,
                    layer_orders,
                    next_layer_order,
                    declarations,
                );
            }
        } else if prelude.starts_with('@') {
            let mut nested_condition_context = condition_context.clone();
            nested_condition_context.push(normalize_query_condition_prelude(prelude));
            collect_query_checker_cascade_blocks(
                source,
                body_start,
                close_index,
                parent_selector.clone(),
                nested_condition_context,
                layer_name.clone(),
                layer_order,
                layer_orders,
                next_layer_order,
                declarations,
            );
        } else if !prelude.is_empty() {
            // A selector list (`.a, .b { … }`) records one declaration set per
            // member so each member can tie with a sibling rule on the same
            // selector (RFC-0007 B2). Identical canonical members within one
            // prelude are de-duplicated to avoid a spurious self-tie.
            let mut canonical_members = Vec::new();
            for member in split_query_selector_list(prelude) {
                let canonical_selector =
                    canonical_query_checker_selector(parent_selector.as_deref(), &member);
                if !canonical_members.contains(&canonical_selector) {
                    canonical_members.push(canonical_selector);
                }
            }

            for canonical_selector in canonical_members {
                collect_query_checker_direct_declarations(
                    source,
                    body_start,
                    close_index,
                    &canonical_selector,
                    QueryCheckerCascadeScope {
                        condition_context: condition_context.clone(),
                        layer_name: layer_name.clone(),
                        layer_order,
                    },
                    declarations,
                );
                collect_query_checker_cascade_blocks(
                    source,
                    body_start,
                    close_index,
                    Some(canonical_selector),
                    condition_context.clone(),
                    layer_name.clone(),
                    layer_order,
                    layer_orders,
                    next_layer_order,
                    declarations,
                );
            }
        }

        index = close_index + 1;
    }
}

/// Splits a selector-list prelude on top-level commas, ignoring commas nested
/// inside `()` (e.g. `:is(.a, .b)`), `[]`, or string literals (RFC-0007 B2).
/// Returns one entry per member; a prelude with no top-level comma returns a
/// single-element vector containing the whole (trimmed) prelude.
fn split_query_selector_list(prelude: &str) -> Vec<String> {
    let mut members = Vec::new();
    let mut segment_start = 0usize;
    let mut index = 0usize;
    let mut quote: Option<char> = None;
    let mut paren_depth = 0usize;
    let mut bracket_depth = 0usize;

    while index < prelude.len() {
        let Some(ch) = prelude[index..].chars().next() else {
            break;
        };
        if let Some(quote_ch) = quote {
            index += ch.len_utf8();
            if ch == '\\' {
                if let Some(escaped) = prelude[index..].chars().next() {
                    index += escaped.len_utf8();
                }
            } else if ch == quote_ch {
                quote = None;
            }
            continue;
        }
        match ch {
            '"' | '\'' => quote = Some(ch),
            '(' => paren_depth += 1,
            ')' => paren_depth = paren_depth.saturating_sub(1),
            '[' => bracket_depth += 1,
            ']' => bracket_depth = bracket_depth.saturating_sub(1),
            ',' if paren_depth == 0 && bracket_depth == 0 => {
                let member = prelude[segment_start..index].trim();
                if !member.is_empty() {
                    members.push(member.to_string());
                }
                segment_start = index + ch.len_utf8();
            }
            _ => {}
        }
        index += ch.len_utf8();
    }

    let tail = prelude[segment_start..].trim();
    if !tail.is_empty() {
        members.push(tail.to_string());
    }
    if members.is_empty() {
        members.push(prelude.trim().to_string());
    }
    members
}

fn canonical_query_checker_selector(parent_selector: Option<&str>, selector: &str) -> String {
    let selector = selector.trim();
    match parent_selector {
        Some(parent_selector) => expand_css_nested_selector(parent_selector, selector)
            .unwrap_or_else(|| fallback_expand_query_nested_selector(parent_selector, selector)),
        None => selector.to_string(),
    }
}

fn fallback_expand_query_nested_selector(parent_selector: &str, selector: &str) -> String {
    if selector.contains('&') {
        selector.replace('&', parent_selector)
    } else {
        format!("{parent_selector} {selector}")
    }
}

fn collect_query_checker_direct_declarations(
    source: &str,
    body_start: usize,
    body_end: usize,
    selector: &str,
    scope: QueryCheckerCascadeScope,
    declarations: &mut Vec<QueryCheckerCascadeDeclaration>,
) {
    let mut statement_start = body_start;
    let mut index = body_start;
    while index < body_end {
        if let Some(open_index) = find_query_top_level_byte(source, index, body_end, b'{') {
            while let Some(semicolon_index) =
                find_query_top_level_byte(source, index, open_index, b';')
            {
                push_query_checker_declaration(
                    source,
                    statement_start,
                    semicolon_index,
                    selector,
                    &scope,
                    declarations,
                );
                statement_start = semicolon_index + 1;
                index = statement_start;
            }
            let Some(close_index) = matching_query_block_end(source, open_index, body_end) else {
                break;
            };
            statement_start = close_index + 1;
            index = statement_start;
            continue;
        }

        while let Some(semicolon_index) = find_query_top_level_byte(source, index, body_end, b';') {
            push_query_checker_declaration(
                source,
                statement_start,
                semicolon_index,
                selector,
                &scope,
                declarations,
            );
            statement_start = semicolon_index + 1;
            index = statement_start;
        }
        break;
    }

    push_query_checker_declaration(
        source,
        statement_start,
        body_end,
        selector,
        &scope,
        declarations,
    );
}

fn push_query_checker_declaration(
    source: &str,
    start: usize,
    end: usize,
    selector: &str,
    scope: &QueryCheckerCascadeScope,
    declarations: &mut Vec<QueryCheckerCascadeDeclaration>,
) {
    let Some((trimmed_start, trimmed_end)) = trimmed_query_span(source, start, end) else {
        return;
    };
    let raw_statement = &source[trimmed_start..trimmed_end];
    // Strip CSS/Sass comments before the property/value split. A leading
    // `/* */` block (or a `//` line comment) that precedes the property name
    // otherwise poisons the property string (e.g. `/* primary */ color`), so the
    // whitespace guard below rejects it and the declaration is silently dropped
    // from cascade analysis (RFC-0007 B1).
    let statement = strip_query_statement_comments(raw_statement);
    let statement = statement.as_str();
    let Some(colon_offset) = find_query_top_level_colon(statement) else {
        return;
    };
    let property = statement[..colon_offset].trim();
    if property.is_empty()
        || property.starts_with('@')
        // Sass `$`-variable assignments are compile-time bindings that are erased
        // before CSS emission, so they never participate in the cascade. Skip
        // them here (symmetric to the `--custom-property` cascade path, which
        // does belong in the cascade) so re-binding a `$`-var is not mistaken for
        // a duplicate CSS declaration / cascade tie.
        || property.starts_with('$')
        || property.contains(char::is_whitespace)
        || property.contains('{')
        || property.contains('}')
    {
        return;
    }
    let mut value = statement[colon_offset + 1..].trim().to_string();
    let important = query_value_has_important_suffix(&value);
    if important {
        value = value
            .trim_end()
            .trim_end_matches(|ch: char| ch.is_ascii_whitespace())
            .trim_end_matches("!important")
            .trim_end()
            .to_string();
    }
    let source_order = declarations.len();
    let declaration_id = format!("decl-{source_order}");
    declarations.push(QueryCheckerCascadeDeclaration {
        input: OmenaCheckerCascadeDeclarationInputV0 {
            declaration_id,
            selector: selector.to_string(),
            property: property.to_string(),
            value: value.clone(),
            source_order: source_order.min(u32::MAX as usize) as u32,
            condition_context: scope.condition_context.clone(),
            layer_name: scope.layer_name.clone(),
            layer_order: scope.layer_order,
            important,
            var_references: collect_query_var_references_in_value(&value),
        },
        byte_span: ParserByteSpanV0 {
            start: trimmed_start,
            end: trimmed_end,
        },
    });
}

fn query_value_has_important_suffix(value: &str) -> bool {
    value
        .trim_end()
        .to_ascii_lowercase()
        .ends_with("!important")
}

fn trimmed_query_span(source: &str, start: usize, end: usize) -> Option<(usize, usize)> {
    let mut trimmed_start = start;
    let mut trimmed_end = end;
    while trimmed_start < trimmed_end
        && source[trimmed_start..]
            .chars()
            .next()
            .is_some_and(char::is_whitespace)
    {
        trimmed_start += source[trimmed_start..].chars().next()?.len_utf8();
    }
    while trimmed_end > trimmed_start
        && source[..trimmed_end]
            .chars()
            .next_back()
            .is_some_and(char::is_whitespace)
    {
        trimmed_end -= source[..trimmed_end].chars().next_back()?.len_utf8();
    }
    (trimmed_start < trimmed_end).then_some((trimmed_start, trimmed_end))
}

/// Removes CSS/Sass comments from a single declaration statement, quote-aware.
///
/// `/* ... */` block comments are elided entirely; `//` line comments are
/// truncated to the end of their line (Sass semantics). Comment delimiters
/// inside string literals are preserved. The result is used for the
/// property/value split so a comment positioned before a property name no
/// longer poisons it (RFC-0007 B1).
fn strip_query_statement_comments(statement: &str) -> String {
    let mut out = String::with_capacity(statement.len());
    let mut index = 0usize;
    let mut quote: Option<char> = None;
    let mut paren_depth = 0usize;
    while index < statement.len() {
        let Some(ch) = statement[index..].chars().next() else {
            break;
        };
        if let Some(quote_ch) = quote {
            out.push(ch);
            index += ch.len_utf8();
            if ch == '\\' {
                if let Some(escaped) = statement[index..].chars().next() {
                    out.push(escaped);
                    index += escaped.len_utf8();
                }
            } else if ch == quote_ch {
                quote = None;
            }
            continue;
        }
        if statement[index..].starts_with("/*") {
            match statement[index + 2..].find("*/") {
                Some(close_offset) => {
                    // Replace the comment with a single space so adjacent tokens
                    // (e.g. `color/* x */:`) do not get glued together.
                    out.push(' ');
                    index += close_offset + 4;
                }
                // Unterminated block comment: drop the remainder.
                None => break,
            }
            continue;
        }
        // A `//` outside parentheses is a Sass line comment; inside parentheses
        // (e.g. `url(http://example.com)`) it is part of a value and must be
        // preserved, otherwise the value is corrupted into an unbalanced token.
        if paren_depth == 0 && statement[index..].starts_with("//") {
            // Sass line comment: skip to the next newline (or end of statement).
            match statement[index..].find('\n') {
                Some(newline_offset) => {
                    out.push('\n');
                    index += newline_offset + 1;
                }
                None => break,
            }
            continue;
        }
        match ch {
            '"' | '\'' => quote = Some(ch),
            '(' => paren_depth += 1,
            ')' => paren_depth = paren_depth.saturating_sub(1),
            _ => {}
        }
        out.push(ch);
        index += ch.len_utf8();
    }
    out
}

fn find_query_top_level_colon(statement: &str) -> Option<usize> {
    let mut index = 0usize;
    let mut quote: Option<char> = None;
    let mut paren_depth = 0usize;

    while index < statement.len() {
        let ch = statement[index..].chars().next()?;
        if let Some(quote_ch) = quote {
            index += ch.len_utf8();
            if ch == '\\' {
                if let Some(escaped) = statement[index..].chars().next() {
                    index += escaped.len_utf8();
                }
            } else if ch == quote_ch {
                quote = None;
            }
            continue;
        }

        match ch {
            '"' | '\'' => {
                quote = Some(ch);
                index += ch.len_utf8();
            }
            '(' => {
                paren_depth += 1;
                index += ch.len_utf8();
            }
            ')' => {
                paren_depth = paren_depth.saturating_sub(1);
                index += ch.len_utf8();
            }
            ':' if paren_depth == 0 => return Some(index),
            _ => index += ch.len_utf8(),
        }
    }
    None
}

fn query_prelude_start(source: &str, search_start: usize, open_index: usize) -> usize {
    source[search_start..open_index]
        .rfind(['{', '}', ';'])
        .map(|offset| search_start + offset + 1)
        .unwrap_or(search_start)
}

fn query_layer_name_from_prelude(prelude: &str) -> Option<String> {
    let rest = prelude.trim_start().strip_prefix("@layer")?.trim();
    let name = rest
        .split(|ch: char| ch.is_ascii_whitespace() || matches!(ch, ',' | '{' | ';'))
        .next()
        .unwrap_or_default()
        .trim_matches(['"', '\'']);
    if name.is_empty() {
        Some("(anonymous-layer)".to_string())
    } else {
        Some(name.to_string())
    }
}

fn normalize_query_condition_prelude(prelude: &str) -> String {
    prelude.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// RFC-0007-E4 (#45): recognize the `@at-root <selector>` form and return the trailing selector
/// list. Returns `None` for the bare block form (`@at-root { … }`, no selector) — which already
/// works via the generic selector recursion — and for the `@at-root (with: …) <selector>` /
/// `@at-root (without: …) <selector>` query forms, whose leading `(...)` clause we do not yet
/// model; those keep falling through to the generic at-rule handling rather than risk mis-rooting.
/// Any other at-rule returns `None`.
fn query_at_root_selector_from_prelude(prelude: &str) -> Option<String> {
    let rest = prelude.trim_start().strip_prefix("@at-root")?;
    // Require a boundary after the keyword so `@at-rootish` never matches.
    if let Some(next) = rest.chars().next()
        && !next.is_ascii_whitespace()
    {
        return None;
    }
    let selector = rest.trim();
    // Bare block form (no selector) or the `(with:/without:)` query form: defer to generic handling.
    if selector.is_empty() || selector.starts_with('(') {
        return None;
    }
    Some(selector.to_string())
}

fn collect_query_var_references_in_value(value: &str) -> Vec<String> {
    let mut refs = BTreeSet::new();
    let mut index = 0usize;
    let mut quote: Option<char> = None;
    while index < value.len() {
        let Some(ch) = value[index..].chars().next() else {
            break;
        };
        if let Some(quote_ch) = quote {
            index += ch.len_utf8();
            if ch == '\\' {
                if let Some(escaped) = value[index..].chars().next() {
                    index += escaped.len_utf8();
                }
            } else if ch == quote_ch {
                quote = None;
            }
            continue;
        }

        match ch {
            '"' | '\'' => {
                quote = Some(ch);
                index += ch.len_utf8();
            }
            _ if query_function_name_starts_at(value, index, "var") => {
                let open_index = index + "var".len();
                let Some(close_index) = matching_query_paren_end(value, open_index, value.len())
                else {
                    index += ch.len_utf8();
                    continue;
                };
                collect_query_var_references_from_arguments(
                    &value[open_index + 1..close_index],
                    &mut refs,
                );
                index = close_index + 1;
            }
            _ => {
                index += ch.len_utf8();
            }
        }
    }
    refs.into_iter().collect()
}

fn collect_query_var_references_from_arguments(arguments: &str, refs: &mut BTreeSet<String>) {
    let parts = split_query_top_level_arguments(arguments);
    let Some(first_argument) = parts.first().map(|part| part.trim()) else {
        return;
    };
    if first_argument.starts_with("--") {
        refs.insert(first_argument.to_string());
    }
    for fallback in parts.iter().skip(1) {
        for reference in collect_query_var_references_in_value(fallback) {
            refs.insert(reference);
        }
    }
}

fn split_query_top_level_arguments(arguments: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut start = 0usize;
    let mut index = 0usize;
    let mut quote: Option<char> = None;
    let mut paren_depth = 0usize;

    while index < arguments.len() {
        let Some(ch) = arguments[index..].chars().next() else {
            break;
        };
        if let Some(quote_ch) = quote {
            index += ch.len_utf8();
            if ch == '\\' {
                if let Some(escaped) = arguments[index..].chars().next() {
                    index += escaped.len_utf8();
                }
            } else if ch == quote_ch {
                quote = None;
            }
            continue;
        }

        match ch {
            '"' | '\'' => {
                quote = Some(ch);
                index += ch.len_utf8();
            }
            '(' => {
                paren_depth += 1;
                index += ch.len_utf8();
            }
            ')' => {
                paren_depth = paren_depth.saturating_sub(1);
                index += ch.len_utf8();
            }
            ',' if paren_depth == 0 => {
                parts.push(&arguments[start..index]);
                index += ch.len_utf8();
                start = index;
            }
            _ => {
                index += ch.len_utf8();
            }
        }
    }
    parts.push(&arguments[start..]);
    parts
}

fn query_function_name_starts_at(value: &str, index: usize, function_name: &str) -> bool {
    value
        .get(index..index + function_name.len())
        .is_some_and(|name| name.eq_ignore_ascii_case(function_name))
        && value[index + function_name.len()..].starts_with('(')
}

fn find_query_top_level_byte(source: &str, start: usize, end: usize, needle: u8) -> Option<usize> {
    let mut index = start;
    let mut quote: Option<char> = None;
    let mut paren_depth = 0usize;
    while index < end {
        let ch = source[index..].chars().next()?;
        if let Some(quote_ch) = quote {
            index += ch.len_utf8();
            if ch == '\\' {
                if let Some(escaped) = source[index..].chars().next() {
                    index += escaped.len_utf8();
                }
            } else if ch == quote_ch {
                quote = None;
            }
            continue;
        }
        if source[index..].starts_with("/*")
            && let Some(close_offset) = source[index + 2..end].find("*/")
        {
            index += close_offset + 4;
            continue;
        }
        // Sass `//` line comments outside parentheses are not declaration
        // boundaries, so a `;` (or `{`) buried in one must not be treated as a
        // statement delimiter (RFC-0007 B1). Inside parens (`url(http://…)`) the
        // `//` is part of a value, so it is left intact.
        if paren_depth == 0 && source[index..end].starts_with("//") {
            match source[index..end].find('\n') {
                Some(newline_offset) => {
                    index += newline_offset + 1;
                    continue;
                }
                None => return None,
            }
        }
        // Match the requested delimiter exactly as before (paren-unaware) so the
        // existing statement-boundary behavior is unchanged; `paren_depth` is
        // tracked only to gate the `//` line-comment skip above.
        if ch.len_utf8() == 1 && source.as_bytes()[index] == needle {
            return Some(index);
        }
        match ch {
            '"' | '\'' => {
                quote = Some(ch);
                index += ch.len_utf8();
            }
            '(' => {
                paren_depth += 1;
                index += ch.len_utf8();
            }
            ')' => {
                paren_depth = paren_depth.saturating_sub(1);
                index += ch.len_utf8();
            }
            _ => index += ch.len_utf8(),
        }
    }
    None
}

fn matching_query_block_end(source: &str, open_index: usize, end: usize) -> Option<usize> {
    matching_query_delimiter_end(source, open_index, end, b'{', b'}')
}

fn matching_query_paren_end(source: &str, open_index: usize, end: usize) -> Option<usize> {
    matching_query_delimiter_end(source, open_index, end, b'(', b')')
}

fn matching_query_delimiter_end(
    source: &str,
    open_index: usize,
    end: usize,
    open: u8,
    close: u8,
) -> Option<usize> {
    if source.as_bytes().get(open_index).copied()? != open {
        return None;
    }
    let mut index = open_index + 1;
    let mut depth = 1usize;
    let mut quote: Option<char> = None;
    // Only gate `//` line-comment skipping for brace matching, where a `}` in a
    // comment would otherwise close the block early. A `//` inside a value's
    // parentheses (`url(http://…)`) is part of the value, so it must be left
    // intact — track an inner paren depth to distinguish the two.
    let track_line_comments = open == b'{';
    let mut inner_paren_depth = 0usize;

    while index < end {
        let ch = source[index..].chars().next()?;
        if let Some(quote_ch) = quote {
            index += ch.len_utf8();
            if ch == '\\' {
                if let Some(escaped) = source[index..].chars().next() {
                    index += escaped.len_utf8();
                }
            } else if ch == quote_ch {
                quote = None;
            }
            continue;
        }
        if source[index..].starts_with("/*")
            && let Some(close_offset) = source[index + 2..end].find("*/")
        {
            index += close_offset + 4;
            continue;
        }
        // Sass `//` line comment: skip to the next newline so a `}` (RFC-0007 B1)
        // buried in a comment does not close the block prematurely. Restricted to
        // brace matching, and only outside value parentheses.
        if track_line_comments && inner_paren_depth == 0 && source[index..end].starts_with("//") {
            match source[index..end].find('\n') {
                Some(newline_offset) => {
                    index += newline_offset + 1;
                    continue;
                }
                None => return None,
            }
        }
        if track_line_comments {
            match ch {
                '(' => inner_paren_depth += 1,
                ')' => inner_paren_depth = inner_paren_depth.saturating_sub(1),
                _ => {}
            }
        }
        match ch {
            '"' | '\'' => {
                quote = Some(ch);
                index += ch.len_utf8();
            }
            _ if ch.len_utf8() == 1 && source.as_bytes()[index] == open => {
                depth += 1;
                index += 1;
            }
            _ if ch.len_utf8() == 1 && source.as_bytes()[index] == close => {
                depth -= 1;
                if depth == 0 {
                    return Some(index);
                }
                index += 1;
            }
            _ => index += ch.len_utf8(),
        }
    }
    None
}

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

    fn recorded(source: &str) -> Vec<(String, String, String)> {
        collect_query_checker_cascade_declarations(source)
            .into_iter()
            .map(|declaration| {
                (
                    declaration.input.selector,
                    declaration.input.property,
                    declaration.input.value,
                )
            })
            .collect()
    }

    fn diagnostic_codes(source: &str) -> Vec<&'static str> {
        summarize_query_cascade_checker_diagnostics_with_deep_analysis(
            "file:///tmp/test.scss",
            source,
            false,
        )
        .into_iter()
        .map(|diagnostic| diagnostic.code)
        .collect()
    }

    fn diagnostic_codes_with_deep_analysis(source: &str, deep_analysis: bool) -> Vec<&'static str> {
        summarize_query_cascade_checker_diagnostics_with_deep_analysis(
            "file:///tmp/test.scss",
            source,
            deep_analysis,
        )
        .into_iter()
        .map(|diagnostic| diagnostic.code)
        .collect()
    }

    fn cascade_codes(source: &str) -> Vec<&'static str> {
        diagnostic_codes(source)
            .into_iter()
            .filter(|code| matches!(*code, "unreachableDeclaration" | "unspecifiedCascadeTie"))
            .collect()
    }

    // ---- B1: comment poisoning ----------------------------------------

    #[test]
    fn b1_block_comment_before_property_does_not_drop_declaration() {
        let recorded = recorded(".a { /* primary */ color: red; color: blue; }");
        let properties: Vec<_> = recorded.iter().map(|(_, property, _)| property).collect();
        assert_eq!(properties, vec!["color", "color"], "{recorded:?}");
    }

    #[test]
    fn b1_block_comment_repro_fires_tie_and_unreachable() {
        let cascade = cascade_codes(".a { /* primary */ color: red; color: blue; }");
        assert!(
            cascade.contains(&"unreachableDeclaration")
                && cascade.contains(&"unspecifiedCascadeTie"),
            "expected both cascade diagnostics, got {cascade:?}"
        );
    }

    #[test]
    fn b1_line_comment_before_declarations_does_not_drop_them() {
        let cascade = cascade_codes(".a { // primary\ncolor: red; color: blue; }");
        assert!(
            cascade.contains(&"unreachableDeclaration")
                && cascade.contains(&"unspecifiedCascadeTie"),
            "expected both cascade diagnostics, got {cascade:?}"
        );
    }

    #[test]
    fn b1_value_comment_is_stripped_but_property_survives() {
        let recorded = recorded(".a { color /* c */ : red /* d */; }");
        assert_eq!(
            recorded,
            vec![(".a".to_string(), "color".to_string(), "red".to_string())],
            "comment-laden declaration should still record cleanly"
        );
    }

    // ---- B1 over-correction: commented-out declarations stay inert -----

    #[test]
    fn b1_line_commented_out_declaration_is_not_analyzed_as_live() {
        // The override is commented out, so there is no live duplicate / tie.
        let cascade = cascade_codes(".a { color: red; // color: blue;\n}");
        assert!(
            cascade.is_empty(),
            "commented-out decl must not tie: {cascade:?}"
        );
    }

    #[test]
    fn b1_block_commented_out_declaration_is_not_analyzed_as_live() {
        let cascade = cascade_codes(".a { color: red; /* color: blue; */ }");
        assert!(
            cascade.is_empty(),
            "commented-out decl must not tie: {cascade:?}"
        );
    }

    #[test]
    fn b1_url_with_double_slash_value_is_preserved_and_later_tie_still_fires() {
        // The `//` inside `url(http://…)` must not be treated as a line comment,
        // and the genuine `color` duplicate that follows must still tie.
        let source = ".a { background: url(http://example.com/a.png); color: red; color: blue; }";
        let recorded = recorded(source);
        assert!(
            recorded
                .iter()
                .any(|(_, property, value)| property == "background"
                    && value == "url(http://example.com/a.png)"),
            "url value should survive intact: {recorded:?}"
        );
        let cascade = cascade_codes(source);
        assert!(
            cascade.contains(&"unspecifiedCascadeTie"),
            "later real tie should still fire: {cascade:?}"
        );
    }

    // ---- B2: selector-list cross-rule tie -----------------------------

    #[test]
    fn b2_selector_list_member_records_separately() {
        let recorded = recorded(".a, .b { color: red; }");
        let selectors: Vec<_> = recorded.iter().map(|(selector, ..)| selector).collect();
        assert_eq!(selectors, vec![".a", ".b"], "{recorded:?}");
    }

    #[test]
    fn b2_selector_list_member_ties_with_sibling_rule() {
        let cascade = cascade_codes(".a, .b { color: red; }\n.a { color: blue; }");
        assert!(
            cascade.contains(&"unreachableDeclaration")
                && cascade.contains(&"unspecifiedCascadeTie"),
            "list member .a should tie with .a sibling: {cascade:?}"
        );
    }

    // ---- B2 over-correction: no spurious ties -------------------------

    #[test]
    fn b2_distinct_list_member_does_not_tie_with_unrelated_rule() {
        // `.a, .b` vs `.c` share no selector, so no tie may be reported.
        let cascade = cascade_codes(".a, .b { color: red; }\n.c { color: blue; }");
        assert!(
            cascade.is_empty(),
            "unrelated rule must not tie: {cascade:?}"
        );
    }

    #[test]
    fn b2_duplicate_member_in_one_prelude_is_deduplicated() {
        // `.a, .a` is a single rule; the duplicated member must not self-tie.
        let recorded = recorded(".a, .a { color: red; }");
        assert_eq!(
            recorded.len(),
            1,
            "identical members must be de-duplicated: {recorded:?}"
        );
        let cascade = cascade_codes(".a, .a { color: red; }");
        assert!(
            cascade.is_empty(),
            "deduped member must not self-tie: {cascade:?}"
        );
    }

    #[test]
    fn b2_comma_inside_functional_pseudo_is_not_split() {
        // The comma inside `:is(.a, .b)` is paren-protected, so the rule records
        // as a single opaque-compound selector rather than two bogus members.
        let recorded = recorded(":is(.a, .b) { color: red; }");
        let selectors: Vec<_> = recorded.iter().map(|(selector, ..)| selector).collect();
        assert_eq!(selectors, vec![":is(.a, .b)"], "{recorded:?}");
    }

    // ---- WP7-b: de-noise rg-flow + categorical theory hints -----------

    /// A two-property custom-property reference cycle that the product chain
    /// flags as `circularVar`.
    const VAR_CYCLE_SOURCE: &str = ":root { --a: var(--b); --b: var(--a); }";

    #[test]
    fn wp7b_var_cycle_still_fires_circular_var_warning() {
        // Over-correction guard: the product `circularVar` warning must keep
        // firing on a real custom-property reference cycle regardless of the
        // deep-analysis flag — the dedup removes only the theory hints.
        for deep_analysis in [false, true] {
            let codes = diagnostic_codes_with_deep_analysis(VAR_CYCLE_SOURCE, deep_analysis);
            assert!(
                codes.contains(&"circularVar"),
                "circularVar must still fire on a real var cycle (deep_analysis={deep_analysis}): {codes:?}"
            );
        }
    }

    #[test]
    fn wp7b_default_surface_var_cycle_emits_only_circular_var() {
        // Default surface (deep-analysis OFF): a lone var cycle yields exactly the
        // `circularVar` warning and no whole-file-ranged theory hints.
        let codes = diagnostic_codes(VAR_CYCLE_SOURCE);
        assert!(
            codes.contains(&"circularVar"),
            "circularVar must fire on the default surface: {codes:?}"
        );
        assert!(
            !codes.contains(&"rgFlowRelevantOperator"),
            "rg-flow theory hint must be OFF by default: {codes:?}"
        );
        assert!(
            !codes.contains(&"categoricalCascadeEvidenceInconsistency"),
            "categorical theory hint must be OFF by default: {codes:?}"
        );
        // No theory triple-fire: the cycle yields the product `circularVar`
        // warning (and any other product cascade diagnostics) but neither of the
        // two redundant, whole-file-ranged theory hints.
        assert!(
            codes.iter().all(|code| !matches!(
                *code,
                "rgFlowRelevantOperator" | "categoricalCascadeEvidenceInconsistency"
            )),
            "default surface must surface no theory hints for a lone var cycle: {codes:?}"
        );
    }

    #[test]
    fn wp7b_deep_analysis_dedups_theory_hints_into_circular_var() -> Result<(), &'static str> {
        // Deep-analysis ON: the rg-flow + categorical hints key off the same
        // reference-cycle predicate as `circularVar`, so they are deduplicated
        // (folded into `circularVar`'s provenance) rather than triple-firing.
        let codes = diagnostic_codes_with_deep_analysis(VAR_CYCLE_SOURCE, true);
        assert!(
            codes.contains(&"circularVar"),
            "circularVar must fire with deep analysis ON: {codes:?}"
        );
        assert!(
            !codes.contains(&"rgFlowRelevantOperator"),
            "rg-flow hint must be deduplicated against circularVar: {codes:?}"
        );
        assert!(
            !codes.contains(&"categoricalCascadeEvidenceInconsistency"),
            "categorical hint must be deduplicated against circularVar: {codes:?}"
        );

        // The suppressed theory mechanisms' provenance is merged into the
        // surviving `circularVar` diagnostic so the audit trail is preserved.
        let diagnostics = summarize_query_cascade_checker_diagnostics_with_deep_analysis(
            "file:///tmp/test.scss",
            VAR_CYCLE_SOURCE,
            true,
        );
        let circular_var = diagnostics
            .iter()
            .find(|diagnostic| diagnostic.code == "circularVar")
            .ok_or("circularVar diagnostic must exist")?;
        assert!(
            circular_var
                .provenance
                .iter()
                .any(|label| label.contains("rg-flow")),
            "rg-flow provenance should be folded into circularVar: {:?}",
            circular_var.provenance
        );
        assert!(
            circular_var
                .provenance
                .iter()
                .any(|label| label.contains("categorical")),
            "categorical provenance should be folded into circularVar: {:?}",
            circular_var.provenance
        );
        Ok(())
    }

    #[test]
    fn wp7b_deep_analysis_reaches_theory_gate_on_cyclic_input() {
        // With deep-analysis ON the theory producers are reachable (the gate runs)
        // even though their output is deduplicated here: the rg-flow coupling and
        // categorical mapping are both populated for a cyclic stylesheet, so the
        // underlying mechanisms still execute (proving the opt-in path is live).
        let (checker_input, _, _) =
            collect_query_checker_cascade_input("file:///tmp/test.scss", VAR_CYCLE_SOURCE);
        let rg_flow = summarize_query_rg_flow_coupling_diagnostics(
            VAR_CYCLE_SOURCE,
            &checker_input.custom_properties,
        );
        let categorical = summarize_query_categorical_cascade_evidence_diagnostics(
            VAR_CYCLE_SOURCE,
            &checker_input.custom_properties,
        );
        assert!(
            !rg_flow.is_empty(),
            "rg-flow theory gate should fire on a cyclic stylesheet when reached"
        );
        assert!(
            !categorical.is_empty(),
            "categorical theory gate should fire on a cyclic stylesheet when reached"
        );
    }

    #[test]
    fn wp7b_acyclic_stylesheet_emits_no_theory_hints_even_with_deep_analysis() {
        // Over-correction guard (the other direction): an acyclic custom-property
        // graph must not spuriously surface a theory hint under deep analysis.
        let acyclic = ":root { --a: 1px; --b: var(--a); }";
        let codes = diagnostic_codes_with_deep_analysis(acyclic, true);
        assert!(
            !codes.contains(&"rgFlowRelevantOperator")
                && !codes.contains(&"categoricalCascadeEvidenceInconsistency"),
            "acyclic stylesheet must not surface theory hints: {codes:?}"
        );
    }

    #[test]
    fn wp7b_acyclic_high_gain_hub_surfaces_standalone_rg_flow_hint() {
        let high_gain = r#"
:root {
  --seed: 1px;
  --a: var(--seed);
  --b: var(--seed);
  --c: var(--seed);
  --d: var(--seed);
}
"#;

        let default_codes = diagnostic_codes_with_deep_analysis(high_gain, false);
        assert!(
            !default_codes.contains(&"rgFlowRelevantOperator"),
            "rg-flow theory hint must stay off on the default surface: {default_codes:?}"
        );

        let deep_codes = diagnostic_codes_with_deep_analysis(high_gain, true);
        assert!(
            deep_codes.contains(&"rgFlowRelevantOperator"),
            "acyclic high-gain hub should surface a standalone rg-flow hint: {deep_codes:?}"
        );
        assert!(
            !deep_codes.contains(&"circularVar"),
            "standalone rg-flow hint must not depend on circularVar: {deep_codes:?}"
        );
    }
}