knot 1.11.4

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
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
use std::collections::{HashMap, HashSet, VecDeque};
use uuid::Uuid;

use super::context::ResolutionContext;
use crate::models::{CallIntent, EntityKind};

pub(crate) fn disambiguate_overload(
    fqn_uuid: Uuid,
    intent: &CallIntent,
    ctx: &ResolutionContext,
    expected_enclosing_class: Option<&str>,
) -> Uuid {
    if let Some(ac) = intent.arg_count
        && let Some(ac_map) = ctx.uuid_to_arg_count
        && ac_map.get(&fqn_uuid) != Some(&ac)
        && let Some(uuids) = ctx.name_to_uuids.get(&intent.method)
    {
        if let Some(class_name) = expected_enclosing_class
            && let Some(fqn_map) = ctx.uuid_to_fqn
        {
            let dot_fqn = format!("{}.{}", class_name, intent.method);
            let colon_fqn = format!("{}::{}", class_name, intent.method);

            if let Some(&better) = uuids.iter().find(|&&u| {
                ac_map.get(&u) == Some(&ac)
                    && fqn_map
                        .get(&u)
                        .is_some_and(|fqn| *fqn == dot_fqn || *fqn == colon_fqn)
            }) {
                return better;
            }
        }

        if let Some(&better) = uuids.iter().find(|u| ac_map.get(u) == Some(&ac)) {
            return better;
        }
    }
    fqn_uuid
}

/// Disambiguate candidates by scoring each one's FQN against the segments of a
/// chained receiver expression (e.g. `engine.chatter.method`).
///
/// For a receiver like `engine.chatter` and candidates whose FQNs are
/// `llamafactory.webui.chatter.WebChatModel.method` and
/// `llamafactory.model.loader.method`, the first FQN contains the receiver
/// segment `chatter` (score 1) while the second contains nothing (score 0).
/// The unique top-scorer wins; ties fall through to other heuristics.
///
/// Receivers without dots are ignored — the existing same-file / unique-name
/// fallbacks already handle them.
pub(crate) fn disambiguate_by_receiver_chain(
    candidate_uuids: &[Uuid],
    receiver: &str,
    ctx: &ResolutionContext,
) -> Option<Uuid> {
    if !receiver.contains('.') {
        return None;
    }
    let uuid_to_fqn = ctx.uuid_to_fqn?;

    let segments: Vec<&str> = receiver
        .split('.')
        .map(str::trim)
        .filter(|s| !s.is_empty() && *s != "self" && *s != "cls" && *s != "this")
        .collect();
    if segments.is_empty() {
        return None;
    }

    let mut best_score: usize = 0;
    let mut best_uuid: Option<Uuid> = None;
    let mut tied = false;

    for uuid in candidate_uuids {
        let Some(fqn) = uuid_to_fqn.get(uuid) else {
            continue;
        };
        let fqn_segments: Vec<&str> = fqn.split(['.', ':']).collect();
        let score = segments
            .iter()
            .filter(|seg| fqn_segments.contains(seg))
            .count();
        if score == 0 {
            continue;
        }
        match score.cmp(&best_score) {
            std::cmp::Ordering::Greater => {
                best_score = score;
                best_uuid = Some(*uuid);
                tied = false;
            }
            std::cmp::Ordering::Equal => {
                tied = true;
            }
            std::cmp::Ordering::Less => {}
        }
    }

    if tied { None } else { best_uuid }
}

/// Detects receiver expressions that denote a `super` invocation.
///
/// Covers:
/// - Java/Kotlin: `super.method()` → receiver is `"super"`.
/// - Python 3: `super().__init__()` → receiver is `"super()"`.
/// - Python 2 / explicit form: `super(WebChatModel, self).__init__()` →
///   receiver is `"super(WebChatModel, self)"`.
pub(crate) fn is_super_receiver(receiver: &str) -> bool {
    receiver == "super" || receiver == "super()" || receiver.starts_with("super(")
}

pub(crate) fn lookup_fqn(
    class: &str,
    method: &str,
    fqn_to_uuid: &HashMap<String, Uuid>,
) -> Option<Uuid> {
    let dot_fqn = format!("{}.{}", class, method);
    if let Some(&uuid) = fqn_to_uuid.get(&dot_fqn) {
        return Some(uuid);
    }
    let colon_fqn = format!("{}::{}", class, method);
    fqn_to_uuid.get(&colon_fqn).copied()
}

pub(crate) fn find_entity_in_same_file(
    candidate_uuids: &[Uuid],
    caller_file_path: &str,
    uuid_to_file: &HashMap<Uuid, String>,
) -> Option<Uuid> {
    for &uuid in candidate_uuids {
        if let Some(file_path) = uuid_to_file.get(&uuid)
            && file_path == caller_file_path
        {
            return Some(uuid);
        }
    }
    None
}

/// Rank equally-plausible resolution candidates with a total order and return
/// the winner.
///
/// `HashMap::iter()` / `HashMap::values()` order is randomized per process
/// (`std::collections::hash_map::RandomState`), so a "first match wins" scan
/// over a map emits a different edge target on every run whenever several
/// candidates match at once. Candidates are ranked by:
///
/// 1. same-file locality — a candidate declared in the caller's own file wins
///    outright, which is the criterion [`find_entity_in_same_file`] already
///    establishes elsewhere in this module;
/// 2. the lexicographically smallest FQN;
/// 3. the smallest UUID, reachable when two distinct entities carry the same
///    FQN — this completes the ordering so the winner is always unique.
///
/// `caller_file` is the caller's file path together with the uuid → file map.
/// Pass `None` when same-file locality is not meaningful for the match (a VCL
/// `include` target is a different file from the includer by construction);
/// rule 1 is then skipped and the FQN / UUID ordering decides.
///
/// This only picks *which* target an already-decided edge points at. It never
/// changes whether the edge is created: a caller that found at least one
/// candidate keeps resolving to exactly one target.
pub(crate) fn pick_deterministic_candidate(
    candidates: &[(&str, Uuid)],
    caller_file: Option<(&str, &HashMap<Uuid, String>)>,
) -> Option<Uuid> {
    candidates
        .iter()
        .map(|&(fqn, uuid)| {
            let in_caller_file = caller_file.is_some_and(|(file, uuid_to_file)| {
                uuid_to_file.get(&uuid).is_some_and(|f| f == file)
            });
            // `!in_caller_file` is `false` for same-file candidates so they
            // sort first; the tuple as a whole is a total order, so the winner
            // is unique and independent of the order candidates arrived in.
            (!in_caller_file, fqn, uuid)
        })
        .min()
        .map(|(_, _, uuid)| uuid)
}

pub(crate) fn find_by_arg_count(
    uuids: &[Uuid],
    arg_count: usize,
    uuid_to_arg_count: &HashMap<Uuid, usize>,
) -> Option<Uuid> {
    let matches: Vec<&Uuid> = uuids
        .iter()
        .filter(|u| uuid_to_arg_count.get(u) == Some(&arg_count))
        .collect();
    if matches.len() == 1 {
        Some(*matches[0])
    } else {
        None
    }
}

/// Redirect a resolved class call UUID to its constructor (`__init__`) when applicable.
///
/// For languages where class instantiation is semantically equivalent to invoking
/// the constructor (Python `Foo()`, etc.), this turns a `(Foo, Calls)` edge into a
/// `(Foo.__init__, Calls)` edge. The redirect is applied **after** resolution so it
/// works for every parser without language-specific changes.
///
/// Only triggers when:
/// 1. `uuid` resolves to a class-like entity (`Class`, `PythonClass`, `RustStruct`,
///    or `CStruct`).
/// 2. The class has an explicit `__init__` method, or one is reachable via the
///    extends-map (inheritance chain).
///
/// Other intents (`TypeReference`, `ValueReference`, `Extends`, …) are unaffected.
pub(crate) fn redirect_class_call_to_constructor(
    uuid: Uuid,
    caller_file_path: &str,
    ctx: &ResolutionContext,
) -> Uuid {
    let Some(kind_map) = ctx.uuid_to_kind else {
        return uuid;
    };
    let Some(name_map) = ctx.uuid_to_name else {
        return uuid;
    };

    let Some(kind) = kind_map.get(&uuid) else {
        return uuid;
    };
    if !matches!(
        kind,
        EntityKind::Class | EntityKind::RustStruct | EntityKind::CStruct | EntityKind::PythonClass
    ) {
        return uuid;
    }

    let Some(class_name) = name_map.get(&uuid) else {
        return uuid;
    };

    if let Some(init_uuid) = lookup_init_in_class_hierarchy(class_name, caller_file_path, ctx) {
        return init_uuid;
    }

    if let Some(parents) = ctx.extends_map.get(class_name) {
        for parent in parents {
            if let Some(init_uuid) = lookup_init_in_class_hierarchy(parent, caller_file_path, ctx) {
                return init_uuid;
            }
        }
    }

    uuid
}

/// Locate a class's `__init__` constructor by trying every FQN shape the parser
/// may have produced (`<ClassName>.__init__`, `<mod.ClassName>.__init__`, …).
fn lookup_init_in_class_hierarchy(
    class_name: &str,
    caller_file_path: &str,
    ctx: &ResolutionContext,
) -> Option<Uuid> {
    lookup_method_in_class_hierarchy(class_name, "__init__", caller_file_path, ctx)
}

/// Locate `<class_name>.<method>` by trying every FQN shape the parser may
/// have produced. Falls back to suffix matching against the FQN map so that
/// short class names (e.g. `"ChatModel"`) resolve to fully-qualified
/// methods (e.g. `"llamafactory.chat.ChatModel.__init__"`).
fn lookup_method_in_class_hierarchy(
    class_name: &str,
    method: &str,
    caller_file_path: &str,
    ctx: &ResolutionContext,
) -> Option<Uuid> {
    if let Some(uuid) = lookup_fqn(class_name, method, ctx.fqn_to_uuid) {
        return Some(uuid);
    }

    if let Some(uuid_to_fqn) = ctx.uuid_to_fqn {
        // The suffix predicate matches every class that ends with the short
        // name, so a name reused across modules (`pkg.alpha.ChatModel`,
        // `pkg.beta.ChatModel`, …) yields several methods at once. Collect
        // them all and rank them instead of returning the first hit out of
        // the map: `uuid_to_fqn` iteration order is randomized per process.
        // Recall is unchanged — an edge is still produced whenever at least
        // one class FQN matches.
        let candidates: Vec<(&str, Uuid)> = uuid_to_fqn
            .values()
            .filter_map(|class_fqn| {
                let is_class_match = class_fqn == class_name
                    || class_fqn.ends_with(&format!(".{}", class_name))
                    || class_fqn.ends_with(&format!("::{}", class_name));
                if !is_class_match {
                    return None;
                }
                lookup_fqn_by_fqn(class_fqn, method, ctx.fqn_to_uuid)
                    .map(|uuid| (class_fqn.as_str(), uuid))
            })
            .collect();
        return pick_deterministic_candidate(
            &candidates,
            Some((caller_file_path, ctx.uuid_to_file)),
        );
    }

    None
}

/// Lookup `__init__` using a fully-qualified class path (handles `mod.Class.__init__`).
fn lookup_fqn_by_fqn(
    class_fqn: &str,
    method: &str,
    fqn_to_uuid: &HashMap<String, Uuid>,
) -> Option<Uuid> {
    lookup_fqn(class_fqn, method, fqn_to_uuid)
}

/// Fallback ladder for homonym candidates that share the callee's method name
/// (neither FQN nor receiver lookup matched):
///
/// 1. arg-count match, preferring a same-file candidate;
/// 2. same-file match;
/// 3. receiver-chain disambiguation (only when a receiver is available);
/// 4. a single unambiguous candidate.
fn resolve_homonym_fallback(
    uuids: &[Uuid],
    arg_count: Option<usize>,
    receiver: Option<&str>,
    caller_file_path: &str,
    ctx: &ResolutionContext,
) -> Option<Uuid> {
    if let (Some(ac), Some(ac_map)) = (arg_count, ctx.uuid_to_arg_count) {
        if let Some(&same_file_ac_uuid) = uuids.iter().find(|&&u| {
            ac_map.get(&u) == Some(&ac)
                && ctx
                    .uuid_to_file
                    .get(&u)
                    .is_some_and(|f| f == caller_file_path)
        }) {
            return Some(same_file_ac_uuid);
        }
        if let Some(u) = find_by_arg_count(uuids, ac, ac_map) {
            return Some(u);
        }
    }
    if let Some(same_file_uuid) =
        find_entity_in_same_file(uuids, caller_file_path, ctx.uuid_to_file)
    {
        return Some(same_file_uuid);
    }
    if let Some(receiver) = receiver
        && let Some(u) = disambiguate_by_receiver_chain(uuids, receiver, ctx)
    {
        return Some(u);
    }
    if uuids.len() == 1 {
        return uuids.first().copied();
    }
    None
}

fn resolve_super_call(
    intent: &CallIntent,
    caller_enclosing_class: Option<&str>,
    caller_file_path: &str,
    ctx: &ResolutionContext,
) -> Option<Uuid> {
    let enclosing_class = caller_enclosing_class?;
    let parents = ctx.extends_map.get(enclosing_class)?;
    for parent in parents {
        if let Some(uuid) =
            lookup_method_in_class_hierarchy(parent, &intent.method, caller_file_path, ctx)
        {
            return Some(disambiguate_overload(uuid, intent, ctx, Some(parent)));
        }
    }
    None
}

fn resolve_implicit_this_call(
    intent: &CallIntent,
    caller_enclosing_class: Option<&str>,
    ctx: &ResolutionContext,
) -> Option<Uuid> {
    if !(intent.receiver.is_none()
        || intent.receiver.as_deref() == Some("this")
        || intent.receiver.as_deref() == Some("self"))
    {
        return None;
    }
    let enclosing_class = caller_enclosing_class?;
    if let Some(uuid) = lookup_fqn(enclosing_class, &intent.method, ctx.fqn_to_uuid) {
        return Some(disambiguate_overload(
            uuid,
            intent,
            ctx,
            Some(enclosing_class),
        ));
    }

    if intent.receiver.as_deref() == Some("self")
        && let Some(parents) = ctx.extends_map.get(enclosing_class)
    {
        for parent in parents {
            if let Some(uuid) = lookup_fqn(parent, &intent.method, ctx.fqn_to_uuid) {
                return Some(uuid);
            }
        }
    }
    None
}

/// Locate `method` declared on a type whose simple (or partially qualified)
/// name is `class_name`: `CatalogProvider` matches
/// `com.api.CatalogProvider.fetchItems` but never
/// `com.impl.HttpCatalogProvider.fetchItems`. A single hash probe on the
/// class/member index replaces a scan over every FQN.
fn lookup_method_by_class_and_name(
    class_name: &str,
    method: &str,
    caller_file_path: &str,
    ctx: &ResolutionContext,
) -> Option<Uuid> {
    if let Some(uuid) = lookup_fqn(class_name, method, ctx.fqn_to_uuid) {
        return Some(uuid);
    }

    let simple_class = class_name.rsplit(['.', ':']).next()?;
    let entries = ctx
        .class_member_index
        .get(&format!("{simple_class}.{method}"))?;
    let suffix_dot = format!(".{class_name}.{method}");
    let suffix_colon = format!("::{class_name}::{method}");
    let candidates: Vec<(&str, Uuid)> = entries
        .iter()
        .filter(|(fqn, _)| fqn.ends_with(&suffix_dot) || fqn.ends_with(&suffix_colon))
        .map(|(fqn, uuid)| (fqn.as_str(), *uuid))
        .collect();
    pick_deterministic_candidate(&candidates, Some((caller_file_path, ctx.uuid_to_file)))
}

fn resolve_static_receiver_call(
    intent: &CallIntent,
    caller_file_path: &str,
    ctx: &ResolutionContext,
) -> Option<Uuid> {
    let receiver = intent.receiver.as_deref()?;
    if !receiver.chars().next().is_some_and(|c| c.is_uppercase()) {
        return None;
    }

    // Breadth-first over the receiver type and its `extends` ancestors, so a
    // method inherited from a parent type (e.g. a sub-interface field calling
    // a method declared on its super-interface) still resolves. The nearest
    // declaring type wins.
    let mut visited: HashSet<&str> = HashSet::from([receiver]);
    let mut queue: VecDeque<&str> = VecDeque::from([receiver]);
    while let Some(class_name) = queue.pop_front() {
        if let Some(uuid) =
            lookup_method_by_class_and_name(class_name, &intent.method, caller_file_path, ctx)
        {
            return Some(disambiguate_overload(uuid, intent, ctx, Some(class_name)));
        }
        let parents = ctx.extends_map.get(class_name).into_iter().flatten();
        for parent in parents {
            if visited.insert(parent.as_str()) {
                queue.push_back(parent.as_str());
            }
        }
    }

    None
}

fn resolve_receiver_call(
    intent: &CallIntent,
    caller_file_path: &str,
    ctx: &ResolutionContext,
) -> Option<Uuid> {
    let receiver = intent.receiver.as_ref()?;
    let receiver_class = if receiver.contains('.') {
        receiver
            .split('.')
            .next_back()
            .map(|s| s.trim())
            .unwrap_or(receiver)
    } else {
        receiver
    };

    if !receiver_class.is_empty() {
        if let Some(uuid) = lookup_fqn(receiver_class, &intent.method, ctx.fqn_to_uuid) {
            return Some(disambiguate_overload(
                uuid,
                intent,
                ctx,
                Some(receiver_class),
            ));
        }

        let mut chars = receiver_class.chars();
        let capitalized = if let Some(first) = chars.next() {
            first.to_uppercase().to_string() + chars.as_str()
        } else {
            receiver_class.to_string()
        };

        if let Some(uuid) = lookup_fqn(&capitalized, &intent.method, ctx.fqn_to_uuid) {
            return Some(disambiguate_overload(uuid, intent, ctx, Some(&capitalized)));
        }

        let method_dot = format!("{}.{}", receiver_class, intent.method);
        let capitalized_method_dot = format!("{}.{}", capitalized, intent.method);
        let method_colon = format!("{}::{}", receiver_class, intent.method);
        let capitalized_method_colon = format!("{}::{}", capitalized, intent.method);
        // The substring predicate is deliberately loose (`pkg.alpha.Widget.render`
        // and `pkg.beta.Widget.render` both contain `Widget.render`), so
        // several FQNs hit at once when a method name is reused across module
        // paths. Collect every hit and rank them instead of returning the
        // first one out of the map: `fqn_to_uuid` iteration order is
        // randomized per process. Recall is unchanged — an edge is still
        // produced whenever at least one FQN matches.
        let candidates: Vec<(&str, Uuid)> = ctx
            .fqn_to_uuid
            .iter()
            .filter(|(fqn, _)| {
                fqn.contains(&method_dot)
                    || fqn.contains(&capitalized_method_dot)
                    || fqn.contains(&method_colon)
                    || fqn.contains(&capitalized_method_colon)
            })
            .map(|(fqn, uuid)| (fqn.as_str(), *uuid))
            .collect();
        if let Some(uuid) =
            pick_deterministic_candidate(&candidates, Some((caller_file_path, ctx.uuid_to_file)))
        {
            return Some(uuid);
        }
    }

    if let Some(uuids) = ctx.name_to_uuids.get(&intent.method)
        && let Some(u) = resolve_homonym_fallback(
            uuids,
            intent.arg_count,
            Some(receiver.as_str()),
            caller_file_path,
            ctx,
        )
    {
        return Some(u);
    }

    None
}

fn resolve_bare_call(
    intent: &CallIntent,
    caller_file_path: &str,
    ctx: &ResolutionContext,
) -> Option<Uuid> {
    if intent.receiver.is_some() {
        return None;
    }
    let uuids = ctx.name_to_uuids.get(&intent.method)?;
    resolve_homonym_fallback(uuids, intent.arg_count, None, caller_file_path, ctx)
}

pub(crate) fn resolve_single_call_intent(
    intent: &CallIntent,
    caller_file_path: &str,
    caller_enclosing_class: Option<&str>,
    ctx: &ResolutionContext,
) -> Option<Uuid> {
    // `super.` calls are terminal: an unresolved super() must never fall
    // through to the bare-name fallback (it would be misattributed to self).
    if intent.receiver.as_deref().is_some_and(is_super_receiver) {
        return resolve_super_call(intent, caller_enclosing_class, caller_file_path, ctx);
    }
    resolve_implicit_this_call(intent, caller_enclosing_class, ctx)
        .or_else(|| resolve_static_receiver_call(intent, caller_file_path, ctx))
        .or_else(|| resolve_receiver_call(intent, caller_file_path, ctx))
        .or_else(|| resolve_bare_call(intent, caller_file_path, ctx))
}

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

    #[test]
    fn test_resolve_local_call() {
        let mut caller = mock_resolution_entity("methodA", "ClassA.methodA", Some("ClassA"));
        let callee = mock_resolution_entity("methodB", "ClassA.methodB", Some("ClassA"));

        caller.reference_intents.push(ReferenceIntent::Call {
            method: "methodB".to_string(),
            receiver: None,
            line: 10,
            arg_count: None,
        });

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

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

    #[test]
    fn test_resolve_static_call() {
        let mut caller = mock_resolution_entity("main", "App.main", None);
        let callee = mock_resolution_entity("staticMethod", "Utils.staticMethod", Some("Utils"));

        caller.reference_intents.push(ReferenceIntent::Call {
            method: "staticMethod".to_string(),
            receiver: Some("Utils".to_string()),
            line: 5,
            arg_count: None,
        });

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

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

    #[test]
    fn test_resolve_instance_call_fuzzy() {
        let mut caller = mock_resolution_entity("doWork", "Service.doWork", Some("Service"));
        let callee = mock_resolution_entity("execute", "Worker.execute", Some("Worker"));

        caller.reference_intents.push(ReferenceIntent::Call {
            method: "execute".to_string(),
            receiver: Some("worker".to_string()),
            line: 20,
            arg_count: None,
        });

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

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

    #[test]
    fn test_e2e_rust_same_file_function_resolution() {
        let orphans_fn = ResolutionEntity {
            uuid: Uuid::new_v4(),
            kind: EntityKind::Function,
            name: "find_nearest_entity_by_line".to_string(),
            fqn: "knot::pipeline::parser::orphans::find_nearest_entity_by_line".to_string(),
            file_path: "src/pipeline/parser/orphans.rs".to_string(),
            enclosing_class: None,
            enclosing_class_fqn: None,
            signature: None,
            reference_intents: Vec::new(),
            relationships: Vec::new(),
            alias_module_path: None,
            original_export_name: None,
            default_export: None,
            is_test_context: false,
        };

        let rust_fn = ResolutionEntity {
            uuid: Uuid::new_v4(),
            kind: EntityKind::Function,
            name: "find_nearest_entity_by_line".to_string(),
            fqn: "knot::pipeline::parser::languages::rust::find_nearest_entity_by_line".to_string(),
            file_path: "src/pipeline/parser/languages/rust.rs".to_string(),
            enclosing_class: None,
            enclosing_class_fqn: None,
            signature: None,
            reference_intents: Vec::new(),
            relationships: Vec::new(),
            alias_module_path: None,
            original_export_name: None,
            default_export: None,
            is_test_context: false,
        };

        let rust_caller = ResolutionEntity {
            uuid: Uuid::new_v4(),
            kind: EntityKind::Function,
            name: "collect_rust_type_references".to_string(),
            fqn: "knot::pipeline::parser::languages::rust::collect_rust_type_references"
                .to_string(),
            file_path: "src/pipeline/parser/languages/rust.rs".to_string(),
            enclosing_class: None,
            enclosing_class_fqn: None,
            signature: None,
            reference_intents: vec![ReferenceIntent::Call {
                method: "find_nearest_entity_by_line".to_string(),
                receiver: None,
                line: 258,
                arg_count: None,
            }],
            relationships: Vec::new(),
            alias_module_path: None,
            original_export_name: None,
            default_export: None,
            is_test_context: false,
        };

        let orphans_caller = ResolutionEntity {
            uuid: Uuid::new_v4(),
            kind: EntityKind::Function,
            name: "collect_orphaned_references".to_string(),
            fqn: "knot::pipeline::parser::orphans::collect_orphaned_references".to_string(),
            file_path: "src/pipeline/parser/orphans.rs".to_string(),
            enclosing_class: None,
            enclosing_class_fqn: None,
            signature: None,
            reference_intents: vec![ReferenceIntent::Call {
                method: "find_nearest_entity_by_line".to_string(),
                receiver: None,
                line: 8,
                arg_count: None,
            }],
            relationships: Vec::new(),
            alias_module_path: None,
            original_export_name: None,
            default_export: None,
            is_test_context: false,
        };

        let orphans_fn_uuid = orphans_fn.uuid;
        let rust_fn_uuid = rust_fn.uuid;

        let mut entities = vec![orphans_fn, rust_fn, rust_caller, orphans_caller];
        resolve_reference_intents(&mut entities);

        let rust_caller_rels = &entities[2].relationships;
        assert_eq!(rust_caller_rels.len(), 1);
        assert_eq!(rust_caller_rels[0], (rust_fn_uuid, RelationshipType::Calls));

        let orphans_caller_rels = &entities[3].relationships;
        assert_eq!(orphans_caller_rels.len(), 1);
        assert_eq!(
            orphans_caller_rels[0],
            (orphans_fn_uuid, RelationshipType::Calls)
        );
    }

    #[test]
    fn test_resolve_self_method_same_class_name_collision() {
        let module_func = mock_resolution_entity_with_kind(
            "do_thing",
            "do_thing",
            None,
            "lora.py",
            EntityKind::Function,
        );
        let my_class = mock_resolution_entity_with_kind(
            "MyLoader",
            "MyLoader",
            None,
            "nodes.py",
            EntityKind::Class,
        );
        let class_method = mock_resolution_entity_with_kind(
            "do_thing",
            "MyLoader.do_thing",
            Some("MyLoader"),
            "nodes.py",
            EntityKind::Method,
        );

        let mut caller_method = mock_resolution_entity_with_kind(
            "caller",
            "MyLoader.caller",
            Some("MyLoader"),
            "nodes.py",
            EntityKind::Method,
        );
        caller_method.reference_intents = vec![ReferenceIntent::Call {
            method: "do_thing".to_string(),
            receiver: Some("self".to_string()),
            line: 20,
            arg_count: None,
        }];

        let module_uuid = module_func.uuid;
        let class_method_uuid = class_method.uuid;

        let mut entities = vec![module_func, my_class, class_method, caller_method];
        resolve_reference_intents(&mut entities);

        let caller = entities.iter().find(|e| e.name == "caller").unwrap();
        assert!(
            caller
                .relationships
                .contains(&(class_method_uuid, RelationshipType::Calls))
        );
        assert!(
            !caller
                .relationships
                .contains(&(module_uuid, RelationshipType::Calls))
        );
    }

    #[test]
    fn test_resolve_rust_qualified_call_with_homonyms() {
        let widget_a_new =
            mock_resolution_entity_at("new", "WidgetA::new", Some("WidgetA"), "test/sample.rs");
        let widget_b_new =
            mock_resolution_entity_at("new", "WidgetB::new", Some("WidgetB"), "test/sample.rs");

        let mut caller = mock_resolution_entity_with_kind(
            "exercise_qualified_calls",
            "exercise_qualified_calls",
            None,
            "test/sample.rs",
            EntityKind::Function,
        );
        caller.reference_intents = vec![ReferenceIntent::Call {
            method: "new".to_string(),
            receiver: Some("WidgetA".to_string()),
            line: 50,
            arg_count: None,
        }];

        let widget_a_new_uuid = widget_a_new.uuid;
        let widget_b_new_uuid = widget_b_new.uuid;

        let mut entities = vec![widget_a_new, widget_b_new, caller];
        resolve_reference_intents(&mut entities);

        let caller_entity = entities.last().unwrap();
        assert!(
            caller_entity
                .relationships
                .contains(&(widget_a_new_uuid, RelationshipType::Calls))
        );
        assert!(
            !caller_entity
                .relationships
                .contains(&(widget_b_new_uuid, RelationshipType::Calls))
        );
    }

    #[test]
    fn test_resolve_rust_self_method_call() {
        let foo_helper =
            mock_resolution_entity_at("helper", "Foo::helper", Some("Foo"), "test/sample.rs");

        let mut foo_bar =
            mock_resolution_entity_at("bar", "Foo::bar", Some("Foo"), "test/sample.rs");
        foo_bar.reference_intents = vec![ReferenceIntent::Call {
            method: "helper".to_string(),
            receiver: Some("Foo".to_string()),
            line: 30,
            arg_count: None,
        }];

        let foo_helper_uuid = foo_helper.uuid;

        let mut entities = vec![foo_helper, foo_bar];
        resolve_reference_intents(&mut entities);

        let foo_bar_entity = entities.last().unwrap();
        assert!(
            foo_bar_entity
                .relationships
                .contains(&(foo_helper_uuid, RelationshipType::Calls))
        );
    }

    #[test]
    fn test_resolve_fallback_uniqueness_guard() {
        let mut caller = mock_resolution_entity("main", "App.main", None);
        let callee1 =
            mock_resolution_entity_at("new", "Class1.new", Some("Class1"), "test/file1.java");
        let callee2 =
            mock_resolution_entity_at("new", "Class2.new", Some("Class2"), "test/file2.java");

        caller.reference_intents.push(ReferenceIntent::Call {
            method: "new".to_string(),
            receiver: None,
            line: 10,
            arg_count: None,
        });

        let mut entities = vec![caller, callee1, callee2];
        resolve_reference_intents(&mut entities);

        assert_eq!(entities[0].relationships.len(), 0);
    }

    #[test]
    fn test_resolve_fallback_arg_count_disambiguation() {
        let mut caller = mock_resolution_entity("main", "App.main", None);
        let mut callee1 =
            mock_resolution_entity_at("add", "Calc.add", Some("Calc"), "test/calc.java");
        callee1.signature = Some("add(int, int)".to_string()); // 2 args

        let mut callee2 =
            mock_resolution_entity_at("add", "List.add", Some("List"), "test/list.java");
        callee2.signature = Some("add(int)".to_string()); // 1 arg

        caller.reference_intents.push(ReferenceIntent::Call {
            method: "add".to_string(),
            receiver: None,
            line: 10,
            arg_count: Some(2),
        });

        let mut entities = vec![caller, callee1, callee2];
        resolve_reference_intents(&mut entities);

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

    // ============================================================
    // Spec: docs/specs/python_constructor_call_resolution.md
    // ClassName(...) must resolve to ClassName.__init__
    // ============================================================

    #[test]
    fn test_python_class_call_redirects_to_init() {
        let foo_class = mock_resolution_entity_with_kind(
            "Foo",
            "mod.Foo",
            None,
            "test/mod.py",
            EntityKind::Class,
        );
        let foo_init = mock_resolution_entity_with_kind(
            "__init__",
            "mod.Foo.__init__",
            Some("Foo"),
            "test/mod.py",
            EntityKind::Method,
        );

        let mut factory = mock_resolution_entity_with_kind(
            "factory",
            "mod.factory",
            None,
            "test/mod.py",
            EntityKind::Function,
        );
        factory.reference_intents.push(ReferenceIntent::Call {
            method: "Foo".to_string(),
            receiver: None,
            line: 10,
            arg_count: None,
        });

        let foo_class_uuid = foo_class.uuid;
        let foo_init_uuid = foo_init.uuid;

        let mut entities = vec![foo_class, foo_init, factory];
        resolve_reference_intents(&mut entities);

        let factory_entity = entities.iter().find(|e| e.name == "factory").unwrap();
        assert!(
            factory_entity
                .relationships
                .contains(&(foo_init_uuid, RelationshipType::Calls)),
            "factory should call Foo.__init__, not Foo"
        );
        assert!(
            !factory_entity
                .relationships
                .contains(&(foo_class_uuid, RelationshipType::Calls)),
            "factory must NOT call the Foo class entity itself"
        );
    }

    #[test]
    fn test_python_class_call_no_init_keeps_class() {
        let bar_class = mock_resolution_entity_with_kind(
            "Bar",
            "mod.Bar",
            None,
            "test/mod.py",
            EntityKind::Class,
        );

        let mut caller = mock_resolution_entity_with_kind(
            "caller",
            "mod.caller",
            None,
            "test/mod.py",
            EntityKind::Function,
        );
        caller.reference_intents.push(ReferenceIntent::Call {
            method: "Bar".to_string(),
            receiver: None,
            line: 5,
            arg_count: None,
        });

        let bar_class_uuid = bar_class.uuid;

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

        let caller_entity = entities.iter().find(|e| e.name == "caller").unwrap();
        assert_eq!(caller_entity.relationships.len(), 1);
        assert_eq!(
            caller_entity.relationships[0],
            (bar_class_uuid, RelationshipType::Calls),
            "Class without __init__ must keep the legacy behavior (call goes to class)"
        );
    }

    #[test]
    fn test_python_class_call_inherited_init() {
        let parent_class = mock_resolution_entity_with_kind(
            "Parent",
            "mod.Parent",
            None,
            "test/mod.py",
            EntityKind::Class,
        );
        let parent_init = mock_resolution_entity_with_kind(
            "__init__",
            "mod.Parent.__init__",
            Some("Parent"),
            "test/mod.py",
            EntityKind::Method,
        );
        let mut child_class = mock_resolution_entity_with_kind(
            "Child",
            "mod.Child",
            None,
            "test/mod.py",
            EntityKind::Class,
        );
        child_class
            .reference_intents
            .push(ReferenceIntent::Extends {
                parent: "Parent".to_string(),
                line: 1,
            });

        let mut caller = mock_resolution_entity_with_kind(
            "caller",
            "mod.caller",
            None,
            "test/mod.py",
            EntityKind::Function,
        );
        caller.reference_intents.push(ReferenceIntent::Call {
            method: "Child".to_string(),
            receiver: None,
            line: 20,
            arg_count: None,
        });

        let parent_init_uuid = parent_init.uuid;

        let mut entities = vec![parent_class, parent_init, child_class, caller];
        resolve_reference_intents(&mut entities);

        let caller_entity = entities.iter().find(|e| e.name == "caller").unwrap();
        assert!(
            caller_entity
                .relationships
                .contains(&(parent_init_uuid, RelationshipType::Calls)),
            "Child() with no own __init__ must redirect to Parent.__init__ via inheritance"
        );
    }

    #[test]
    fn test_function_named_like_class_not_redirected() {
        let foo_function = mock_resolution_entity_with_kind(
            "foo",
            "mod.foo",
            None,
            "test/mod.py",
            EntityKind::Function,
        );

        let mut caller = mock_resolution_entity_with_kind(
            "caller",
            "mod.caller",
            None,
            "test/mod.py",
            EntityKind::Function,
        );
        caller.reference_intents.push(ReferenceIntent::Call {
            method: "foo".to_string(),
            receiver: None,
            line: 5,
            arg_count: None,
        });

        let foo_function_uuid = foo_function.uuid;

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

        let caller_entity = entities.iter().find(|e| e.name == "caller").unwrap();
        assert_eq!(caller_entity.relationships.len(), 1);
        assert_eq!(
            caller_entity.relationships[0],
            (foo_function_uuid, RelationshipType::Calls),
            "A function must NOT be redirected — only Class/Struct kinds trigger the redirect"
        );
    }

    // Regression: bug reported on LlamaFactory's webui/chatter.py.
    // `engine.chatter.load_model(args)` was failing to resolve when there were
    // two homonyms in different modules:
    //   - `llamafactory.webui.chatter.WebChatModel.load_model` (method)
    //   - `llamafactory.model.loader.load_model` (top-level function)
    // The receiver chain `engine.chatter` contains the segment `chatter` which
    // uniquely identifies the WebChatModel method via its FQN module path.
    #[test]
    fn test_call_disambiguation_by_receiver_chain_segments() {
        let web_chat_method = mock_resolution_entity_with_kind(
            "load_model",
            "llamafactory.webui.chatter.WebChatModel.load_model",
            Some("WebChatModel"),
            "src/llamafactory/webui/chatter.py",
            EntityKind::Method,
        );
        let loader_fn = mock_resolution_entity_with_kind(
            "load_model",
            "llamafactory.model.loader.load_model",
            None,
            "src/llamafactory/model/loader.py",
            EntityKind::Function,
        );

        let mut caller = mock_resolution_entity_with_kind(
            "build_chat_tab",
            "llamafactory.webui.components.chatbot.build_chat_tab",
            None,
            "src/llamafactory/webui/components/chatbot.py",
            EntityKind::Function,
        );
        caller.reference_intents.push(ReferenceIntent::Call {
            method: "load_model".to_string(),
            receiver: Some("engine.chatter".to_string()),
            line: 42,
            arg_count: Some(1),
        });

        let web_chat_method_uuid = web_chat_method.uuid;
        let loader_fn_uuid = loader_fn.uuid;

        let mut entities = vec![web_chat_method, loader_fn, caller];
        resolve_reference_intents(&mut entities);

        let caller_entity = entities
            .iter()
            .find(|e| e.name == "build_chat_tab")
            .unwrap();
        assert!(
            caller_entity
                .relationships
                .contains(&(web_chat_method_uuid, RelationshipType::Calls)),
            "engine.chatter.load_model(...) must resolve to WebChatModel.load_model"
        );
        assert!(
            !caller_entity
                .relationships
                .iter()
                .any(|(u, _)| *u == loader_fn_uuid),
            "must NOT misattribute to the module-level loader.load_model"
        );
    }

    // Two candidates whose FQNs both contain a single receiver-chain segment
    // (`chatter`) result in a tie and the resolver must NOT pick either one.
    #[test]
    fn test_call_disambiguation_ties_are_dropped() {
        let candidate_a = mock_resolution_entity_with_kind(
            "load_model",
            "mod.chatter.WebChatModel.load_model",
            Some("WebChatModel"),
            "src/a.py",
            EntityKind::Method,
        );
        let candidate_b = mock_resolution_entity_with_kind(
            "load_model",
            "mod.chatter.Other.load_model",
            Some("Other"),
            "src/b.py",
            EntityKind::Method,
        );

        let mut caller = mock_resolution_entity_with_kind(
            "caller",
            "mod.caller",
            None,
            "src/caller.py",
            EntityKind::Function,
        );
        caller.reference_intents.push(ReferenceIntent::Call {
            method: "load_model".to_string(),
            receiver: Some("engine.chatter".to_string()),
            line: 1,
            arg_count: Some(1),
        });

        let candidate_a_uuid = candidate_a.uuid;
        let candidate_b_uuid = candidate_b.uuid;

        let mut entities = vec![candidate_a, candidate_b, caller];
        resolve_reference_intents(&mut entities);

        let caller_entity = entities.iter().find(|e| e.name == "caller").unwrap();
        assert!(
            !caller_entity
                .relationships
                .iter()
                .any(|(u, _)| *u == candidate_a_uuid || *u == candidate_b_uuid),
            "tie on receiver-chain score must drop the call rather than guess"
        );
    }

    // Regression: bug reported on LlamaFactory's webui/chatter.py.
    // `super().__init__()` inside `WebChatModel.__init__` was being resolved to
    // the same-file `WebChatModel.__init__` (the enclosing function itself) via
    // the name_to_uuids fallback, instead of `ChatModel.__init__`.
    #[test]
    fn test_python_super_init_resolves_to_parent_class() {
        let parent_class = mock_resolution_entity_with_kind(
            "ChatModel",
            "llamafactory.chat.ChatModel",
            None,
            "src/llamafactory/chat/chat_model.py",
            EntityKind::PythonClass,
        );
        let parent_init = mock_resolution_entity_with_kind(
            "__init__",
            "llamafactory.chat.ChatModel.__init__",
            Some("ChatModel"),
            "src/llamafactory/chat/chat_model.py",
            EntityKind::Method,
        );
        let mut child_class = mock_resolution_entity_with_kind(
            "WebChatModel",
            "llamafactory.webui.chatter.WebChatModel",
            None,
            "src/llamafactory/webui/chatter.py",
            EntityKind::PythonClass,
        );
        child_class
            .reference_intents
            .push(ReferenceIntent::Extends {
                parent: "ChatModel".to_string(),
                line: 81,
            });

        let mut child_init = mock_resolution_entity_with_kind(
            "__init__",
            "llamafactory.webui.chatter.WebChatModel.__init__",
            Some("WebChatModel"),
            "src/llamafactory/webui/chatter.py",
            EntityKind::Method,
        );
        child_init.reference_intents.push(ReferenceIntent::Call {
            method: "__init__".to_string(),
            receiver: Some("super()".to_string()),
            line: 87,
            arg_count: Some(0),
        });
        child_init.reference_intents.push(ReferenceIntent::Call {
            method: "__init__".to_string(),
            receiver: Some("super()".to_string()),
            line: 93,
            arg_count: Some(1),
        });

        let parent_init_uuid = parent_init.uuid;
        let child_init_uuid = child_init.uuid;

        let mut entities = vec![parent_class, parent_init, child_class, child_init];
        resolve_reference_intents(&mut entities);

        let child_init_entity = entities.iter().find(|e| e.uuid == child_init_uuid).unwrap();

        let calls_to_parent = child_init_entity
            .relationships
            .iter()
            .filter(|(uuid, rel)| *uuid == parent_init_uuid && *rel == RelationshipType::Calls)
            .count();
        assert_eq!(
            calls_to_parent, 1,
            "super().__init__() must resolve to ChatModel.__init__ (deduplicated across the two call sites)"
        );

        let self_calls = child_init_entity
            .relationships
            .iter()
            .filter(|(uuid, rel)| *uuid == child_init_uuid && *rel == RelationshipType::Calls)
            .count();
        assert_eq!(
            self_calls, 0,
            "super().__init__() must NOT be misattributed to the enclosing WebChatModel.__init__"
        );
    }

    // Java/Kotlin style: `super.method()` produces receiver `"super"`.
    #[test]
    fn test_java_super_call_resolves_to_parent_class() {
        let parent_class = mock_resolution_entity_with_kind(
            "Base",
            "com.example.Base",
            None,
            "src/Base.java",
            EntityKind::Class,
        );
        let parent_method = mock_resolution_entity_with_kind(
            "init",
            "com.example.Base.init",
            Some("Base"),
            "src/Base.java",
            EntityKind::Method,
        );
        let mut child_class = mock_resolution_entity_with_kind(
            "Child",
            "com.example.Child",
            None,
            "src/Child.java",
            EntityKind::Class,
        );
        child_class
            .reference_intents
            .push(ReferenceIntent::Extends {
                parent: "Base".to_string(),
                line: 1,
            });

        let mut child_method = mock_resolution_entity_with_kind(
            "init",
            "com.example.Child.init",
            Some("Child"),
            "src/Child.java",
            EntityKind::Method,
        );
        child_method.reference_intents.push(ReferenceIntent::Call {
            method: "init".to_string(),
            receiver: Some("super".to_string()),
            line: 5,
            arg_count: Some(0),
        });

        let parent_method_uuid = parent_method.uuid;
        let child_method_uuid = child_method.uuid;

        let mut entities = vec![parent_class, parent_method, child_class, child_method];
        resolve_reference_intents(&mut entities);

        let child_method_entity = entities
            .iter()
            .find(|e| e.uuid == child_method_uuid)
            .unwrap();
        assert!(
            child_method_entity
                .relationships
                .contains(&(parent_method_uuid, RelationshipType::Calls)),
            "super.init() must resolve to Base.init"
        );
    }

    #[test]
    fn test_python_super_init_no_parent_returns_no_edge() {
        // If the parent class isn't indexed, super().__init__() should drop the
        // call (return None) rather than fall back to the same-file __init__.
        let mut child_class = mock_resolution_entity_with_kind(
            "Orphan",
            "mod.Orphan",
            None,
            "test/mod.py",
            EntityKind::PythonClass,
        );
        child_class
            .reference_intents
            .push(ReferenceIntent::Extends {
                parent: "UnindexedExternal".to_string(),
                line: 1,
            });

        let mut child_init = mock_resolution_entity_with_kind(
            "__init__",
            "mod.Orphan.__init__",
            Some("Orphan"),
            "test/mod.py",
            EntityKind::Method,
        );
        child_init.reference_intents.push(ReferenceIntent::Call {
            method: "__init__".to_string(),
            receiver: Some("super()".to_string()),
            line: 5,
            arg_count: Some(0),
        });

        let child_init_uuid = child_init.uuid;

        let mut entities = vec![child_class, child_init];
        resolve_reference_intents(&mut entities);

        let child_init_entity = entities.iter().find(|e| e.uuid == child_init_uuid).unwrap();
        let self_calls = child_init_entity
            .relationships
            .iter()
            .filter(|(uuid, rel)| *uuid == child_init_uuid && *rel == RelationshipType::Calls)
            .count();
        assert_eq!(
            self_calls, 0,
            "Unresolved super() must not be misattributed to self"
        );
    }

    #[test]
    fn test_python_class_call_with_existing_init_no_duplicate() {
        let foo_class = mock_resolution_entity_with_kind(
            "Foo",
            "mod.Foo",
            None,
            "test/mod.py",
            EntityKind::Class,
        );
        let foo_init = mock_resolution_entity_with_kind(
            "__init__",
            "mod.Foo.__init__",
            Some("Foo"),
            "test/mod.py",
            EntityKind::Method,
        );

        let mut caller = mock_resolution_entity_with_kind(
            "caller",
            "mod.caller",
            None,
            "test/mod.py",
            EntityKind::Function,
        );
        caller.reference_intents.push(ReferenceIntent::Call {
            method: "Foo".to_string(),
            receiver: None,
            line: 10,
            arg_count: None,
        });
        caller.reference_intents.push(ReferenceIntent::Call {
            method: "__init__".to_string(),
            receiver: Some("Foo".to_string()),
            line: 10,
            arg_count: None,
        });

        let foo_init_uuid = foo_init.uuid;

        let mut entities = vec![foo_class, foo_init, caller];
        resolve_reference_intents(&mut entities);

        let caller_entity = entities.iter().find(|e| e.name == "caller").unwrap();
        let init_calls = caller_entity
            .relationships
            .iter()
            .filter(|(uuid, rel)| *uuid == foo_init_uuid && *rel == RelationshipType::Calls)
            .count();
        assert_eq!(
            init_calls, 1,
            "There must be exactly one Calls edge to Foo.__init__ (parser + redirect deduplicated)"
        );
    }

    #[test]
    fn test_type_receiver_prefers_exact_class_over_suffix_homonym() {
        let http_impl = mock_resolution_entity_at(
            "fetchItems",
            "com.a.impl.HttpCatalogProvider.fetchItems",
            Some("HttpCatalogProvider"),
            "src/impl/HttpCatalogProvider.java",
        );
        let iface = mock_resolution_entity_at(
            "fetchItems",
            "com.z.api.CatalogProvider.fetchItems",
            Some("CatalogProvider"),
            "src/api/CatalogProvider.java",
        );
        let mut caller = mock_resolution_entity_at(
            "build",
            "com.web.ReportService.build",
            Some("ReportService"),
            "src/web/ReportService.java",
        );
        caller.reference_intents.push(ReferenceIntent::Call {
            method: "fetchItems".to_string(),
            receiver: Some("CatalogProvider".to_string()),
            line: 10,
            arg_count: None,
        });

        let iface_uuid = iface.uuid;
        let mut entities = vec![http_impl, iface, caller];
        resolve_reference_intents(&mut entities);

        let caller_entity = entities.iter().find(|e| e.name == "build").unwrap();
        assert_eq!(caller_entity.relationships.len(), 1);
        assert_eq!(
            caller_entity.relationships[0],
            (iface_uuid, RelationshipType::Calls),
            "Expected call to resolve to CatalogProvider.fetchItems, not HttpCatalogProvider.fetchItems"
        );
    }

    #[test]
    fn test_type_receiver_resolves_inherited_interface_method() {
        let base_method = mock_resolution_entity_at(
            "fetchItems",
            "com.api.BaseProvider.fetchItems",
            Some("BaseProvider"),
            "src/api/BaseProvider.java",
        );
        let other_method = mock_resolution_entity_at(
            "fetchItems",
            "com.api.OtherProvider.fetchItems",
            Some("OtherProvider"),
            "src/api/OtherProvider.java",
        );
        let mut child_iface = mock_resolution_entity_with_kind(
            "CatalogProvider",
            "com.api.CatalogProvider",
            None,
            "src/api/CatalogProvider.java",
            EntityKind::Interface,
        );
        child_iface
            .reference_intents
            .push(ReferenceIntent::Extends {
                parent: "BaseProvider".to_string(),
                line: 3,
            });
        let mut caller = mock_resolution_entity_at(
            "build",
            "com.web.ReportService.build",
            Some("ReportService"),
            "src/web/ReportService.java",
        );
        caller.reference_intents.push(ReferenceIntent::Call {
            method: "fetchItems".to_string(),
            receiver: Some("CatalogProvider".to_string()),
            line: 10,
            arg_count: None,
        });

        let base_method_uuid = base_method.uuid;
        let mut entities = vec![base_method, other_method, child_iface, caller];
        resolve_reference_intents(&mut entities);

        let caller_entity = entities.iter().find(|e| e.name == "build").unwrap();
        assert_eq!(caller_entity.relationships.len(), 1);
        assert_eq!(
            caller_entity.relationships[0],
            (base_method_uuid, RelationshipType::Calls),
            "Expected call to resolve to BaseProvider.fetchItems via extends hierarchy"
        );
    }
}