omena-query 0.3.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
use crate::{
    OmenaQuerySourceImportedStyleBindingV0, OmenaQuerySourceMissingSelectorDiagnosticCandidateV0,
    OmenaQuerySourceSelectorCandidateV0, OmenaQuerySourceSelectorReferenceEditTargetV0,
    OmenaQuerySourceSelectorReferenceFactV0, OmenaQuerySourceSelectorReferenceMatchKindV0,
    OmenaQuerySourceSyntaxIndexV0, OmenaQuerySourceTypeFactProviderUnavailableFactV0,
    OmenaQueryStyleModuleDiskCandidateIdentityV0, OmenaQueryStyleResolutionInputsV0,
    OmenaQueryStyleSelectorDefinitionV0, OmenaQueryStyleSourceInputV0,
    OmenaQueryTsconfigPathMappingV0, ParserByteSpanV0, ParserPositionV0, ParserRangeV0,
    canonicalize_omena_query_source_selector_references, is_omena_query_sass_symbol_candidate_kind,
    is_omena_query_sass_symbol_reference_kind, omena_query_sass_symbol_kind_from_candidate_kind,
    omena_query_sass_symbol_target_matches, resolve_omena_query_sass_forward_sources,
    resolve_omena_query_sass_module_use_sources_for_candidate,
    resolve_omena_query_sass_symbol_declarations, resolve_omena_query_selector_rename_edits,
    resolve_omena_query_source_candidate_selector_names,
    resolve_omena_query_source_provider_candidates,
    resolve_omena_query_style_selector_definitions_for_source_candidate,
    resolve_omena_query_style_uri_for_specifier, summarize_omena_query_sass_module_sources,
    summarize_omena_query_source_diagnostics_for_file,
    summarize_omena_query_source_diagnostics_for_workspace_file,
    summarize_omena_query_source_diagnostics_for_workspace_file_with_context_depth,
    summarize_omena_query_source_diagnostics_for_workspace_file_with_resolution_inputs,
    summarize_omena_query_source_diagnostics_for_workspace_file_with_source_syntax_index,
    summarize_omena_query_source_import_declarations, summarize_omena_query_source_syntax_index,
    summarize_omena_query_style_hover_candidates,
};

#[test]
fn source_candidate_matching_normalizes_percent_encoded_file_uris() {
    let source_range = ParserRangeV0 {
        start: ParserPositionV0 {
            line: 0,
            character: 0,
        },
        end: ParserPositionV0 {
            line: 0,
            character: 4,
        },
    };
    let definition_range = ParserRangeV0 {
        start: ParserPositionV0 {
            line: 1,
            character: 1,
        },
        end: ParserPositionV0 {
            line: 1,
            character: 5,
        },
    };
    let candidate = OmenaQuerySourceSelectorCandidateV0 {
        kind: "sourceSelectorPrefixReference",
        name: "btn-".to_string(),
        range: source_range,
        source: "omenaQuerySourceSyntaxIndex",
        target_style_uri: Some(
            "file:///workspace/app/%28marketing%29/Button.module.scss".to_string(),
        ),
    };
    let definitions = vec![OmenaQueryStyleSelectorDefinitionV0 {
        uri: "file:///workspace/app/(marketing)/Button.module.scss".to_string(),
        name: "btn-primary".to_string(),
        range: definition_range,
    }];

    assert_eq!(
        resolve_omena_query_source_candidate_selector_names(
            &candidate,
            definitions.as_slice(),
            None,
        ),
        vec!["btn-primary".to_string()]
    );
}

#[test]
fn source_syntax_index_adapter_is_query_owned_without_changing_product() {
    let style_uri = resolve_omena_query_style_uri_for_specifier(
        "file:///workspace/src/Button.tsx",
        Some("file:///workspace"),
        "./Button.module.scss",
    );
    assert_eq!(
        style_uri.as_deref(),
        Some("file:///workspace/src/Button.module.scss")
    );
    let style_uri = style_uri.unwrap_or_default();
    assert_eq!(style_uri, "file:///workspace/src/Button.module.scss");

    let import_summary = summarize_omena_query_source_import_declarations(
        "import styles from './Button.module.scss';",
    );
    assert_eq!(import_summary.import_count, 1);
    assert_eq!(import_summary.imports[0].binding, "styles");

    let source = "import styles from './Button.module.scss';\nconst el = styles.root;\n";
    let mut index = summarize_omena_query_source_syntax_index(
        source,
        vec![OmenaQuerySourceImportedStyleBindingV0 {
            binding: "styles".to_string(),
            style_uri,
        }],
        Vec::new(),
    );
    assert_eq!(index.product, "omena-bridge.source-syntax-index");
    assert_eq!(index.selector_references.len(), 1);
    let reference = &index.selector_references[0];
    assert_eq!(
        &source[reference.byte_span.start..reference.byte_span.end],
        "root"
    );

    canonicalize_omena_query_source_selector_references(&mut index.selector_references);
    assert_eq!(index.selector_references.len(), 1);
}

#[test]
fn source_diagnostics_for_file_are_query_owned() {
    let diagnostics = summarize_omena_query_source_diagnostics_for_file(
        "file:///workspace/src/App.tsx",
        &[OmenaQuerySourceMissingSelectorDiagnosticCandidateV0 {
            target_style_uri: "file:///workspace/src/App.module.scss".to_string(),
            target_style_source: ".root {\n}\n".to_string(),
            selector_name: "missing".to_string(),
            source_reference_range: ParserRangeV0 {
                start: ParserPositionV0 {
                    line: 2,
                    character: 18,
                },
                end: ParserPositionV0 {
                    line: 2,
                    character: 25,
                },
            },
        }],
    );

    assert_eq!(diagnostics.product, "omena-query.diagnostics-for-file");
    assert_eq!(diagnostics.file_kind, "source");
    assert_eq!(diagnostics.diagnostic_count, 1);
    assert_eq!(diagnostics.diagnostics[0].code, "missingSelector");
    assert_eq!(
        diagnostics.diagnostics[0].provenance.as_slice(),
        [
            "omena-query.source-syntax-index",
            "omena-query.style-selector-definitions",
            "omena-query-checker-orchestrator.product-diagnostic-gate",
            "omena-checker.rule-registry",
        ]
    );
    assert!(
        diagnostics
            .ready_surfaces
            .contains(&"crossLanguageDiagnostics")
    );
    assert!(
        diagnostics
            .ready_surfaces
            .contains(&"checkerProductDiagnosticGate")
    );
}

#[test]
fn source_diagnostics_for_workspace_file_are_query_owned() -> Result<(), String> {
    let diagnostics = summarize_omena_query_source_diagnostics_for_workspace_file(
        "/workspace/src/App.tsx",
        r#"import bind from "classnames/bind";
import styles from "./App.module.scss";
import missing from "./Missing.module.scss";
const cx = bind.bind(styles);
const variant = Math.random() > 0.5 ? "chip" : "ghost";
const dynamicPrefix = "lost-" + suffix;
export function App({ suffix }) {
  return <div className={cx("ghost", variant, dynamicPrefix, `empty-${suffix}`)} data-x={styles.ghost} />;
}"#,
        &[OmenaQueryStyleSourceInputV0 {
            style_path: "/workspace/src/App.module.scss".to_string(),
            style_source: ".root {}\n.chip {}\n".to_string(),
        }],
        &[],
    );

    let codes = diagnostics
        .diagnostics
        .iter()
        .map(|diagnostic| diagnostic.code)
        .collect::<Vec<_>>();
    assert_eq!(diagnostics.product, "omena-query.diagnostics-for-file");
    assert_eq!(diagnostics.file_kind, "source");
    assert!(codes.contains(&"missingModule"));
    assert!(codes.contains(&"missingStaticClass"));
    assert!(codes.contains(&"missingResolvedClassValues"));
    assert!(codes.contains(&"missingResolvedClassDomain"));
    assert!(codes.contains(&"missingTemplatePrefix"));
    let checker_product_diagnostic_provenance = [
        "omena-query.source-syntax-index",
        "omena-query.style-selector-definitions",
        "omena-query-checker-orchestrator.product-diagnostic-gate",
        "omena-checker.rule-registry",
    ];
    for code in ["missingStaticClass", "missingTemplatePrefix"] {
        let diagnostic = diagnostics
            .diagnostics
            .iter()
            .find(|diagnostic| diagnostic.code == code)
            .ok_or_else(|| format!("expected source selector diagnostic for {code}"))?;
        assert_eq!(
            diagnostic.provenance.as_slice(),
            checker_product_diagnostic_provenance.as_slice()
        );
        let precision = diagnostic
            .precision
            .as_ref()
            .ok_or_else(|| format!("{code} must carry source diagnostic precision"))?;
        assert_eq!(precision.product, "omena-query.analysis-precision");
        assert_eq!(precision.value_domain, "classValueResolution");
        assert_eq!(
            precision.revision_axis,
            "OmenaQuerySourceDiagnosticsForFileV0.input"
        );
    }
    assert_eq!(
        diagnostics
            .diagnostics
            .iter()
            .find(|diagnostic| diagnostic.code == "missingModule")
            .map(|diagnostic| diagnostic.provenance.as_slice()),
        Some(
            [
                "omena-query.source-import-declarations",
                "omena-resolver.style-module-resolution",
                "omena-query-checker-orchestrator.product-diagnostic-gate",
                "omena-checker.rule-registry",
            ]
            .as_slice()
        )
    );
    assert!(
        diagnostics
            .ready_surfaces
            .contains(&"sourceResolvedClassDiagnostics")
    );
    assert!(
        diagnostics
            .ready_surfaces
            .contains(&"checkerProductDiagnosticGate")
    );
    Ok(())
}

#[test]
fn workspace_source_diagnostics_resolve_aliases_and_preserve_missing_targets() {
    let source_path = "/workspace/src/App.tsx";
    let style_path = "/workspace/src/styles/App.module.scss";
    let source = r#"import styles from "@styles/App.module.scss";
import missing from "@styles/Missing.module.scss";
export const app = <div className={styles.ghost} />;"#;
    let style_sources = [OmenaQueryStyleSourceInputV0 {
        style_path: style_path.to_string(),
        style_source: ".root {}\n".to_string(),
    }];
    let resolution_inputs = OmenaQueryStyleResolutionInputsV0 {
        tsconfig_path_mappings: vec![OmenaQueryTsconfigPathMappingV0 {
            base_path: "/workspace".to_string(),
            pattern: "@styles/*".to_string(),
            target_patterns: vec!["src/styles/*".to_string()],
        }],
        disk_style_path_identities: vec![OmenaQueryStyleModuleDiskCandidateIdentityV0 {
            style_path: style_path.to_string(),
            metadata_identity: "fixture|app-module".to_string(),
        }],
        ..OmenaQueryStyleResolutionInputsV0::default()
    };

    let summary =
        summarize_omena_query_source_diagnostics_for_workspace_file_with_resolution_inputs(
            source_path,
            source,
            &style_sources,
            &[],
            &resolution_inputs,
        );
    let missing_modules = summary
        .diagnostics
        .iter()
        .filter(|diagnostic| diagnostic.code == "missingModule")
        .collect::<Vec<_>>();

    assert_eq!(missing_modules.len(), 1, "{summary:?}");
    assert!(missing_modules[0].message.contains("Missing.module.scss"));
    assert!(
        missing_modules[0]
            .message
            .contains("The file does not exist.")
    );
    assert!(
        summary
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.code == "missingStaticClass"),
        "the resolved alias binding must feed selector diagnostics: {summary:?}"
    );
}

#[test]
fn workspace_source_diagnostics_do_not_claim_nonexistence_without_disk_evidence()
-> Result<(), &'static str> {
    let summary =
        summarize_omena_query_source_diagnostics_for_workspace_file_with_resolution_inputs(
            "/workspace/src/App.tsx",
            r#"import missing from "@styles/Missing.module.scss";"#,
            &[],
            &[],
            &OmenaQueryStyleResolutionInputsV0 {
                tsconfig_path_mappings: vec![OmenaQueryTsconfigPathMappingV0 {
                    base_path: "/workspace".to_string(),
                    pattern: "@styles/*".to_string(),
                    target_patterns: vec!["src/styles/*".to_string()],
                }],
                ..OmenaQueryStyleResolutionInputsV0::default()
            },
        );
    let diagnostic = summary
        .diagnostics
        .iter()
        .find(|diagnostic| diagnostic.code == "missingModule")
        .ok_or("the unresolved module must remain diagnostic")?;

    assert!(diagnostic.message.contains("provided workspace inputs"));
    assert!(!diagnostic.message.contains("does not exist"));
    Ok(())
}

#[test]
fn legacy_workspace_source_diagnostics_delegate_neutrally_for_relative_imports() {
    let source_path = "/workspace/src/App.tsx";
    let source = r#"import styles from "./App.module.scss";
export const app = <div className={styles.ghost} />;"#;
    let style_sources = [OmenaQueryStyleSourceInputV0 {
        style_path: "/workspace/src/App.module.scss".to_string(),
        style_source: ".root {}\n".to_string(),
    }];

    let legacy = summarize_omena_query_source_diagnostics_for_workspace_file(
        source_path,
        source,
        &style_sources,
        &[],
    );
    let explicit =
        summarize_omena_query_source_diagnostics_for_workspace_file_with_resolution_inputs(
            source_path,
            source,
            &style_sources,
            &[],
            &OmenaQueryStyleResolutionInputsV0::default(),
        );

    assert_eq!(legacy, explicit);
}

#[test]
fn source_diagnostics_missing_static_class_carries_query_owned_suggestion() -> Result<(), String> {
    let diagnostics = summarize_omena_query_source_diagnostics_for_workspace_file(
        "/workspace/src/App.tsx",
        r#"import styles from "./App.module.scss";
const value = styles.unknonw;
"#,
        &[OmenaQueryStyleSourceInputV0 {
            style_path: "/workspace/src/App.module.scss".to_string(),
            style_source: ".unknown {}\n".to_string(),
        }],
        &[],
    );

    let diagnostic = diagnostics
        .diagnostics
        .iter()
        .find(|diagnostic| diagnostic.code == "missingStaticClass")
        .ok_or_else(|| {
            format!(
                "the typo must be reported as a Rust-owned source diagnostic: {:?}",
                diagnostics.diagnostics
            )
        })?;
    assert_eq!(diagnostic.suggestion.as_deref(), Some("unknown"));
    assert!(
        diagnostic.message.contains("Did you mean 'unknown'?"),
        "query-owned message should carry the replacement hint: {}",
        diagnostic.message
    );
    let json = serde_json::to_value(diagnostic)
        .map_err(|error| format!("source diagnostic serializes: {error}"))?;
    assert_eq!(json["suggestion"], "unknown");
    Ok(())
}

#[test]
fn source_diagnostics_consume_precomputed_source_syntax_index() {
    let source_path = "/workspace/src/App.tsx";
    let source = "const view = styles.ghost;";
    assert!(source.contains("ghost"), "fixture should contain selector");
    let selector_start = source.find("ghost").unwrap_or_default();
    let style_uri = "/workspace/src/App.module.scss";
    let diagnostics =
        summarize_omena_query_source_diagnostics_for_workspace_file_with_source_syntax_index(
            source_path,
            source,
            &OmenaQuerySourceSyntaxIndexV0 {
                schema_version: "0",
                product: "omena-bridge.source-syntax-index",
                imported_style_bindings: vec![OmenaQuerySourceImportedStyleBindingV0 {
                    binding: "styles".to_string(),
                    style_uri: style_uri.to_string(),
                }],
                class_string_literals: Vec::new(),
                style_property_accesses: Vec::new(),
                inline_style_declarations: Vec::new(),
                selector_references: vec![OmenaQuerySourceSelectorReferenceFactV0 {
                    byte_span: ParserByteSpanV0 {
                        start: selector_start,
                        end: selector_start + "ghost".len(),
                    },
                    selector_name: Some("ghost".to_string()),
                    match_kind: OmenaQuerySourceSelectorReferenceMatchKindV0::Exact,
                    target_style_uri: Some(style_uri.to_string()),
                }],
                type_fact_targets: Vec::new(),
                type_fact_provider_unavailable: Vec::new(),
                class_value_universes: Vec::new(),
                domain_class_references: Vec::new(),
                source_elements: Vec::new(),
                element_parent_edges: Vec::new(),
            },
            &[OmenaQueryStyleSourceInputV0 {
                style_path: style_uri.to_string(),
                style_source: ".root {}".to_string(),
            }],
        );

    assert_eq!(diagnostics.product, "omena-query.diagnostics-for-file");
    assert!(
        diagnostics
            .ready_surfaces
            .contains(&"sourceIndexedSyntaxDiagnostics")
    );
    assert!(
        diagnostics
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.code == "missingStaticClass"),
        "precomputed source syntax index should drive source diagnostics without reparsing imports: {:?}",
        diagnostics.diagnostics
    );
    assert!(
        diagnostics
            .diagnostics
            .iter()
            .all(|diagnostic| diagnostic.code != "missingModule"),
        "the precomputed-index path should not synthesize import-resolution diagnostics"
    );
}

#[test]
fn source_diagnostics_surface_variant_recipe_option_universe() {
    let diagnostics = summarize_omena_query_source_diagnostics_for_workspace_file(
        "/workspace/src/App.tsx",
        r#"import { cva } from "class-variance-authority";
const button = cva("btn", {
  variants: {
    intent: {
      primary: "btn-primary",
      secondary: "btn-secondary",
    },
  },
});
button({ intent: "primary" });
button({ intent: "ghost" });
"#,
        &[],
        &[],
    );

    let missing_options = diagnostics
        .diagnostics
        .iter()
        .filter(|diagnostic| diagnostic.code == "missingClassValueOption")
        .collect::<Vec<_>>();
    assert_eq!(missing_options.len(), 1, "{diagnostics:?}");
    assert!(
        missing_options[0]
            .message
            .contains("Class value option 'ghost' is not defined for button.intent")
    );
    assert_eq!(
        missing_options[0].provenance,
        vec![
            "omena-bridge.class-value-universe-provider",
            "omena-query.source-domain-class-references"
        ]
    );
}

#[test]
fn source_diagnostics_tag_tsgo_unavailable_type_fact_as_unknown_precision()
-> Result<(), Box<dyn std::error::Error>> {
    let source_path = "/workspace/src/App.tsx";
    let source = "const className = cx(size);";
    let size_start = source.find("size").unwrap_or_default();
    let style_uri = "/workspace/src/App.module.scss";
    let diagnostics =
        summarize_omena_query_source_diagnostics_for_workspace_file_with_source_syntax_index(
            source_path,
            source,
            &OmenaQuerySourceSyntaxIndexV0 {
                schema_version: "0",
                product: "omena-bridge.source-syntax-index",
                imported_style_bindings: vec![OmenaQuerySourceImportedStyleBindingV0 {
                    binding: "styles".to_string(),
                    style_uri: style_uri.to_string(),
                }],
                class_string_literals: Vec::new(),
                style_property_accesses: Vec::new(),
                inline_style_declarations: Vec::new(),
                selector_references: Vec::new(),
                type_fact_targets: Vec::new(),
                type_fact_provider_unavailable: vec![
                    OmenaQuerySourceTypeFactProviderUnavailableFactV0 {
                        byte_span: ParserByteSpanV0 {
                            start: size_start,
                            end: size_start + "size".len(),
                        },
                        expression_id: "expr-size".to_string(),
                        target_style_uri: Some(style_uri.to_string()),
                        provider_id: "tsgo",
                        reason: "unresolvable",
                    },
                ],
                class_value_universes: Vec::new(),
                domain_class_references: Vec::new(),
                source_elements: Vec::new(),
                element_parent_edges: Vec::new(),
            },
            &[OmenaQueryStyleSourceInputV0 {
                style_path: style_uri.to_string(),
                style_source: ".small {}".to_string(),
            }],
        );

    let diagnostic = diagnostics
        .diagnostics
        .iter()
        .find(|diagnostic| diagnostic.code == "unknownClassValueDomain")
        .ok_or_else(|| {
            std::io::Error::other(
                "tsgo-unavailable fact must produce an unknown precision diagnostic",
            )
        })?;
    let precision = diagnostic
        .precision
        .as_ref()
        .ok_or_else(|| std::io::Error::other("unknown provider diagnostic must carry precision"))?;
    assert_eq!(precision.value_domain, "unknown");
    assert_eq!(precision.flow_sensitivity, "typeOracleProviderUnavailable");
    assert!(
        diagnostic
            .provenance
            .contains(&"tsgo-provider.unavailable->unknown-precision")
    );
    assert!(
        !diagnostic.message.contains("small"),
        "provider-unavailable diagnostic must not guess a concrete selector"
    );
    assert!(diagnostic.create_selector.is_none());
    // The open-string arm is a property of the CODE, so it carries the one
    // action that lifts it and stays at hint severity.
    assert_eq!(diagnostic.severity, "hint");
    assert!(
        diagnostic
            .suggestion
            .as_deref()
            .is_some_and(|suggestion| suggestion.contains("string-literal union")),
        "the open-type disclosure must carry the narrowing action"
    );
    Ok(())
}

#[test]
fn source_provider_candidate_resolution_is_query_owned() {
    let source_range = ParserRangeV0 {
        start: ParserPositionV0 {
            line: 0,
            character: 0,
        },
        end: ParserPositionV0 {
            line: 0,
            character: 4,
        },
    };
    let definition_range = ParserRangeV0 {
        start: ParserPositionV0 {
            line: 1,
            character: 1,
        },
        end: ParserPositionV0 {
            line: 1,
            character: 5,
        },
    };

    let resolution = resolve_omena_query_source_provider_candidates(
        vec![
            OmenaQuerySourceSelectorCandidateV0 {
                kind: "sourceSelectorReference",
                name: "root".to_string(),
                range: source_range,
                source: "omenaQuerySourceSyntaxIndex",
                target_style_uri: Some("file:///workspace/src/App.module.scss".to_string()),
            },
            OmenaQuerySourceSelectorCandidateV0 {
                kind: "sourceSelectorPrefixReference",
                name: "btn-".to_string(),
                range: source_range,
                source: "omenaQuerySourceSyntaxIndex",
                target_style_uri: Some("file:///workspace/src/App.module.scss".to_string()),
            },
            OmenaQuerySourceSelectorCandidateV0 {
                kind: "sourceSelectorReference",
                name: "ghost".to_string(),
                range: source_range,
                source: "omenaQuerySourceSyntaxIndex",
                target_style_uri: Some("file:///workspace/src/Other.module.scss".to_string()),
            },
        ],
        &[
            OmenaQueryStyleSelectorDefinitionV0 {
                uri: "file:///workspace/src/App.module.scss".to_string(),
                name: "root".to_string(),
                range: definition_range,
            },
            OmenaQueryStyleSelectorDefinitionV0 {
                uri: "file:///workspace/src/App.module.scss".to_string(),
                name: "btn-primary".to_string(),
                range: definition_range,
            },
        ],
    );

    assert_eq!(
        resolution
            .matched
            .iter()
            .map(|candidate| candidate.name.as_str())
            .collect::<Vec<_>>(),
        vec!["btn-", "root"]
    );
    assert_eq!(
        resolution
            .unresolved
            .iter()
            .map(|candidate| candidate.name.as_str())
            .collect::<Vec<_>>(),
        vec!["ghost"]
    );

    let prefix_candidate = &resolution.matched[0];
    let definitions = vec![
        OmenaQueryStyleSelectorDefinitionV0 {
            uri: "file:///workspace/src/App.module.scss".to_string(),
            name: "root".to_string(),
            range: definition_range,
        },
        OmenaQueryStyleSelectorDefinitionV0 {
            uri: "file:///workspace/src/App.module.scss".to_string(),
            name: "btn-primary".to_string(),
            range: definition_range,
        },
    ];
    assert_eq!(
        resolve_omena_query_source_candidate_selector_names(
            prefix_candidate,
            definitions.as_slice(),
            None
        ),
        vec!["btn-primary".to_string()]
    );
    assert_eq!(
        resolve_omena_query_style_selector_definitions_for_source_candidate(
            prefix_candidate,
            definitions.as_slice(),
        )
        .into_iter()
        .map(|definition| definition.name)
        .collect::<Vec<_>>(),
        vec!["btn-primary".to_string()]
    );
}

#[test]
fn selector_rename_edit_planning_is_query_owned() {
    let source_range = ParserRangeV0 {
        start: ParserPositionV0 {
            line: 3,
            character: 16,
        },
        end: ParserPositionV0 {
            line: 3,
            character: 20,
        },
    };
    let definition_range = ParserRangeV0 {
        start: ParserPositionV0 {
            line: 0,
            character: 1,
        },
        end: ParserPositionV0 {
            line: 0,
            character: 5,
        },
    };

    let edits = resolve_omena_query_selector_rename_edits(
        "root",
        ".shell",
        Some("file:///workspace/src/App.module.scss"),
        &[OmenaQueryStyleSelectorDefinitionV0 {
            uri: "file:///workspace/src/App.module.scss".to_string(),
            name: "root".to_string(),
            range: definition_range,
        }],
        &[OmenaQuerySourceSelectorReferenceEditTargetV0 {
            uri: "file:///workspace/src/App.tsx".to_string(),
            name: "root".to_string(),
            range: source_range,
            target_style_uri: Some("file:///workspace/src/App.module.scss".to_string()),
        }],
    );

    assert_eq!(
        edits
            .iter()
            .map(|edit| (edit.uri.as_str(), edit.new_text.as_str()))
            .collect::<Vec<_>>(),
        vec![
            ("file:///workspace/src/App.module.scss", "shell"),
            ("file:///workspace/src/App.tsx", "shell"),
        ]
    );
}

#[test]
fn sass_symbol_matching_is_query_owned() {
    let source = "$accent: red;\n.button { color: $accent; }\n";
    let Some(candidates) =
        summarize_omena_query_style_hover_candidates("Component.module.scss", source)
    else {
        return;
    };

    assert!(is_omena_query_sass_symbol_candidate_kind(
        "sassVariableDeclaration"
    ));
    assert!(is_omena_query_sass_symbol_reference_kind(
        "sassVariableReference"
    ));
    assert_eq!(
        omena_query_sass_symbol_kind_from_candidate_kind("sassVariableReference"),
        Some("variable")
    );
    assert!(omena_query_sass_symbol_target_matches(
        "sassVariableReference",
        "accent",
        None,
        "sassVariableDeclaration",
        "accent",
        None,
    ));

    let declarations = resolve_omena_query_sass_symbol_declarations(
        candidates.candidates.as_slice(),
        "variable",
        "accent",
    );
    assert_eq!(declarations.len(), 1);
    assert_eq!(declarations[0].kind, "sassVariableDeclaration");
}

#[test]
fn sass_module_sources_are_query_owned() {
    let sources = summarize_omena_query_sass_module_sources(
        "Component.module.scss",
        r#"
@use "./tokens" as tokens;
@use "./reset" as *;
@use "sass:map";
@import "./legacy";
@forward "./theme";
@forward "sass:color";
"#,
    );
    assert!(sources.is_some());
    let Some(sources) = sources else {
        return;
    };

    assert_eq!(sources.product, "omena-query.sass-module-sources");
    assert!(sources.module_use_edges.iter().any(|edge| {
        edge.source == "./tokens"
            && edge.namespace.as_deref() == Some("tokens")
            && edge.namespace_kind == "alias"
    }));
    assert!(sources.module_use_edges.iter().any(|edge| {
        edge.source == "./reset" && edge.namespace.is_none() && edge.namespace_kind == "wildcard"
    }));
    assert!(sources.module_use_edges.iter().any(|edge| {
        edge.source == "./legacy" && edge.namespace.is_none() && edge.namespace_kind == "wildcard"
    }));
    assert_eq!(
        resolve_omena_query_sass_module_use_sources_for_candidate(&sources, None),
        vec!["./legacy".to_string(), "./reset".to_string()]
    );
    assert_eq!(
        resolve_omena_query_sass_module_use_sources_for_candidate(&sources, Some("tokens"),),
        vec!["./tokens".to_string()]
    );
    assert_eq!(
        resolve_omena_query_sass_forward_sources(&sources),
        vec!["./theme".to_string()]
    );
}

/// Non-tautological mechanism-depth test on the REAL default workspace product
/// path (`summarize_omena_query_source_diagnostics_for_workspace_file`, the
/// function the napi/wasm/CLI consumers forward to).
///
/// The fixture has two dynamic className template projections that interpolate
/// the same `variant` binding: `btn-${variant}` (whose `btn-` prefix matches the
/// indexed `btn-primary` / `btn-secondary` selectors) and `xyz-${variant}`
/// (whose `xyz-` prefix matches no indexed selector). Both call sites are
/// harvested from the syntax index inside the default path and flowed through the
/// real k-limited (k-CFA) M-tier gate.
///
/// At the context-insensitive baseline `k = 0` the two call sites share the
/// `variant` callee and collapse into one `<root>` context: their `btn-` and
/// `xyz-` prefixes join to the longest-common-prefix `""`, i.e. `Top`, which
/// projects across the whole selector universe and never raises
/// `noUnknownDynamicClass`. At the context-sensitive default `k` the call sites
/// stay separate, so the `xyz-` projection narrows to the empty selector set and
/// the harvested default path raises `noUnknownDynamicClass` at the `xyz-`
/// reference range.
///
/// The load-bearing assertion is the differential between the default
/// (context-sensitive) path and the `k = 0` baseline. If `analyze_k_limited_call_site_flows`
/// were replaced by a constant/identity (always k = 0 collapse, or never
/// joining), both runs would emit the same diagnostic set and the differential
/// would fail — so this is not a tautology.
#[test]
fn workspace_source_diagnostics_harvest_context_sensitive_m_tier_flow() {
    let source_path = "/workspace/src/Button.tsx";
    let source = r#"import styles from "./Button.module.scss";
export function Button({ variant }) {
  return (
    <div>
      <span className={`btn-${variant}`} />
      <span className={`xyz-${variant}`} />
    </div>
  );
}"#;
    let style_sources = [OmenaQueryStyleSourceInputV0 {
        style_path: "/workspace/src/Button.module.scss".to_string(),
        style_source: ".btn-primary {}\n.btn-secondary {}\n".to_string(),
    }];

    let context_sensitive = summarize_omena_query_source_diagnostics_for_workspace_file(
        source_path,
        source,
        &style_sources,
        &[],
    );
    let context_insensitive =
        summarize_omena_query_source_diagnostics_for_workspace_file_with_context_depth(
            source_path,
            source,
            &style_sources,
            &[],
            0,
        );

    assert_eq!(context_sensitive.file_kind, "source");

    // The harvested M-tier diagnostics carry the k-limited flow provenance, so
    // they are demonstrably the real mechanism, not a hardcoded source warning.
    let context_sensitive_m_tier = context_sensitive
        .diagnostics
        .iter()
        .filter(|diagnostic| {
            diagnostic
                .provenance
                .contains(&"omena-abstract-value.k-limited-call-site-flow")
        })
        .collect::<Vec<_>>();
    assert!(
        !context_sensitive_m_tier.is_empty(),
        "default workspace path must emit harvested k-CFA M-tier diagnostics without an external producer"
    );

    // Context-sensitive default k: the `xyz-` site separates and trips
    // noUnknownDynamicClass; the context-insensitive baseline joins it into Top
    // and never does.
    let unknown_class_present = |summary: &crate::OmenaQuerySourceDiagnosticsForFileV0| {
        summary
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.code == "noUnknownDynamicClass")
    };
    assert!(
        unknown_class_present(&context_sensitive),
        "context-sensitive flow must raise noUnknownDynamicClass for the unmatched xyz- projection"
    );
    assert!(
        !unknown_class_present(&context_insensitive),
        "context-insensitive (k=0) collapse joins the prefixes to Top and must NOT raise noUnknownDynamicClass"
    );

    // The differential: the emitted diagnostic set must change with the
    // context-depth bound, not just metadata.
    let context_sensitive_codes = context_sensitive
        .diagnostics
        .iter()
        .map(|diagnostic| (diagnostic.code, diagnostic.range.start.line))
        .collect::<Vec<_>>();
    let context_insensitive_codes = context_insensitive
        .diagnostics
        .iter()
        .map(|diagnostic| (diagnostic.code, diagnostic.range.start.line))
        .collect::<Vec<_>>();
    assert_ne!(
        context_sensitive_codes, context_insensitive_codes,
        "k-limiting must change which workspace M-tier diagnostics are emitted"
    );
}

/// Over-correction guard for the M8 k-CFA M-tier FP cleanup (WP7-a).
///
/// `no-imprecise-value` must NOT fire on harvested affix templates: an
/// interpolation is inherently imprecise, so a hint per template is
/// information-free noise. This asserts the demotion is real while the
/// load-bearing `no-unknown-dynamic-class` true positive on the unmatched `xyz-`
/// projection is still preserved (so the demotion did not also silence the real
/// finding).
#[test]
fn workspace_source_diagnostics_suppress_imprecise_value_noise_on_harvested_templates() {
    let source_path = "/workspace/src/Button.tsx";
    let source = r#"import styles from "./Button.module.scss";
export function Button({ variant }) {
  return (
    <div>
      <span className={`btn-${variant}`} />
      <span className={`xyz-${variant}`} />
    </div>
  );
}"#;
    let style_sources = [OmenaQueryStyleSourceInputV0 {
        style_path: "/workspace/src/Button.module.scss".to_string(),
        style_source: ".btn-primary {}\n.btn-secondary {}\n".to_string(),
    }];

    let summary = summarize_omena_query_source_diagnostics_for_workspace_file(
        source_path,
        source,
        &style_sources,
        &[],
    );

    // FP #2 gone: no information-free `noImpreciseValue` hint on either template.
    assert!(
        summary
            .diagnostics
            .iter()
            .all(|diagnostic| diagnostic.code != "noImpreciseValue"),
        "harvested affix templates must not emit information-free noImpreciseValue hints, got {:?}",
        summary
            .diagnostics
            .iter()
            .map(|diagnostic| diagnostic.code)
            .collect::<Vec<_>>()
    );

    // True positive preserved: the unmatched `xyz-` projection still flags
    // noUnknownDynamicClass at its own reference range, and the matched `btn-`
    // projection (line 4) stays clean.
    let unknown_class = summary
        .diagnostics
        .iter()
        .filter(|diagnostic| diagnostic.code == "noUnknownDynamicClass")
        .collect::<Vec<_>>();
    assert_eq!(
        unknown_class.len(),
        1,
        "exactly the unmatched xyz- projection must flag noUnknownDynamicClass"
    );
    assert_eq!(
        unknown_class[0].range.start.line, 5,
        "noUnknownDynamicClass must anchor to the unmatched xyz- template, not the matched btn- one"
    );
}

/// Over-correction guard for the SOUND module-scoping half of WP7-a.
///
/// A `cx(`btn-${variant}`)` call is bound (via `classnames/bind`) to a SPECIFIC
/// imported CSS Module, so the harvested type-fact target carries that module's
/// resolved `target_style_uri`. `no-unknown-dynamic-class` must therefore be
/// evaluated against ONLY the bound module's selectors, not the union of every
/// imported module:
///
/// - bound to a module that HAS `btn-*` selectors -> provably non-empty -> clean;
/// - bound to a module that has NO `btn-*` selectors -> provably empty ->
///   `no-unknown-dynamic-class` STILL fires, even though a DIFFERENT imported
///   module happens to define `btn-*` (the union would have masked the bug).
#[test]
fn workspace_source_diagnostics_scope_unknown_dynamic_class_to_bound_module() {
    let style_sources = [
        OmenaQueryStyleSourceInputV0 {
            style_path: "/workspace/src/A.module.scss".to_string(),
            style_source: ".btn-primary {}\n.btn-secondary {}\n".to_string(),
        },
        OmenaQueryStyleSourceInputV0 {
            style_path: "/workspace/src/B.module.scss".to_string(),
            style_source: ".card {}\n.panel {}\n".to_string(),
        },
    ];

    let unknown_class_count = |bind_target: &str| {
        let source = format!(
            r#"import bind from "classnames/bind";
import a from "./A.module.scss";
import b from "./B.module.scss";
const cx = bind.bind({bind_target});
export function App({{ variant }}) {{
  return <div className={{cx(`btn-${{variant}}`)}} />;
}}"#
        );
        summarize_omena_query_source_diagnostics_for_workspace_file(
            "/workspace/src/App.tsx",
            &source,
            &style_sources,
            &[],
        )
        .diagnostics
        .iter()
        .filter(|diagnostic| diagnostic.code == "noUnknownDynamicClass")
        .count()
    };

    // Bound to module A, which HAS btn-* selectors: scoped intersection is
    // non-empty -> NO false positive.
    assert_eq!(
        unknown_class_count("a"),
        0,
        "btn- bound to a module that HAS btn-* selectors must not flag noUnknownDynamicClass"
    );

    // Bound to module B, which has NO btn-* selectors: scoped intersection is
    // provably empty -> the genuine bug STILL fires, even though module A (a
    // different import) defines btn-* (the union universe would have masked it).
    assert_eq!(
        unknown_class_count("b"),
        1,
        "btn- bound to a module with NO btn-* selectors must still flag noUnknownDynamicClass \
         (scoped to the bound module, not cross-matched against the union)"
    );
}