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
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
//! Unit tests for the C# parser (plan §7–§10, BDD: tests define the contract).
//!
//! Coverage:
//! - Entity extraction per kind (§7) — the grammar-gap cases (fields, const,
//!   records, indexer, operator, local functions) included.
//! - FQN construction across namespace forms (§8.1).
//! - References: inheritance heuristic, attributes, type refs, call intents
//!   with receiver substitution (§9).
//! - OVERRIDES end-to-end via `resolve_reference_intents` (§10.1).
//! - Orphan handling for top-level statements (§13).

use super::refs::{
    extract_attribute_references, extract_class_inheritance_csharp,
    extract_reference_intents_csharp,
};
use super::{build_csharp_fqn_prefix, extract_file_scoped_namespace};
use crate::models::{EntityKind, ReferenceIntent, RelationshipType, ResolutionEntity};
use crate::pipeline::parser::DEFAULT_CSHARP_QUERY;
use crate::pipeline::parser::context::{ClassContext, extract_class_contexts};
use crate::pipeline::parser::extractor::extract_entities;
use crate::pipeline::parser::test_utils::{
    collect_extends, collect_implements, find_first_node, parse_csharp_snippet,
};
use tree_sitter::Node;

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Run the full query-driven extraction on a snippet, as `parse_single_file`
/// would for a `.cs` file.
fn extract(code: &str) -> Vec<crate::models::ParsedEntity> {
    extract_entities(
        code,
        tree_sitter_c_sharp::LANGUAGE.into(),
        DEFAULT_CSHARP_QUERY,
        "csharp",
        "Test.cs",
        "test-repo",
    )
    .expect("C# extraction failed")
}

fn find_entity<'a>(
    entities: &'a [crate::models::ParsedEntity],
    name: &str,
    kind: &EntityKind,
) -> &'a crate::models::ParsedEntity {
    entities
        .iter()
        .find(|e| e.name == name && e.kind == *kind)
        .unwrap_or_else(|| panic!("entity {name} of kind {kind} not found"))
}

fn entities_of_kind<'a>(
    entities: &'a [crate::models::ParsedEntity],
    kind: &EntityKind,
) -> Vec<&'a str> {
    entities
        .iter()
        .filter(|e| e.kind == *kind)
        .map(|e| e.name.as_str())
        .collect()
}

fn find_node<'a>(root: Node<'a>, kind: &str, name: &str, source: &[u8]) -> Node<'a> {
    let mut stack = vec![root];
    while let Some(n) = stack.pop() {
        if n.kind() == kind
            && let Some(name_node) = n.child_by_field_name("name")
            && name_node.utf8_text(source).unwrap_or("") == name
        {
            return n;
        }
        let mut child = n.child(0);
        while let Some(c) = child {
            stack.push(c);
            child = c.next_sibling();
        }
    }
    panic!("node {kind} named {name} not found");
}

// ---------------------------------------------------------------------------
// Phase 1 — discovery / snippet parsing
// ---------------------------------------------------------------------------

#[test]
fn test_parse_csharp_snippet_parses_class() {
    let tree = parse_csharp_snippet("class Foo {}").expect("parse failed");
    assert!(!tree.root_node().has_error());
}

// ---------------------------------------------------------------------------
// Phase 2 — entity extraction
// ---------------------------------------------------------------------------

#[test]
fn test_extract_class_interface_struct_enum() {
    let code = r#"
namespace App;
public class Foo {}
public interface IBar {}
public struct Baz {}
public enum Qux { A, B }
"#;
    let entities = extract(code);
    assert_eq!(
        entities_of_kind(&entities, &EntityKind::CSharpClass),
        ["Foo"]
    );
    assert_eq!(
        entities_of_kind(&entities, &EntityKind::CSharpInterface),
        ["IBar"]
    );
    assert_eq!(
        entities_of_kind(&entities, &EntityKind::CSharpStruct),
        ["Baz"]
    );
    assert_eq!(
        entities_of_kind(&entities, &EntityKind::CSharpEnum),
        ["Qux"]
    );
}

#[test]
fn test_extract_record_class_and_record_struct_are_records() {
    // Grammar gap (§2.3, Gap 3): both flavors share `record_declaration`
    // and surface as CSharpRecord.
    let code = r#"
namespace App;
public record Point(int X, int Y);
public record struct Coord(double Lat, double Lon);
"#;
    let entities = extract(code);
    let records = entities_of_kind(&entities, &EntityKind::CSharpRecord);
    assert_eq!(records.len(), 2, "both record flavours are records");
    assert!(records.contains(&"Point"));
    assert!(records.contains(&"Coord"));
    assert!(
        !entities_of_kind(&entities, &EntityKind::CSharpStruct).contains(&"Coord"),
        "record struct must not double-extract as struct"
    );
}

#[test]
fn test_extract_method_property_constructor() {
    let code = r#"
namespace App;
public class Foo
{
    public int Bar { get; set; }
    public Foo() {}
    public void DoWork() {}
}
"#;
    let entities = extract(code);
    assert_eq!(
        entities_of_kind(&entities, &EntityKind::CSharpProperty),
        ["Bar"]
    );
    assert_eq!(
        entities_of_kind(&entities, &EntityKind::CSharpConstructor),
        ["Foo"]
    );
    assert_eq!(
        entities_of_kind(&entities, &EntityKind::CSharpMethod),
        ["DoWork"]
    );
}

#[test]
fn test_extract_field_and_const_detection() {
    // Grammar gap (§2.3, Gap 2): field names live in variable_declarator;
    // `const` promotes the kind.
    let code = r#"
namespace App;
public class Foo
{
    public const int Max = 3;
    private readonly string _name;
}
"#;
    let entities = extract(code);
    assert_eq!(
        entities_of_kind(&entities, &EntityKind::CSharpConstant),
        ["Max"],
        "const field must be a CSharpConstant"
    );
    assert_eq!(
        entities_of_kind(&entities, &EntityKind::CSharpField),
        ["_name"],
        "readonly field must be a CSharpField"
    );
}

#[test]
fn test_extract_delegate_event_indexer_operator() {
    let code = r#"
namespace App;
public class Foo
{
    public delegate void Handler(string msg);
    public event Handler? OnEvent;
    public string this[int i] { get => ""; set { } }
    public static Foo operator +(Foo a, Foo b) => a;
}
"#;
    let entities = extract(code);
    assert_eq!(
        entities_of_kind(&entities, &EntityKind::CSharpDelegate),
        ["Handler"]
    );
    assert_eq!(
        entities_of_kind(&entities, &EntityKind::CSharpEvent),
        ["OnEvent"],
        "event-field form must extract the declarator name"
    );
    assert_eq!(
        entities_of_kind(&entities, &EntityKind::CSharpIndexer),
        ["this[]"],
        "indexer name is synthesised (no grammar name field)"
    );
    assert_eq!(
        entities_of_kind(&entities, &EntityKind::CSharpOperator),
        ["operator +"],
        "operator name is synthesised from the operator token"
    );
}

#[test]
fn test_extract_local_function() {
    let code = r#"
namespace App;
public static class Extensions
{
    public static string Slugify(this string value)
    {
        string Normalize(string raw) => raw.Trim();
        return Normalize(value);
    }
}
"#;
    let entities = extract(code);
    assert_eq!(
        entities_of_kind(&entities, &EntityKind::CSharpMethod),
        ["Slugify"]
    );
    assert_eq!(
        entities_of_kind(&entities, &EntityKind::CSharpLocalFunction),
        ["Normalize"]
    );
}

#[test]
fn test_extract_block_and_file_scoped_namespaces() {
    let code = r#"
namespace App.Deep
{
    public class Foo {}
}
namespace App.Top;
public class Bar {}
"#;
    let entities = extract(code);
    let namespaces = entities_of_kind(&entities, &EntityKind::CSharpNamespace);
    assert_eq!(namespaces.len(), 2);
    assert!(namespaces.contains(&"App.Deep"));
    assert!(namespaces.contains(&"App.Top"));
}

#[test]
fn test_extract_class_contexts_includes_struct_record_enum() {
    // context.rs wiring: struct/record/enum declarations establish class
    // contexts so members inside them get qualified FQNs.
    let code = r#"
public struct S { public int X { get; set; } }
public record R { public int Y { get; set; } }
public enum E { A }
"#;
    let tree = parse_csharp_snippet(code).expect("parse failed");
    let mut contexts: Vec<ClassContext> = Vec::new();
    extract_class_contexts(tree.root_node(), code.as_bytes(), &mut contexts);
    assert!(
        contexts.iter().any(|c| c.name == "S"),
        "struct must be a class context"
    );
    assert!(
        contexts.iter().any(|c| c.name == "R"),
        "record must be a class context"
    );
    assert!(
        contexts.iter().any(|c| c.name == "E"),
        "enum must be a class context"
    );
}

// ---------------------------------------------------------------------------
// Phase 3 — namespaces and FQN (§8.1)
// ---------------------------------------------------------------------------

#[test]
fn test_fqn_file_scoped_namespace() {
    let code = "namespace MyApp.Services;\npublic class UserService {}";
    let entities = extract(code);
    let e = find_entity(&entities, "UserService", &EntityKind::CSharpClass);
    assert_eq!(e.fqn, "MyApp.Services.UserService");
}

#[test]
fn test_fqn_block_namespace() {
    let code = "namespace MyApp\n{\n    public class Foo {}\n}";
    let entities = extract(code);
    let e = find_entity(&entities, "Foo", &EntityKind::CSharpClass);
    assert_eq!(e.fqn, "MyApp.Foo");
}

#[test]
fn test_fqn_nested_block_namespace() {
    let code = r#"
namespace MyApp.Legacy
{
    namespace Deep
    {
        public class OldStyle {}
    }
}
"#;
    let entities = extract(code);
    let e = find_entity(&entities, "OldStyle", &EntityKind::CSharpClass);
    assert_eq!(e.fqn, "MyApp.Legacy.Deep.OldStyle");
}

#[test]
fn test_fqn_no_namespace() {
    let code = "public class Free {}";
    let entities = extract(code);
    let e = find_entity(&entities, "Free", &EntityKind::CSharpClass);
    assert_eq!(e.fqn, "Free");
}

#[test]
fn test_fqn_nested_type_in_type() {
    let code = r#"
namespace MyApp.Domain;
public class Container
{
    public class Nested {}
}
"#;
    let entities = extract(code);
    let e = find_entity(&entities, "Nested", &EntityKind::CSharpClass);
    assert_eq!(e.fqn, "MyApp.Domain.Container.Nested");
}

#[test]
fn test_fqn_nested_type_in_nested_namespace() {
    let code = r#"
namespace MyApp.Legacy
{
    namespace Deep
    {
        public class OldStyle
        {
            public class Inner {}
        }
    }
}
"#;
    let entities = extract(code);
    let e = find_entity(&entities, "Inner", &EntityKind::CSharpClass);
    assert_eq!(e.fqn, "MyApp.Legacy.Deep.OldStyle.Inner");
}

#[test]
fn test_fqn_method_under_file_scoped_namespace() {
    let code = r#"
namespace MyApp.Services;
public class UserService
{
    public Task<Dto> GetUserAsync(int id) { return null; }
}
"#;
    let entities = extract(code);
    let e = find_entity(&entities, "GetUserAsync", &EntityKind::CSharpMethod);
    assert_eq!(e.fqn, "MyApp.Services.UserService.GetUserAsync");
    assert_eq!(e.enclosing_class.as_deref(), Some("UserService"));
    assert_eq!(
        e.enclosing_class_fqn.as_deref(),
        Some("MyApp.Services.UserService"),
        "enclosing_class_fqn enables the exact CONTAINS auto-link"
    );
}

#[test]
fn test_fqn_member_of_nested_type() {
    let code = r#"
namespace App;
public class Outer
{
    public class Inner
    {
        public void Run() {}
    }
}
"#;
    let entities = extract(code);
    let e = find_entity(&entities, "Run", &EntityKind::CSharpMethod);
    assert_eq!(e.fqn, "App.Outer.Inner.Run");
}

// ---------------------------------------------------------------------------
// Phase 4 — references (§9)
// ---------------------------------------------------------------------------

#[test]
fn test_inheritance_class_extends_and_implements() {
    let code = "class UserService : BaseService, IUserService {}";
    let tree = parse_csharp_snippet(code).unwrap();
    let class_node = find_first_node(tree.root_node(), &["class_declaration"]).unwrap();
    let mut intents = Vec::new();
    extract_class_inheritance_csharp(class_node, code.as_bytes(), &mut intents);
    assert_eq!(collect_extends(&intents), ["BaseService"]);
    assert_eq!(collect_implements(&intents), ["IUserService"]);
}

#[test]
fn test_inheritance_class_leading_interface_goes_to_implements() {
    // The §3.3 heuristic: a first entry matching `^I[A-Z]` is an interface.
    let code = "class UserRepository : IRepository {}";
    let tree = parse_csharp_snippet(code).unwrap();
    let class_node = find_first_node(tree.root_node(), &["class_declaration"]).unwrap();
    let mut intents = Vec::new();
    extract_class_inheritance_csharp(class_node, code.as_bytes(), &mut intents);
    assert!(collect_extends(&intents).is_empty());
    assert_eq!(collect_implements(&intents), ["IRepository"]);
}

#[test]
fn test_inheritance_interface_extends_everything() {
    let code = "interface IAdminRepository : IRepository<User>, IDisposable {}";
    let tree = parse_csharp_snippet(code).unwrap();
    let iface = find_first_node(tree.root_node(), &["interface_declaration"]).unwrap();
    let mut intents = Vec::new();
    extract_class_inheritance_csharp(iface, code.as_bytes(), &mut intents);
    assert_eq!(collect_extends(&intents), ["IRepository", "IDisposable"]);
    assert!(collect_implements(&intents).is_empty());
}

#[test]
fn test_inheritance_struct_only_implements() {
    let code = "struct Point : IEquatable<Point> {}";
    let tree = parse_csharp_snippet(code).unwrap();
    let struct_node = find_first_node(tree.root_node(), &["struct_declaration"]).unwrap();
    let mut intents = Vec::new();
    extract_class_inheritance_csharp(struct_node, code.as_bytes(), &mut intents);
    assert_eq!(collect_implements(&intents), ["IEquatable"]);
    assert!(
        collect_extends(&intents).is_empty(),
        "a struct never extends"
    );
}

#[test]
fn test_inheritance_record_class_first_extends() {
    let code = "record Employee : Person, IComparable<Employee> {}";
    let tree = parse_csharp_snippet(code).unwrap();
    let record = find_first_node(tree.root_node(), &["record_declaration"]).unwrap();
    assert!(!super::refs::record_is_struct(record));
    let mut intents = Vec::new();
    extract_class_inheritance_csharp(record, code.as_bytes(), &mut intents);
    assert_eq!(collect_extends(&intents), ["Person"]);
    assert_eq!(collect_implements(&intents), ["IComparable"]);
}

#[test]
fn test_inheritance_record_struct_only_implements() {
    let code = "record struct Coord : IEquatable<Coord> {}";
    let tree = parse_csharp_snippet(code).unwrap();
    let record = find_first_node(tree.root_node(), &["record_declaration"]).unwrap();
    assert!(super::refs::record_is_struct(record));
    let mut intents = Vec::new();
    extract_class_inheritance_csharp(record, code.as_bytes(), &mut intents);
    assert_eq!(collect_implements(&intents), ["IEquatable"]);
    assert!(collect_extends(&intents).is_empty());
}

#[test]
fn test_inheritance_generic_arguments_stripped() {
    // v1.3.6-parity: base entries are stripped of type arguments.
    let code = "class UserRepository : IRepository<User> {}";
    let tree = parse_csharp_snippet(code).unwrap();
    let class_node = find_first_node(tree.root_node(), &["class_declaration"]).unwrap();
    let mut intents = Vec::new();
    extract_class_inheritance_csharp(class_node, code.as_bytes(), &mut intents);
    assert_eq!(collect_implements(&intents), ["IRepository"]);
}

#[test]
fn test_attribute_references_emitted_as_calls() {
    let code = r#"
[Obsolete("Use V2 instead")]
class UserService {}
"#;
    let tree = parse_csharp_snippet(code).unwrap();
    let class_node = find_first_node(tree.root_node(), &["class_declaration"]).unwrap();
    let mut intents = Vec::new();
    extract_attribute_references(class_node, code.as_bytes(), &mut intents);
    assert!(
        intents
            .iter()
            .any(|i| matches!(i, ReferenceIntent::Call { method, .. } if method == "Obsolete")),
        "attribute names must be emitted, got {intents:?}"
    );
}

#[test]
fn test_type_references_from_method_signature_and_body() {
    let code = r#"
class UserService
{
    Task<UserDto> GetUserAsync(int id)
    {
        var dto = new UserDto(id);
        return null;
    }
}
"#;
    let tree = parse_csharp_snippet(code).unwrap();
    let method = find_first_node(tree.root_node(), &["method_declaration"]).unwrap();
    let mut intents = Vec::new();
    extract_reference_intents_csharp(method, code.as_bytes(), &mut intents);
    let type_refs: Vec<&str> = intents
        .iter()
        .filter_map(|i| match i {
            ReferenceIntent::TypeReference { type_name, .. } => Some(type_name.as_str()),
            _ => None,
        })
        .collect();
    assert!(type_refs.contains(&"UserDto"), "got {type_refs:?}");
    assert!(
        intents
            .iter()
            .any(|i| matches!(i, ReferenceIntent::Call { method, .. } if method == "UserDto")),
        "object_creation_expression must emit a Call intent"
    );
}

#[test]
fn test_call_receiver_substituted_with_field_type() {
    let code = r#"
class UserService
{
    private readonly UserRepository _repository;
    void Load(int id)
    {
        var u = _repository.FindByIdAsync(id);
    }
}
"#;
    let tree = parse_csharp_snippet(code).unwrap();
    let method = find_first_node(tree.root_node(), &["method_declaration"]).unwrap();
    let mut intents = Vec::new();
    extract_reference_intents_csharp(method, code.as_bytes(), &mut intents);
    let call = intents.iter().find_map(|i| match i {
        ReferenceIntent::Call {
            method, receiver, ..
        } if method == "FindByIdAsync" => Some(receiver.clone()),
        _ => None,
    });
    assert_eq!(
        call,
        Some(Some("UserRepository".to_string())),
        "field receiver must be substituted with its declared type"
    );
}

#[test]
fn test_call_base_receiver_maps_to_super() {
    let code = r#"
class Derived : Base
{
    override void Process(string input)
    {
        base.Process(input);
    }
}
"#;
    let tree = parse_csharp_snippet(code).unwrap();
    let method = find_first_node(tree.root_node(), &["method_declaration"]).unwrap();
    let mut intents = Vec::new();
    extract_reference_intents_csharp(method, code.as_bytes(), &mut intents);
    let call = intents.iter().find_map(|i| match i {
        ReferenceIntent::Call {
            method, receiver, ..
        } if method == "Process" => Some(receiver.clone()),
        _ => None,
    });
    assert_eq!(
        call,
        Some(Some("super".to_string())),
        "C# `base.` must map to the resolver's `super` receiver"
    );
}

#[test]
fn test_orphan_pass_captures_top_level_statements() {
    // C# 9 top-level statements (§13): no enclosing entity, so the orphan
    // pass must collect the calls into a synthetic <module> entity.
    let code = r#"
using System;
Console.WriteLine("hello");
Foo();
"#;
    let entities = extract(code);
    let module = entities
        .iter()
        .find(|e| e.name == "<module>")
        .expect("orphan pass must create a synthetic <module> entity");
    assert_eq!(module.kind, EntityKind::CSharpNamespace);
    assert!(
        module
            .reference_intents
            .iter()
            .any(|i| matches!(i, ReferenceIntent::Call { method, .. } if method == "Foo")),
        "top-level call must be orphaned onto <module>, got {:?}",
        module.reference_intents
    );
}

#[test]
fn test_xml_doc_comments_captured_as_docstring() {
    let code = r#"
namespace App;
/// <summary>
/// Generic persistence abstraction.
/// </summary>
public interface IRepository
{
    /// <summary>Finds an entity by its identifier.</summary>
    Task<object> FindByIdAsync(int id);
}
"#;
    let entities = extract(code);
    let iface = find_entity(&entities, "IRepository", &EntityKind::CSharpInterface);
    assert_eq!(
        iface.docstring.as_deref(),
        Some("Generic persistence abstraction."),
        "XML doc comment must be captured with tags stripped"
    );
    let method = find_entity(&entities, "FindByIdAsync", &EntityKind::CSharpMethod);
    assert_eq!(
        method.docstring.as_deref(),
        Some("Finds an entity by its identifier.")
    );
}

#[test]
fn test_attribute_captured_in_decorators() {
    let code = r#"
[Obsolete("Use UserServiceV2 instead")]
public class UserService {}
"#;
    let entities = extract(code);
    let e = find_entity(&entities, "UserService", &EntityKind::CSharpClass);
    assert!(
        e.decorators.iter().any(|d| d.contains("Obsolete")),
        "attribute must appear in decorators, got {:?}",
        e.decorators
    );
}

// ---------------------------------------------------------------------------
// Phase 5 — OVERRIDES (§10.1), end-to-end through resolution
// ---------------------------------------------------------------------------

/// Parse two snippets as separate files and resolve their relationships.
fn resolve_together(repo_files: &[(&str, &str)]) -> Vec<ResolutionEntity> {
    let mut entities = Vec::new();
    for (path, code) in repo_files {
        let parsed = extract_entities(
            code,
            tree_sitter_c_sharp::LANGUAGE.into(),
            DEFAULT_CSHARP_QUERY,
            "csharp",
            path,
            "test-repo",
        )
        .expect("extraction failed");
        entities.extend(parsed.into_iter().map(|e| {
            let mut r = ResolutionEntity::from(&e);
            r.file_path = path.to_string();
            r
        }));
    }
    crate::pipeline::ingest::resolve_reference_intents(&mut entities);
    entities
}

fn has_rel(e: &ResolutionEntity, target: uuid::Uuid, rel: RelationshipType) -> bool {
    e.relationships.contains(&(target, rel))
}

#[test]
fn test_override_csharp_interface_impl() {
    let entities = resolve_together(&[
        (
            "IRepository.cs",
            "namespace App;\npublic interface IRepository\n{\n    Task<object> FindByIdAsync(int id);\n}",
        ),
        (
            "UserRepository.cs",
            "namespace App;\npublic class UserRepository : IRepository\n{\n    public Task<object> FindByIdAsync(int id) { return null; }\n}",
        ),
    ]);
    let iface_method = entities
        .iter()
        .find(|e| e.fqn == "App.IRepository.FindByIdAsync")
        .expect("interface method");
    let impl_method = entities
        .iter()
        .find(|e| e.fqn == "App.UserRepository.FindByIdAsync")
        .expect("impl method");
    assert!(
        has_rel(impl_method, iface_method.uuid, RelationshipType::Overrides),
        "interface implementation must produce OVERRIDES"
    );
}

#[test]
fn test_override_csharp_class_virtual() {
    let entities = resolve_together(&[
        (
            "BaseService.cs",
            "namespace App;\npublic abstract class BaseService\n{\n    public virtual string Process(string input) { return input; }\n}",
        ),
        (
            "UserService.cs",
            "namespace App;\npublic class UserService : BaseService\n{\n    public override string Process(string input) { return input; }\n}",
        ),
    ]);
    let base_method = entities
        .iter()
        .find(|e| e.fqn == "App.BaseService.Process")
        .expect("virtual method");
    let derived_method = entities
        .iter()
        .find(|e| e.fqn == "App.UserService.Process")
        .expect("override method");
    assert!(has_rel(
        derived_method,
        base_method.uuid,
        RelationshipType::Overrides
    ));
}

#[test]
fn test_override_csharp_constructor_excluded() {
    let entities = resolve_together(&[
        (
            "Base.cs",
            "namespace App;\npublic class Base\n{\n    public Base() {}\n}",
        ),
        (
            "Derived.cs",
            "namespace App;\npublic class Derived : Base\n{\n    public Derived() {}\n}",
        ),
    ]);
    let derived_ctor = entities
        .iter()
        .find(|e| e.fqn == "App.Derived.Derived")
        .expect("derived constructor");
    assert!(
        derived_ctor
            .relationships
            .iter()
            .all(|(_, r)| *r != RelationshipType::Overrides),
        "constructors must never get OVERRIDES edges"
    );
}

#[test]
fn test_override_csharp_calls_resolve_across_files() {
    // C22/G31 contract: a field-typed receiver call resolves to the exact
    // implementation method (not the interface declaration).
    let entities = resolve_together(&[
        (
            "IRepository.cs",
            "namespace App;\npublic interface IRepository\n{\n    Task<object> FindByIdAsync(int id);\n}",
        ),
        (
            "UserRepository.cs",
            "namespace App;\npublic class UserRepository : IRepository\n{\n    public Task<object> FindByIdAsync(int id) { return null; }\n}",
        ),
        (
            "UserService.cs",
            "namespace App;\npublic class UserService\n{\n    private readonly UserRepository _repository;\n    public Task<object> GetUserAsync(int id) { return _repository.FindByIdAsync(id); }\n}",
        ),
    ]);
    let impl_method = entities
        .iter()
        .find(|e| e.fqn == "App.UserRepository.FindByIdAsync")
        .expect("impl method");
    let caller = entities
        .iter()
        .find(|e| e.fqn == "App.UserService.GetUserAsync")
        .expect("caller");
    assert!(
        has_rel(caller, impl_method.uuid, RelationshipType::Calls),
        "field receiver call must resolve to the implementation method, got {:?}",
        caller.relationships
    );
}

// ---------------------------------------------------------------------------
// FQN prefix helpers (direct unit coverage)
// ---------------------------------------------------------------------------

#[test]
fn test_file_scoped_namespace_extraction_helpers() {
    let code = "namespace A.B;\nclass C {}";
    let tree = parse_csharp_snippet(code).unwrap();
    assert_eq!(
        extract_file_scoped_namespace(tree.root_node(), code.as_bytes()),
        Some("A.B".to_string())
    );
    let class_node = find_node(tree.root_node(), "class_declaration", "C", code.as_bytes());
    assert_eq!(
        build_csharp_fqn_prefix(class_node, code.as_bytes()),
        None,
        "file-scoped namespaces are not ancestors; the pre-pass covers them"
    );
}

#[test]
fn test_is_pattern_emits_qualified_nested_type_reference() {
    let code = "namespace App;\npublic class G { public bool Enabled(Device d) => !(d.Owner is GestureOwner.Off); }";
    let entities = extract(code);
    let method = find_entity(&entities, "Enabled", &EntityKind::CSharpMethod);
    assert!(
        method.reference_intents.iter().any(|i| matches!(i, ReferenceIntent::TypeReference { type_name, .. } if type_name == "GestureOwner.Off")),
        "should emit qualified type reference to GestureOwner.Off, got {:?}",
        method.reference_intents
    );
    assert!(
        method.reference_intents.iter().any(|i| matches!(i, ReferenceIntent::TypeReference { type_name, .. } if type_name == "GestureOwner")),
        "should also emit base identifier GestureOwner, got {:?}",
        method.reference_intents
    );
}

#[test]
fn test_switch_arm_constant_pattern_emits_qualified_reference() {
    let code = "namespace App;\npublic class G { public int? OwnerOf(Device d) => d.Owner switch { MyApp.Gestures.GestureOwner.Off => null, _ => null }; }";
    let entities = extract(code);
    let method = find_entity(&entities, "OwnerOf", &EntityKind::CSharpMethod);
    assert!(
        method.reference_intents.iter().any(|i| matches!(i, ReferenceIntent::TypeReference { type_name, .. } if type_name == "MyApp.Gestures.GestureOwner.Off")),
        "should emit qualified type reference, got {:?}",
        method.reference_intents
    );
}

#[test]
fn test_static_member_access_emits_qualified_reference() {
    let code = "namespace App;\npublic class G { public void Disable(Device d) => d.Owner = MyApp.Gestures.GestureOwner.OffValue; }";
    let entities = extract(code);
    let method = find_entity(&entities, "Disable", &EntityKind::CSharpMethod);
    assert!(
        method.reference_intents.iter().any(|i| matches!(i, ReferenceIntent::TypeReference { type_name, .. } if type_name == "MyApp.Gestures.GestureOwner.OffValue")),
        "should emit qualified type reference to OffValue, got {:?}",
        method.reference_intents
    );
}

#[test]
fn test_declaration_pattern_emits_qualified_not_bare() {
    let code = "namespace App;\npublic class G { public int? OwnerOf(Device d) => d.Owner switch { GestureOwner.Button b => b.Id, _ => null }; }";
    let entities = extract(code);
    let method = find_entity(&entities, "OwnerOf", &EntityKind::CSharpMethod);
    assert!(
        method.reference_intents.iter().any(|i| matches!(i, ReferenceIntent::TypeReference { type_name, .. } if type_name == "GestureOwner.Button")),
        "should emit qualified type reference to Button, got {:?}",
        method.reference_intents
    );
    assert!(
        !method.reference_intents.iter().any(|i| matches!(i, ReferenceIntent::TypeReference { type_name, .. } if type_name == "Button")),
        "should not emit bare Button type reference, got {:?}",
        method.reference_intents
    );
}

#[test]
fn test_enum_member_name_is_not_a_type_reference() {
    let code = "namespace App;\npublic enum LightingEffect { Solid, Breathing, Cycle, Off }";
    let entities = extract(code);
    let enum_ent = find_entity(&entities, "LightingEffect", &EntityKind::CSharpEnum);
    assert!(
        !enum_ent.reference_intents.iter().any(|i| matches!(i, ReferenceIntent::TypeReference { type_name, .. } if type_name == "Off" || type_name == "Solid")),
        "enum members should not yield type references, got {:?}",
        enum_ent.reference_intents
    );
}

#[test]
fn test_declaration_names_are_not_type_references() {
    let code = "namespace App;\npublic record GestureOwner { public record Off : GestureOwner; }";
    let entities = extract(code);
    let owner_rec = find_entity(&entities, "GestureOwner", &EntityKind::CSharpRecord);
    assert!(
        !owner_rec.reference_intents.iter().any(
            |i| matches!(i, ReferenceIntent::TypeReference { type_name, .. } if type_name == "Off")
        ),
        "nested declaration name should not be type reference, got {:?}",
        owner_rec.reference_intents
    );
}

#[test]
fn test_invocation_receiver_path_does_not_duplicate_call_intent() {
    let code =
        "namespace App;\npublic class G { public void Write() { Console.WriteLine(\"hello\"); } }";
    let entities = extract(code);
    let method = find_entity(&entities, "Write", &EntityKind::CSharpMethod);
    assert!(
        !method.reference_intents.iter().any(|i| matches!(i, ReferenceIntent::TypeReference { type_name, .. } if type_name == "Console.WriteLine")),
        "should not emit type reference for Console.WriteLine, got {:?}",
        method.reference_intents
    );
}

/// Fixture for the `GestureOwner.Off` regression: a nested record named `Off`
/// that collides with an unrelated enum member `LightingEffect.Off`.
fn gesture_owner_fixture() -> Vec<ResolutionEntity> {
    resolve_together(&[
        (
            "GestureOwner.cs",
            "namespace MyApp.Gestures;\npublic abstract record GestureOwner {\n  public sealed record Off : GestureOwner;\n  public sealed record Button(int Id) : GestureOwner;\n  public static readonly Off OffValue = new();\n}",
        ),
        (
            "LightingEffect.cs",
            "namespace MyApp.ViewModels;\npublic enum LightingEffect { Solid, Breathing, Cycle, Off }",
        ),
        (
            "GestureConfig.cs",
            "namespace MyApp.Gestures;\npublic class DeviceEntry { public GestureOwner? Owner { get; set; } }\npublic class GestureConfig {\n  public bool GesturesEnabled(DeviceEntry d) => !(d.Owner is GestureOwner.Off);\n  public int? OwnerOf(DeviceEntry d) => d.Owner switch {\n    MyApp.Gestures.GestureOwner.Off => null,\n    GestureOwner.Button b => b.Id,\n    _ => null,\n  };\n  public void Disable(DeviceEntry d) => d.Owner = MyApp.Gestures.GestureOwner.OffValue;\n}",
        ),
    ])
}

fn by_fqn<'a>(entities: &'a [ResolutionEntity], fqn: &str) -> &'a ResolutionEntity {
    entities
        .iter()
        .find(|e| e.fqn == fqn)
        .unwrap_or_else(|| panic!("entity `{fqn}` not found"))
}

#[test]
fn test_gesture_owner_off_no_spurious_edge_from_homonym_enum() {
    let entities = gesture_owner_fixture();
    let lighting_effect = by_fqn(&entities, "MyApp.ViewModels.LightingEffect");
    let off_record = by_fqn(&entities, "MyApp.Gestures.GestureOwner.Off");

    assert!(
        !has_rel(
            lighting_effect,
            off_record.uuid,
            RelationshipType::References
        ),
        "spurious edge LightingEffect -> Off must not exist"
    );
}

#[test]
fn test_gesture_owner_off_referenced_by_consumers() {
    let entities = gesture_owner_fixture();
    let off_record = by_fqn(&entities, "MyApp.Gestures.GestureOwner.Off");
    let off_value = by_fqn(&entities, "MyApp.Gestures.GestureOwner.OffValue");
    let enabled_method = by_fqn(&entities, "MyApp.Gestures.GestureConfig.GesturesEnabled");
    let owner_of_method = by_fqn(&entities, "MyApp.Gestures.GestureConfig.OwnerOf");
    let disable_method = by_fqn(&entities, "MyApp.Gestures.GestureConfig.Disable");

    assert!(
        has_rel(
            enabled_method,
            off_record.uuid,
            RelationshipType::References
        ),
        "GesturesEnabled -> Off REFERENCES missing"
    );
    assert!(
        has_rel(
            owner_of_method,
            off_record.uuid,
            RelationshipType::References
        ),
        "OwnerOf -> Off REFERENCES missing"
    );
    assert!(
        has_rel(disable_method, off_value.uuid, RelationshipType::References),
        "Disable -> OffValue REFERENCES missing"
    );
}

#[test]
fn test_gesture_owner_nested_records_extend_parent_without_back_edges() {
    let entities = gesture_owner_fixture();
    let gesture_owner = by_fqn(&entities, "MyApp.Gestures.GestureOwner");
    let off_record = by_fqn(&entities, "MyApp.Gestures.GestureOwner.Off");
    let button_record = by_fqn(&entities, "MyApp.Gestures.GestureOwner.Button");

    assert!(
        has_rel(off_record, gesture_owner.uuid, RelationshipType::Extends),
        "Off -> GestureOwner EXTENDS missing"
    );
    assert!(
        has_rel(button_record, gesture_owner.uuid, RelationshipType::Extends),
        "Button -> GestureOwner EXTENDS missing"
    );

    assert!(
        !has_rel(gesture_owner, off_record.uuid, RelationshipType::References),
        "GestureOwner -> Off REFERENCES must not exist"
    );
    assert!(
        !has_rel(
            gesture_owner,
            button_record.uuid,
            RelationshipType::References
        ),
        "GestureOwner -> Button REFERENCES must not exist"
    );
}