knot 1.16.2

Codebase Graph + Vector RAG Indexer for Java, TypeScript, JavaScript, Kotlin, Rust, Python, Groovy, C/C++, C#, Build Systems, and HTML/CSS codebases
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
use std::collections::HashMap;
use std::sync::atomic::Ordering;
use tracing::debug;
use uuid::Uuid;

use super::calls::find_entity_in_same_file;
use super::context::RunMetrics;
use crate::models::EntityKind;

/// Type-like kinds that may be the target of an inheritance or type-usage
/// reference. C# constructor entities share their class's name
/// (`BaseService` class + `BaseService` constructor), so name-only
/// resolution for `Extends` / `Implements` / `TypeReference` intents must
/// restrict candidates to types or the constructor wins the ambiguity and
/// the edge is dropped as ambiguous.
fn is_type_like(kind: &EntityKind) -> bool {
    matches!(
        kind,
        EntityKind::Class
            | EntityKind::Interface
            | EntityKind::Enum
            | EntityKind::KotlinClass
            | EntityKind::KotlinInterface
            | EntityKind::KotlinObject
            | EntityKind::KotlinCompanionObject
            | EntityKind::KotlinEnum
            | EntityKind::GroovyClass
            | EntityKind::GroovyInterface
            | EntityKind::GroovyTrait
            | EntityKind::GroovyEnum
            | EntityKind::CSharpClass
            | EntityKind::CSharpInterface
            | EntityKind::CSharpStruct
            | EntityKind::CSharpRecord
            | EntityKind::CSharpEnum
            | EntityKind::CSharpDelegate
            | EntityKind::CSharpNamespace
            | EntityKind::CppClass
            | EntityKind::CppNamespace
            | EntityKind::CStruct
            | EntityKind::PythonClass
            | EntityKind::RustStruct
            | EntityKind::RustEnum
            | EntityKind::RustUnion
            | EntityKind::RustTrait
    )
}

#[expect(
    clippy::too_many_arguments,
    reason = "function is verbose but correct — extraction deferred"
)]
pub(crate) fn resolve_non_call_reference(
    name: &str,
    source_file: &str,
    enclosing_class: Option<&str>,
    fqn_to_uuid: &HashMap<String, Uuid>,
    name_to_uuids: &HashMap<String, Vec<Uuid>>,
    uuid_to_file: &HashMap<Uuid, String>,
    uuid_to_fqn: Option<&HashMap<Uuid, String>>,
    metrics: &RunMetrics,
) -> Option<Uuid> {
    resolve_non_call_reference_typed(
        name,
        source_file,
        enclosing_class,
        fqn_to_uuid,
        name_to_uuids,
        uuid_to_file,
        None,
        uuid_to_fqn,
        metrics,
    )
}

/// Web-reference resolution: DOM element ids (`REFERENCES_DOM`) and CSS
/// class usages (`USES_CSS_CLASS`) must resolve against their exact kind —
/// [`EntityKind::HtmlId`] for a `getElementById('x')` and
/// [`EntityKind::CssClass`] for a class usage — instead of the plain ladder.
///
/// Rationale: a file frequently declares the same bare name as both an html
/// id and a CSS class; the plain ladder then sees two candidates, no context
/// disambiguates them, and the edge dies as "ambiguous". The intent already
/// *knows* which kind it targets, so the candidate set is restricted to that
/// kind up front, and an empty filtered set means NO edge rather than a
/// guess (a DOM lookup never points at a CSS class).
///
/// (7 args like its [`resolve_non_call_reference_typed`] sibling — clippy
/// expectation below, shape dictated by the shared lookup maps.)
#[expect(
    clippy::too_many_arguments,
    reason = "mirror of resolve_non_call_reference_typed's lookup-map signature"
)]
pub(crate) fn resolve_web_reference(
    name: &str,
    preferred: EntityKind,
    source_file: &str,
    name_to_uuids: &HashMap<String, Vec<Uuid>>,
    uuid_to_file: &HashMap<Uuid, String>,
    uuid_to_kind: Option<&HashMap<Uuid, EntityKind>>,
    metrics: &RunMetrics,
) -> Option<Uuid> {
    let Some(all_candidates) = name_to_uuids.get(name) else {
        metrics
            .references_unresolved
            .fetch_add(1, Ordering::Relaxed);
        return None;
    };

    let candidate_uuids: Vec<Uuid> = match uuid_to_kind {
        Some(kinds) => all_candidates
            .iter()
            .filter(|u| kinds.get(*u).is_some_and(|k| *k == preferred))
            .copied()
            .collect(),
        // Without kind knowledge the intent cannot be safely resolved:
        // counting it as unresolved (not ambiguous) keeps the contract that
        // a wrong-kind edge is never created.
        None => Vec::new(),
    };

    match candidate_uuids.as_slice() {
        [] => {
            metrics
                .references_unresolved
                .fetch_add(1, Ordering::Relaxed);
            None
        }
        [only] => {
            metrics.references_resolved.fetch_add(1, Ordering::Relaxed);
            Some(*only)
        }
        _ => {
            if let Some(same_file_uuid) =
                find_entity_in_same_file(&candidate_uuids, source_file, uuid_to_file)
            {
                metrics.references_resolved.fetch_add(1, Ordering::Relaxed);
                return Some(same_file_uuid);
            }
            debug!(
                name = name,
                kind = preferred.to_string(),
                "Ambiguous web reference skipped"
            );
            metrics
                .references_ambiguous_skipped
                .fetch_add(1, Ordering::Relaxed);
            None
        }
    }
}

/// Type-aware variant of [`resolve_non_call_reference`]: when
/// `type_targets_only` is set, candidates are first filtered to type-like
/// kinds (see [`is_type_like`]) before the disambiguation ladder runs.
#[expect(
    clippy::too_many_arguments,
    reason = "function is verbose but correct — extraction deferred"
)]
pub(crate) fn resolve_non_call_reference_typed(
    name: &str,
    source_file: &str,
    enclosing_class: Option<&str>,
    fqn_to_uuid: &HashMap<String, Uuid>,
    name_to_uuids: &HashMap<String, Vec<Uuid>>,
    uuid_to_file: &HashMap<Uuid, String>,
    uuid_to_kind: Option<&HashMap<Uuid, EntityKind>>,
    uuid_to_fqn: Option<&HashMap<Uuid, String>>,
    metrics: &RunMetrics,
) -> Option<Uuid> {
    if name.contains('.') || name.contains("::") {
        // Exact FQN wins outright.
        if let Some(&uuid) = fqn_to_uuid.get(name) {
            metrics.references_resolved.fetch_add(1, Ordering::Relaxed);
            return Some(uuid);
        }
        // Otherwise fall back to candidates whose FQN ends with the qualified
        // name — this catches partially qualified refs (`GestureOwner.Off`).
        let candidates =
            qualified_suffix_candidates(name, name_to_uuids, uuid_to_fqn).unwrap_or_default();
        return pick_unambiguous_candidate(&candidates, source_file, uuid_to_file, metrics);
    }

    let Some(all_candidates) = name_to_uuids.get(name) else {
        metrics
            .references_unresolved
            .fetch_add(1, Ordering::Relaxed);
        return None;
    };

    let candidate_uuids: Vec<Uuid> = match uuid_to_kind {
        // Type targets (Extends/Implements/TypeReference): a constructor or
        // method sharing the name is never the right target.
        Some(kinds) => all_candidates
            .iter()
            .filter(|u| kinds.get(*u).is_some_and(is_type_like))
            .copied()
            .collect(),
        None => all_candidates.clone(),
    };

    if candidate_uuids.is_empty() {
        metrics
            .references_unresolved
            .fetch_add(1, Ordering::Relaxed);
        return None;
    }

    if let Some(same_file_uuid) =
        find_entity_in_same_file(&candidate_uuids, source_file, uuid_to_file)
    {
        metrics.references_resolved.fetch_add(1, Ordering::Relaxed);
        return Some(same_file_uuid);
    }

    if let Some(enclosing) = enclosing_class {
        let dot_fqn = format!("{}.{}", enclosing, name);
        if let Some(&uuid) = fqn_to_uuid.get(&dot_fqn) {
            metrics.references_resolved.fetch_add(1, Ordering::Relaxed);
            return Some(uuid);
        }
        let colon_fqn = format!("{}::{}", enclosing, name);
        if let Some(&uuid) = fqn_to_uuid.get(&colon_fqn) {
            metrics.references_resolved.fetch_add(1, Ordering::Relaxed);
            return Some(uuid);
        }
    }

    if candidate_uuids.len() == 1 {
        metrics.references_resolved.fetch_add(1, Ordering::Relaxed);
        return candidate_uuids.first().copied();
    }

    debug!(
        name = name,
        candidates = candidate_uuids.len(),
        source_file = source_file,
        "Ambiguous reference skipped: multiple candidates with no disambiguating context"
    );
    metrics
        .references_ambiguous_skipped
        .fetch_add(1, Ordering::Relaxed);
    None
}

/// Pick a single target from `candidates`, preferring one declared in
/// `source_file`, and record the outcome in `metrics`.
fn pick_unambiguous_candidate(
    candidates: &[Uuid],
    source_file: &str,
    uuid_to_file: &HashMap<Uuid, String>,
    metrics: &RunMetrics,
) -> Option<Uuid> {
    if candidates.is_empty() {
        metrics
            .references_unresolved
            .fetch_add(1, Ordering::Relaxed);
        return None;
    }

    if let Some(same_file_uuid) = find_entity_in_same_file(candidates, source_file, uuid_to_file) {
        metrics.references_resolved.fetch_add(1, Ordering::Relaxed);
        return Some(same_file_uuid);
    }

    if let [only] = candidates {
        metrics.references_resolved.fetch_add(1, Ordering::Relaxed);
        return Some(*only);
    }

    metrics
        .references_ambiguous_skipped
        .fetch_add(1, Ordering::Relaxed);
    None
}

/// Candidates sharing the last segment of `name` whose FQN ends with `name`.
fn qualified_suffix_candidates(
    name: &str,
    name_to_uuids: &HashMap<String, Vec<Uuid>>,
    uuid_to_fqn: Option<&HashMap<Uuid, String>>,
) -> Option<Vec<Uuid>> {
    let uuid_to_fqn_map = uuid_to_fqn?;
    let last_segment = if name.contains("::") {
        name.rsplit("::").next()?
    } else {
        name.rsplit('.').next()?
    };
    let candidates = name_to_uuids.get(last_segment)?;

    Some(
        candidates
            .iter()
            .filter(|u| {
                uuid_to_fqn_map.get(*u).is_some_and(|fqn| {
                    fqn == name
                        || fqn.ends_with(&format!(".{name}"))
                        || fqn.ends_with(&format!("::{name}"))
                })
            })
            .copied()
            .collect(),
    )
}

#[cfg(test)]
mod tests {
    use super::super::test_utils::*;
    use crate::models::{EntityKind, ReferenceIntent, RelationshipType};
    use crate::pipeline::ingest::resolve::resolve_reference_intents;

    /// The reported web-reference ambiguity: the same bare name exists as an
    /// html id and as a CSS class; a `DomElementReference` must resolve to
    /// the html_id and a `CssClassUsage` to the css_class — neither may
    /// guess, and neither must die as ambiguous.
    #[test]
    fn test_web_reference_resolves_by_exact_kind() {
        let html_id = mock_resolution_entity_with_kind(
            "app-container",
            "#app-container",
            None,
            "app.html",
            EntityKind::HtmlId,
        );
        let css_class = mock_resolution_entity_with_kind(
            "app-container",
            ".app-container",
            None,
            "app.css",
            EntityKind::CssClass,
        );
        let html_id_uuid = html_id.uuid;
        let css_uuid = css_class.uuid;

        let mut js_user = mock_resolution_entity_with_kind(
            "toggleLook",
            "app::toggleLook",
            None,
            "app.js",
            EntityKind::RustFunction,
        );
        js_user.reference_intents = vec![
            ReferenceIntent::DomElementReference {
                element_id: "app-container".to_string(),
                line: 5,
            },
            ReferenceIntent::CssClassUsage {
                class_name: "app-container".to_string(),
                line: 6,
            },
        ];

        let mut entities = vec![html_id, css_class, js_user];
        resolve_reference_intents(&mut entities);

        let user = entities.last().expect("entity");
        assert!(
            user.relationships
                .contains(&(html_id_uuid, RelationshipType::ReferencesDOM)),
            "DOM intent must resolve to the html_id, got {:?}",
            user.relationships
        );
        assert!(
            user.relationships
                .contains(&(css_uuid, RelationshipType::UsesCSSClass)),
            "CSS intent must resolve to the css_class, got {:?}",
            user.relationships
        );
        assert_eq!(user.relationships.len(), 2);
    }

    #[test]
    fn test_resolve_inheritance() {
        let mut child = mock_resolution_entity("Child", "com.Child", None);
        // Inheritance targets must be type-like entities.
        let parent = mock_resolution_entity_with_kind(
            "Parent",
            "com.Parent",
            None,
            "test/file.java",
            EntityKind::Class,
        );

        child.reference_intents.push(ReferenceIntent::Extends {
            parent: "Parent".to_string(),
            line: 1,
        });

        let mut entities = vec![child, parent];
        resolve_reference_intents(&mut entities);

        assert_eq!(entities[0].relationships.len(), 1);
        assert_eq!(
            entities[0].relationships[0],
            (entities[1].uuid, RelationshipType::Extends)
        );
    }

    #[test]
    fn test_resolve_type_reference() {
        let mut entity = mock_resolution_entity("service", "service", None);
        // Type targets must be type-like entities.
        let type_entity = mock_resolution_entity_with_kind(
            "MyType",
            "com.MyType",
            None,
            "test/file.java",
            EntityKind::Class,
        );

        entity
            .reference_intents
            .push(ReferenceIntent::TypeReference {
                type_name: "MyType".to_string(),
                line: 1,
            });

        let mut entities = vec![entity, type_entity];
        resolve_reference_intents(&mut entities);

        assert_eq!(entities[0].relationships.len(), 1);
        assert_eq!(
            entities[0].relationships[0],
            (entities[1].uuid, RelationshipType::References)
        );
    }

    #[test]
    fn test_resolve_self_method_inherited_from_parent_class() {
        let animal_speak = mock_resolution_entity_with_kind(
            "Animal",
            "Animal",
            None,
            "animals.py",
            EntityKind::Class,
        );
        let animal_speak_method = mock_resolution_entity_with_kind(
            "speak",
            "Animal.speak",
            Some("Animal"),
            "animals.py",
            EntityKind::Method,
        );

        let mut dog_class =
            mock_resolution_entity_with_kind("Dog", "Dog", None, "animals.py", EntityKind::Class);
        dog_class.reference_intents = vec![ReferenceIntent::Extends {
            parent: "Animal".to_string(),
            line: 10,
        }];

        let mut dog_compute = mock_resolution_entity_with_kind(
            "compute",
            "Dog.compute",
            Some("Dog"),
            "animals.py",
            EntityKind::Method,
        );
        dog_compute.reference_intents = vec![ReferenceIntent::Call {
            method: "speak".to_string(),
            receiver: Some("self".to_string()),
            line: 15,
            arg_count: None,
        }];

        let mut entities = vec![animal_speak, animal_speak_method, dog_class, dog_compute];
        resolve_reference_intents(&mut entities);

        let dog = entities.iter().find(|e| e.name == "compute").unwrap();
        let speak_method = entities.iter().find(|e| e.fqn == "Animal.speak").unwrap();
        assert!(
            dog.relationships
                .contains(&(speak_method.uuid, RelationshipType::Calls))
        );
    }

    #[test]
    fn test_type_reference_prefers_same_file() {
        let config_in_file_a = mock_resolution_entity_with_kind(
            "Config",
            "Config",
            None,
            "src/config.rs",
            EntityKind::RustStruct,
        );
        let config_in_file_b = mock_resolution_entity_with_kind(
            "Config",
            "Config",
            None,
            "src/other/types.rs",
            EntityKind::RustStruct,
        );

        let mut caller = mock_resolution_entity_with_kind(
            "load",
            "Config::load",
            Some("Config"),
            "src/config.rs",
            EntityKind::RustMethod,
        );
        caller.reference_intents = vec![ReferenceIntent::TypeReference {
            type_name: "Config".to_string(),
            line: 10,
        }];

        let config_a_uuid = config_in_file_a.uuid;
        let config_b_uuid = config_in_file_b.uuid;

        let mut entities = vec![config_in_file_a, config_in_file_b, caller];
        resolve_reference_intents(&mut entities);

        let caller_entity = entities.last().unwrap();
        assert!(
            caller_entity
                .relationships
                .contains(&(config_a_uuid, RelationshipType::References))
        );
        assert!(
            !caller_entity
                .relationships
                .contains(&(config_b_uuid, RelationshipType::References))
        );
    }

    #[test]
    fn test_type_reference_skips_when_ambiguous_no_hints() {
        let config_file_a = mock_resolution_entity_with_kind(
            "Config",
            "Config",
            None,
            "src/a.rs",
            EntityKind::RustStruct,
        );
        let config_file_b = mock_resolution_entity_with_kind(
            "Config",
            "Config",
            None,
            "src/b.rs",
            EntityKind::RustStruct,
        );

        let mut caller = mock_resolution_entity_with_kind(
            "do_work",
            "do_work",
            None,
            "src/c.rs",
            EntityKind::RustFunction,
        );
        caller.reference_intents = vec![ReferenceIntent::TypeReference {
            type_name: "Config".to_string(),
            line: 5,
        }];

        let mut entities = vec![config_file_a, config_file_b, caller];
        resolve_reference_intents(&mut entities);

        let caller_entity = entities.last().unwrap();
        assert_eq!(caller_entity.relationships.len(), 0);
    }

    #[test]
    fn test_type_reference_enclosing_class_disambiguates() {
        let config_struct = mock_resolution_entity_with_kind(
            "Config",
            "Config",
            None,
            "src/config.rs",
            EntityKind::RustStruct,
        );
        let other_config = mock_resolution_entity_with_kind(
            "Config",
            "Config",
            None,
            "src/other.rs",
            EntityKind::RustStruct,
        );

        let mut caller = mock_resolution_entity_with_kind(
            "load",
            "Config::load",
            Some("Config"),
            "src/other.rs",
            EntityKind::RustMethod,
        );
        caller.reference_intents = vec![ReferenceIntent::TypeReference {
            type_name: "Config".to_string(),
            line: 10,
        }];

        let config_uuid = config_struct.uuid;
        let other_config_uuid = other_config.uuid;

        let mut entities = vec![config_struct, other_config, caller];
        resolve_reference_intents(&mut entities);

        let caller_entity = entities.last().unwrap();
        assert!(
            caller_entity
                .relationships
                .contains(&(other_config_uuid, RelationshipType::References))
        );
        assert!(
            !caller_entity
                .relationships
                .contains(&(config_uuid, RelationshipType::References))
        );
    }

    #[test]
    fn test_extends_uses_same_ladder() {
        let parent_in_same_file = mock_resolution_entity_with_kind(
            "MyTrait",
            "MyTrait",
            None,
            "src/lib.rs",
            EntityKind::RustTrait,
        );
        let parent_other_file = mock_resolution_entity_with_kind(
            "MyTrait",
            "MyTrait",
            None,
            "src/other.rs",
            EntityKind::RustTrait,
        );

        let mut child = mock_resolution_entity_with_kind(
            "Child",
            "Child",
            None,
            "src/lib.rs",
            EntityKind::RustStruct,
        );
        child.reference_intents = vec![ReferenceIntent::Implements {
            interface: "MyTrait".to_string(),
            line: 5,
        }];

        let same_uuid = parent_in_same_file.uuid;
        let other_uuid = parent_other_file.uuid;

        let mut entities = vec![parent_in_same_file, parent_other_file, child];
        resolve_reference_intents(&mut entities);

        let child_entity = entities.last().unwrap();
        assert!(
            child_entity
                .relationships
                .contains(&(same_uuid, RelationshipType::Implements))
        );
        assert!(
            !child_entity
                .relationships
                .contains(&(other_uuid, RelationshipType::Implements))
        );
    }

    /// End-to-end check that the Groovy parser emits an `Extends` reference
    /// intent on `Ext1` and that `resolve_reference_intents` converts it into
    /// an `Extends` edge pointing at the parent `PluginExtensionPoint` parsed
    /// in the same file.
    #[test]
    fn test_groovy_extends_resolves_to_extends_relationship() {
        use crate::models::ResolutionEntity;
        use crate::pipeline::parser::languages::groovy::extract_entities_groovy;

        const FILE: &str = "Plugin.groovy";

        let parent_source = "abstract class PluginExtensionPoint { }";
        let child_source = "class Ext1 extends PluginExtensionPoint { }";

        let parent_entities = extract_entities_groovy(parent_source, FILE, "test-repo");
        let child_entities = extract_entities_groovy(child_source, FILE, "test-repo");

        let child_parsed = child_entities
            .iter()
            .find(|e| e.name == "Ext1")
            .expect("Ext1 should be parsed");

        // Sanity check: the parser must emit an `Extends` reference on the
        // child entity before resolution runs.
        let has_extends = child_parsed.reference_intents.iter().any(|r| {
            matches!(r, ReferenceIntent::Extends { parent, .. } if parent == "PluginExtensionPoint")
        });
        assert!(
            has_extends,
            "Parser should emit Extends(PluginExtensionPoint) on Ext1; got {:?}",
            child_parsed.reference_intents
        );

        // Convert ParsedEntity -> ResolutionEntity (clones reference_intents).
        let mut resolution_entities: Vec<ResolutionEntity> = parent_entities
            .iter()
            .chain(child_entities.iter())
            .map(ResolutionEntity::from)
            .collect();

        resolve_reference_intents(&mut resolution_entities);

        let parent_uuid = resolution_entities
            .iter()
            .find(|e| e.name == "PluginExtensionPoint")
            .expect("PluginExtensionPoint not present after conversion")
            .uuid;
        let ext1 = resolution_entities
            .iter()
            .find(|e| e.name == "Ext1")
            .expect("Ext1 not present after conversion");

        assert!(
            ext1.relationships
                .contains(&(parent_uuid, RelationshipType::Extends)),
            "Ext1 should have an Extends edge to PluginExtensionPoint; got {:?}",
            ext1.relationships
        );
    }

    #[test]
    fn test_qualified_type_reference_resolves_by_fqn_suffix() {
        let target = mock_resolution_entity_with_kind(
            "Off",
            "MyApp.Gestures.GestureOwner.Off",
            None,
            "src/GestureOwner.cs",
            EntityKind::CSharpRecord,
        );
        let mut caller = mock_resolution_entity_with_kind(
            "GesturesEnabled",
            "MyApp.Gestures.GestureConfig.GesturesEnabled",
            None,
            "src/GestureConfig.cs",
            EntityKind::CSharpMethod,
        );
        caller.reference_intents = vec![ReferenceIntent::TypeReference {
            type_name: "GestureOwner.Off".to_string(),
            line: 10,
        }];
        let target_uuid = target.uuid;
        let mut entities = vec![target, caller];
        resolve_reference_intents(&mut entities);
        let caller_entity = entities
            .iter()
            .find(|e| e.name == "GesturesEnabled")
            .unwrap();
        assert!(
            caller_entity
                .relationships
                .contains(&(target_uuid, RelationshipType::References)),
            "should resolve by FQN suffix, got {:?}",
            caller_entity.relationships
        );
    }

    #[test]
    fn test_qualified_reference_resolves_non_type_member() {
        let target = mock_resolution_entity_with_kind(
            "OffValue",
            "MyApp.Gestures.GestureOwner.OffValue",
            None,
            "src/GestureOwner.cs",
            EntityKind::CSharpField,
        );
        let mut caller = mock_resolution_entity_with_kind(
            "Disable",
            "MyApp.Gestures.GestureConfig.Disable",
            None,
            "src/GestureConfig.cs",
            EntityKind::CSharpMethod,
        );
        caller.reference_intents = vec![ReferenceIntent::TypeReference {
            type_name: "GestureOwner.OffValue".to_string(),
            line: 10,
        }];
        let target_uuid = target.uuid;
        let mut entities = vec![target, caller];
        resolve_reference_intents(&mut entities);
        let caller_entity = entities.iter().find(|e| e.name == "Disable").unwrap();
        assert!(
            caller_entity
                .relationships
                .contains(&(target_uuid, RelationshipType::References)),
            "should resolve field target by dotted path, got {:?}",
            caller_entity.relationships
        );
    }

    #[test]
    fn test_qualified_reference_has_no_bare_last_segment_fallback() {
        let target = mock_resolution_entity_with_kind(
            "FromResult",
            "SomeNamespace.FromResult",
            None,
            "src/other.cs",
            EntityKind::CSharpMethod,
        );
        let mut caller = mock_resolution_entity_with_kind(
            "Disable",
            "MyApp.Gestures.GestureConfig.Disable",
            None,
            "src/GestureConfig.cs",
            EntityKind::CSharpMethod,
        );
        caller.reference_intents = vec![ReferenceIntent::TypeReference {
            type_name: "Task.FromResult".to_string(),
            line: 10,
        }];
        let mut entities = vec![target, caller];
        resolve_reference_intents(&mut entities);
        let caller_entity = entities.iter().find(|e| e.name == "Disable").unwrap();
        assert!(
            caller_entity.relationships.is_empty(),
            "should not resolve to bare last segment fallback, got {:?}",
            caller_entity.relationships
        );
    }

    #[test]
    fn test_qualified_reference_ambiguous_suffix_is_skipped() {
        let target1 = mock_resolution_entity_with_kind(
            "Off",
            "Namespace1.GestureOwner.Off",
            None,
            "src/File1.cs",
            EntityKind::CSharpRecord,
        );
        let target2 = mock_resolution_entity_with_kind(
            "Off",
            "Namespace2.GestureOwner.Off",
            None,
            "src/File2.cs",
            EntityKind::CSharpRecord,
        );
        let mut caller = mock_resolution_entity_with_kind(
            "GesturesEnabled",
            "MyApp.Gestures.GestureConfig.GesturesEnabled",
            None,
            "src/GestureConfig.cs",
            EntityKind::CSharpMethod,
        );
        caller.reference_intents = vec![ReferenceIntent::TypeReference {
            type_name: "GestureOwner.Off".to_string(),
            line: 10,
        }];
        let mut entities = vec![target1, target2, caller];
        resolve_reference_intents(&mut entities);
        let caller_entity = entities
            .iter()
            .find(|e| e.name == "GesturesEnabled")
            .unwrap();
        assert!(
            caller_entity.relationships.is_empty(),
            "should skip ambiguous suffix, got {:?}",
            caller_entity.relationships
        );
    }

    #[test]
    fn test_qualified_reference_prefers_same_file() {
        let target_foreign = mock_resolution_entity_with_kind(
            "Off",
            "Namespace1.GestureOwner.Off",
            None,
            "src/File1.cs",
            EntityKind::CSharpRecord,
        );
        let target_same = mock_resolution_entity_with_kind(
            "Off",
            "Namespace2.GestureOwner.Off",
            None,
            "src/GestureConfig.cs",
            EntityKind::CSharpRecord,
        );
        let mut caller = mock_resolution_entity_with_kind(
            "GesturesEnabled",
            "MyApp.Gestures.GestureConfig.GesturesEnabled",
            None,
            "src/GestureConfig.cs",
            EntityKind::CSharpMethod,
        );
        caller.reference_intents = vec![ReferenceIntent::TypeReference {
            type_name: "GestureOwner.Off".to_string(),
            line: 10,
        }];
        let same_uuid = target_same.uuid;
        let foreign_uuid = target_foreign.uuid;
        let mut entities = vec![target_foreign, target_same, caller];
        resolve_reference_intents(&mut entities);
        let caller_entity = entities
            .iter()
            .find(|e| e.name == "GesturesEnabled")
            .unwrap();
        assert!(
            caller_entity
                .relationships
                .contains(&(same_uuid, RelationshipType::References)),
            "should prefer same file, got {:?}",
            caller_entity.relationships
        );
        assert!(
            !caller_entity
                .relationships
                .contains(&(foreign_uuid, RelationshipType::References))
        );
    }
}