grapha 0.2.1

Blazingly fast code intelligence CLI and MCP server for Swift and Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::Path;

use tree_sitter::Parser;

use grapha_core::graph::{
    Edge, EdgeKind, EdgeProvenance, Node, NodeKind, NodeRole, Span, Visibility,
};

use super::{ExtractionResult, LanguageExtractor};

thread_local! {
    static RUST_PARSER: RefCell<Parser> = RefCell::new({
        let mut p = Parser::new();
        p.set_language(&tree_sitter_rust::LANGUAGE.into()).expect("failed to load Rust grammar");
        p
    });
}

pub struct RustExtractor;

impl LanguageExtractor for RustExtractor {
    fn extract(&self, source: &[u8], file_path: &Path) -> anyhow::Result<ExtractionResult> {
        let tree = RUST_PARSER.with_borrow_mut(|parser| {
            parser
                .parse(source, None)
                .ok_or_else(|| anyhow::anyhow!("tree-sitter failed to parse source"))
        })?;

        let mut result = ExtractionResult::new();
        let file_str = file_path.to_string_lossy().to_string();

        walk_node(tree.root_node(), source, &file_str, &[], None, &mut result);

        Ok(result)
    }
}

fn edge_provenance(file: &str, node: tree_sitter::Node, symbol_id: &str) -> Vec<EdgeProvenance> {
    let start = node.start_position();
    let end = node.end_position();
    vec![EdgeProvenance {
        file: file.into(),
        span: Span {
            start: [start.row, start.column],
            end: [end.row, end.column],
        },
        symbol_id: symbol_id.to_string(),
    }]
}

/// Recursively walk a tree-sitter node, extracting symbols and edges.
///
/// `module_path` tracks the logical nesting (module names) for ID generation.
/// `parent_id` is the node ID of the enclosing symbol, used to emit Contains edges.
fn walk_node(
    node: tree_sitter::Node,
    source: &[u8],
    file: &str,
    module_path: &[String],
    parent_id: Option<&str>,
    result: &mut ExtractionResult,
) {
    match node.kind() {
        "function_item" | "function_signature_item" => {
            if let Some(graph_node) = extract_function(node, source, file, module_path) {
                if let Some(pid) = parent_id {
                    result.edges.push(Edge {
                        source: pid.to_string(),
                        target: graph_node.id.clone(),
                        kind: EdgeKind::Contains,
                        confidence: 1.0,
                        direction: None,
                        operation: None,
                        condition: None,
                        async_boundary: None,
                        provenance: edge_provenance(file, node, pid),
                    });
                }
                let node_id = graph_node.id.clone();
                result.nodes.push(graph_node);

                // Emit TypeRef edge for non-primitive return types
                if let Some(return_type_node) = node.child_by_field_name("return_type")
                    && let Ok(return_text) = return_type_node.utf8_text(source)
                {
                    // Strip leading "->" and whitespace
                    let type_name = return_text.trim_start_matches("->").trim();
                    if !type_name.is_empty() && !is_primitive(type_name) && type_name != "Self" {
                        let target_id = make_id(file, module_path, type_name);
                        result.edges.push(Edge {
                            source: node_id.clone(),
                            target: target_id,
                            kind: EdgeKind::TypeRef,
                            confidence: 0.85,
                            direction: None,
                            operation: None,
                            condition: None,
                            async_boundary: None,
                            provenance: edge_provenance(file, return_type_node, &node_id),
                        });
                    }
                }

                // Walk function body for nested items and call expressions
                if let Some(body) = node.child_by_field_name("body") {
                    walk_children(body, source, file, module_path, Some(&node_id), result);
                    extract_reads_and_writes(body, source, file, &node_id, result);
                    extract_calls(body, source, file, module_path, &node_id, result);
                }
            }
        }
        "const_item" | "static_item" => {
            if let Some(graph_node) = extract_constant(node, source, file, module_path) {
                if let Some(pid) = parent_id {
                    result.edges.push(Edge {
                        source: pid.to_string(),
                        target: graph_node.id.clone(),
                        kind: EdgeKind::Contains,
                        confidence: 1.0,
                        direction: None,
                        operation: None,
                        condition: None,
                        async_boundary: None,
                        provenance: edge_provenance(file, node, pid),
                    });
                }
                let node_id = graph_node.id.clone();
                result.nodes.push(graph_node);

                if let Some(type_node) = node.child_by_field_name("type")
                    && let Ok(type_name) = type_node.utf8_text(source)
                {
                    push_type_ref_edge(result, file, type_node, &node_id, module_path, type_name);
                }
            }
        }
        "type_item" => {
            if let Some(graph_node) = extract_type_alias(node, source, file, module_path) {
                if let Some(pid) = parent_id {
                    result.edges.push(Edge {
                        source: pid.to_string(),
                        target: graph_node.id.clone(),
                        kind: EdgeKind::Contains,
                        confidence: 1.0,
                        direction: None,
                        operation: None,
                        condition: None,
                        async_boundary: None,
                        provenance: edge_provenance(file, node, pid),
                    });
                }
                let node_id = graph_node.id.clone();
                result.nodes.push(graph_node);

                if let Some(type_node) = node.child_by_field_name("type")
                    && let Ok(type_name) = type_node.utf8_text(source)
                {
                    push_type_ref_edge(result, file, type_node, &node_id, module_path, type_name);
                }
            }
        }
        "struct_item" => {
            if let Some(graph_node) =
                extract_named_item(node, source, file, module_path, NodeKind::Struct)
            {
                if let Some(pid) = parent_id {
                    result.edges.push(Edge {
                        source: pid.to_string(),
                        target: graph_node.id.clone(),
                        kind: EdgeKind::Contains,
                        confidence: 1.0,
                        direction: None,
                        operation: None,
                        condition: None,
                        async_boundary: None,
                        provenance: edge_provenance(file, node, pid),
                    });
                }
                let node_id = graph_node.id.clone();
                let node_name = graph_node.name.clone();
                result.nodes.push(graph_node);

                // Extract fields from the struct body
                if let Some(body) = node.child_by_field_name("body") {
                    extract_struct_fields(
                        body,
                        source,
                        file,
                        module_path,
                        &node_id,
                        &node_name,
                        result,
                    );
                }
            }
        }
        "enum_item" => {
            if let Some(graph_node) =
                extract_named_item(node, source, file, module_path, NodeKind::Enum)
            {
                if let Some(pid) = parent_id {
                    result.edges.push(Edge {
                        source: pid.to_string(),
                        target: graph_node.id.clone(),
                        kind: EdgeKind::Contains,
                        confidence: 1.0,
                        direction: None,
                        operation: None,
                        condition: None,
                        async_boundary: None,
                        provenance: edge_provenance(file, node, pid),
                    });
                }
                let node_id = graph_node.id.clone();
                let node_name = graph_node.name.clone();
                result.nodes.push(graph_node);

                // Extract variants from the enum body
                if let Some(body) = node.child_by_field_name("body") {
                    extract_enum_variants(
                        body,
                        source,
                        file,
                        module_path,
                        &node_id,
                        &node_name,
                        result,
                    );
                }
            }
        }
        "trait_item" => {
            if let Some(graph_node) =
                extract_named_item(node, source, file, module_path, NodeKind::Trait)
            {
                if let Some(pid) = parent_id {
                    result.edges.push(Edge {
                        source: pid.to_string(),
                        target: graph_node.id.clone(),
                        kind: EdgeKind::Contains,
                        confidence: 1.0,
                        direction: None,
                        operation: None,
                        condition: None,
                        async_boundary: None,
                        provenance: edge_provenance(file, node, pid),
                    });
                }
                let node_id = graph_node.id.clone();
                result.nodes.push(graph_node);

                // Emit Inherits edges for supertrait bounds (e.g. `trait Child: Base`)
                if let Some(bounds) = node.child_by_field_name("bounds") {
                    let mut cursor = bounds.walk();
                    for child in bounds.named_children(&mut cursor) {
                        if child.kind() == "type_identifier"
                            && let Ok(bound_name) = child.utf8_text(source)
                        {
                            let target_id = make_id(file, module_path, bound_name);
                            result.edges.push(Edge {
                                source: node_id.clone(),
                                target: target_id,
                                kind: EdgeKind::Inherits,
                                confidence: 0.9,
                                direction: None,
                                operation: None,
                                condition: None,
                                async_boundary: None,
                                provenance: edge_provenance(file, child, &node_id),
                            });
                        }
                    }
                }

                if let Some(body) = node.child_by_field_name("body") {
                    walk_children(body, source, file, module_path, Some(&node_id), result);
                }
            }
        }
        "impl_item" => {
            if let Some(graph_node) = extract_impl_item(node, source, file, module_path) {
                if let Some(pid) = parent_id {
                    result.edges.push(Edge {
                        source: pid.to_string(),
                        target: graph_node.id.clone(),
                        kind: EdgeKind::Contains,
                        confidence: 1.0,
                        direction: None,
                        operation: None,
                        condition: None,
                        async_boundary: None,
                        provenance: edge_provenance(file, node, pid),
                    });
                }
                let node_id = graph_node.id.clone();

                // Emit Implements edge if this is `impl Trait for Type`
                // The source is the type being implemented, target is the trait
                if let Some(trait_node) = node.child_by_field_name("trait")
                    && let Ok(trait_name) = trait_node.utf8_text(source)
                {
                    let type_name = &graph_node.name;
                    let type_id = make_id(file, module_path, type_name);
                    let trait_id = make_id(file, module_path, trait_name);
                    result.edges.push(Edge {
                        source: type_id,
                        target: trait_id,
                        kind: EdgeKind::Implements,
                        confidence: 0.9,
                        direction: None,
                        operation: None,
                        condition: None,
                        async_boundary: None,
                        provenance: edge_provenance(file, trait_node, &node_id),
                    });
                }

                result.nodes.push(graph_node);

                if let Some(body) = node.child_by_field_name("body") {
                    walk_children(body, source, file, module_path, Some(&node_id), result);
                }
            }
        }
        "mod_item" => {
            if let Some(graph_node) =
                extract_named_item(node, source, file, module_path, NodeKind::Module)
            {
                if let Some(pid) = parent_id {
                    result.edges.push(Edge {
                        source: pid.to_string(),
                        target: graph_node.id.clone(),
                        kind: EdgeKind::Contains,
                        confidence: 1.0,
                        direction: None,
                        operation: None,
                        condition: None,
                        async_boundary: None,
                        provenance: edge_provenance(file, node, pid),
                    });
                }
                let mod_name = graph_node.name.clone();
                let node_id = graph_node.id.clone();
                result.nodes.push(graph_node);

                // Walk the module body with extended module_path
                if let Some(body) = node.child_by_field_name("body") {
                    let mut new_path = module_path.to_vec();
                    new_path.push(mod_name);
                    walk_children(body, source, file, &new_path, Some(&node_id), result);
                }
            }
        }
        "use_declaration" => {
            if let Ok(use_text) = node.utf8_text(source) {
                let raw = use_text
                    .trim_start_matches("use ")
                    .trim_end_matches(';')
                    .trim()
                    .to_string();

                let kind = if raw.starts_with("crate::")
                    || raw.starts_with("super::")
                    || raw.starts_with("self::")
                {
                    grapha_core::resolve::ImportKind::Relative
                } else if raw.ends_with("::*") {
                    grapha_core::resolve::ImportKind::Wildcard
                } else {
                    grapha_core::resolve::ImportKind::Named
                };

                // Extract symbols from grouped imports: use foo::{A, B}
                let (path, symbols) = if let Some(brace_start) = raw.find('{') {
                    let base = raw[..brace_start].trim_end_matches("::").to_string();
                    let inner = raw[brace_start + 1..].trim_end_matches('}').trim();
                    let syms = inner.split(',').map(|s| s.trim().to_string()).collect();
                    (base, syms)
                } else {
                    (raw.trim_end_matches("::*").to_string(), vec![])
                };

                result.imports.push(grapha_core::resolve::Import {
                    path,
                    symbols,
                    kind,
                });

                // Keep the Uses edge for backwards compatibility
                result.edges.push(Edge {
                    source: file.to_string(),
                    target: use_text.to_string(),
                    kind: EdgeKind::Uses,
                    confidence: 0.7,
                    direction: None,
                    operation: None,
                    condition: None,
                    async_boundary: None,
                    provenance: edge_provenance(file, node, file),
                });
            }
        }
        _ => {
            // For any other node kind, just walk its children
            walk_children(node, source, file, module_path, parent_id, result);
        }
    }
}

/// Walk all named children of a node.
fn walk_children(
    node: tree_sitter::Node,
    source: &[u8],
    file: &str,
    module_path: &[String],
    parent_id: Option<&str>,
    result: &mut ExtractionResult,
) {
    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        walk_node(child, source, file, module_path, parent_id, result);
    }
}

/// Build a node ID from file, module path, and name.
fn make_id(file: &str, module_path: &[String], name: &str) -> String {
    if module_path.is_empty() {
        format!("{}::{}", file, name)
    } else {
        format!("{}::{}::{}", file, module_path.join("::"), name)
    }
}

/// Extract the text of a named child field.
fn field_text<'a>(node: tree_sitter::Node<'a>, field: &str, source: &'a [u8]) -> Option<String> {
    node.child_by_field_name(field)
        .and_then(|n| n.utf8_text(source).ok())
        .map(|s| s.to_string())
}

/// Extract visibility from a node by checking for a `visibility_modifier` child.
fn extract_visibility(node: tree_sitter::Node, source: &[u8]) -> Visibility {
    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        if child.kind() == "visibility_modifier" {
            let text = child.utf8_text(source).unwrap_or("");
            if text.contains("pub(crate)") {
                return Visibility::Crate;
            } else if text.starts_with("pub") {
                return Visibility::Public;
            }
        }
    }
    Visibility::Private
}

/// Extract metadata (async, unsafe) from the `function_modifiers` named child.
///
/// tree-sitter-rust wraps these keywords in a `function_modifiers` node.
/// The keywords themselves are anonymous tokens with kinds `"async"` / `"unsafe"`.
fn extract_function_metadata(node: tree_sitter::Node, _source: &[u8]) -> HashMap<String, String> {
    let mut meta = HashMap::new();

    // Check direct children for function_modifiers node
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "function_modifiers" {
            let mut mod_cursor = child.walk();
            for modifier in child.children(&mut mod_cursor) {
                match modifier.kind() {
                    "async" => {
                        meta.insert("async".to_string(), "true".to_string());
                    }
                    "unsafe" => {
                        meta.insert("unsafe".to_string(), "true".to_string());
                    }
                    _ => {}
                }
            }
        }
    }

    meta
}

/// Extract a function_item or function_signature_item into a Node.
fn extract_function(
    node: tree_sitter::Node,
    source: &[u8],
    file: &str,
    module_path: &[String],
) -> Option<Node> {
    let name = field_text(node, "name", source)?;
    let id = make_id(file, module_path, &name);
    let visibility = extract_visibility(node, source);
    let metadata = extract_function_metadata(node, source);
    let start = node.start_position();
    let end = node.end_position();

    let role = detect_entry_point(node, source, &name, module_path);
    let signature = extract_signature(node, source);
    let doc_comment = extract_doc_comment(node, source);

    Some(Node {
        id,
        kind: NodeKind::Function,
        name,
        file: file.into(),
        span: Span {
            start: [start.row, start.column],
            end: [end.row, end.column],
        },
        visibility,
        metadata,
        role,
        signature,
        doc_comment,
        module: None,
        snippet: None,
    })
}

/// Detect if a function is an entry point.
///
/// Entry points are: `fn main()` at module level, functions with `#[test]`,
/// `#[tokio::main]`, or `pub fn` at crate root level (no parent impl/trait).
fn detect_entry_point(
    node: tree_sitter::Node,
    source: &[u8],
    name: &str,
    module_path: &[String],
) -> Option<NodeRole> {
    let attrs = collect_attributes(node, source);
    let is_module_level = node
        .parent()
        .map(|p| p.kind() == "source_file" || p.kind() == "declaration_list")
        .unwrap_or(false);
    let is_inside_impl_or_trait = node
        .parent()
        .and_then(|p| p.parent())
        .map(|gp| gp.kind() == "impl_item" || gp.kind() == "trait_item")
        .unwrap_or(false);

    // #[test] or #[tokio::main] attributes
    for attr in &attrs {
        if attr == "test" || attr == "tokio::test" || attr == "tokio::main" {
            return Some(NodeRole::EntryPoint);
        }
    }

    // fn main() at module level, not inside impl/trait
    if name == "main" && is_module_level && !is_inside_impl_or_trait {
        return Some(NodeRole::EntryPoint);
    }

    // pub fn at crate root level (module_path is empty, not inside impl/trait)
    let visibility = extract_visibility(node, source);
    if visibility == Visibility::Public
        && module_path.is_empty()
        && is_module_level
        && !is_inside_impl_or_trait
    {
        return Some(NodeRole::EntryPoint);
    }

    None
}

/// Collect attribute names from sibling `attribute_item` nodes before the function.
fn collect_attributes(node: tree_sitter::Node, source: &[u8]) -> Vec<String> {
    let mut attrs = Vec::new();
    let mut prev = node.prev_named_sibling();
    while let Some(sib) = prev {
        if sib.kind() == "attribute_item" {
            if let Ok(text) = sib.utf8_text(source) {
                // Strip #[ and ]
                let inner = text.trim_start_matches("#[").trim_end_matches(']').trim();
                // Take the attribute path (before any parentheses)
                let attr_name = inner.split('(').next().unwrap_or(inner).trim();
                attrs.push(attr_name.to_string());
            }
            prev = sib.prev_named_sibling();
        } else {
            break;
        }
    }
    attrs
}

/// Extract function signature (text up to opening `{`).
fn extract_signature(node: tree_sitter::Node, source: &[u8]) -> Option<String> {
    let text = node.utf8_text(source).ok()?;
    let sig = if let Some(brace_pos) = text.find('{') {
        text[..brace_pos].trim()
    } else {
        // For signature items (no body), use the whole text minus trailing semicolons
        text.trim().trim_end_matches(';').trim()
    };
    if sig.is_empty() {
        None
    } else {
        Some(sig.to_string())
    }
}

fn extract_decl_signature(node: tree_sitter::Node, source: &[u8]) -> Option<String> {
    node.utf8_text(source)
        .ok()
        .map(str::trim)
        .map(|text| text.trim_end_matches(';').trim())
        .filter(|text| !text.is_empty())
        .map(ToString::to_string)
}

/// Extract doc comments from previous sibling comment nodes.
fn extract_doc_comment(node: tree_sitter::Node, source: &[u8]) -> Option<String> {
    let mut comments = Vec::new();
    let mut prev = node.prev_named_sibling();
    // Skip over attribute_item siblings first
    while let Some(sib) = prev {
        if sib.kind() == "attribute_item" {
            prev = sib.prev_named_sibling();
            continue;
        }
        if sib.kind() == "line_comment" || sib.kind() == "block_comment" {
            if let Ok(text) = sib.utf8_text(source) {
                comments.push(text.to_string());
            }
            prev = sib.prev_named_sibling();
        } else {
            break;
        }
    }
    if comments.is_empty() {
        None
    } else {
        comments.reverse();
        Some(comments.join("\n"))
    }
}

/// Walk up from a call node to find an enclosing conditional, returning condition text.
/// Stops at `function_item` boundary.
fn find_enclosing_condition(node: tree_sitter::Node, source: &[u8]) -> Option<String> {
    let mut current = node.parent();
    while let Some(parent) = current {
        match parent.kind() {
            "function_item" | "function_signature_item" => return None,
            "if_expression" => {
                if let Some(cond) = parent.child_by_field_name("condition") {
                    return cond.utf8_text(source).ok().map(|s| s.trim().to_string());
                }
                return None;
            }
            "if_let_expression" => {
                // Grab "let PATTERN = EXPR" condition text
                if let Some(pat) = parent.child_by_field_name("pattern")
                    && let Some(val) = parent.child_by_field_name("value")
                {
                    let pat_text = pat.utf8_text(source).unwrap_or_default();
                    let val_text = val.utf8_text(source).unwrap_or_default();
                    return Some(format!("let {} = {}", pat_text.trim(), val_text.trim()));
                }
                return None;
            }
            "match_arm" => {
                if let Some(pat) = parent.child_by_field_name("pattern")
                    && let Ok(pat_text) = pat.utf8_text(source)
                {
                    return Some(format!("match {}", pat_text.trim()));
                }
                return None;
            }
            _ => {
                current = parent.parent();
            }
        }
    }
    None
}

/// Check if a call node is at an async boundary (await or inside spawn).
fn detect_async_boundary(node: tree_sitter::Node, source: &[u8]) -> Option<bool> {
    // Check if parent is await_expression
    if let Some(parent) = node.parent()
        && parent.kind() == "await_expression"
    {
        return Some(true);
    }
    // Check if inside a tokio::spawn or std::thread::spawn call
    let mut current = node.parent();
    while let Some(parent) = current {
        if parent.kind() == "function_item" || parent.kind() == "function_signature_item" {
            break;
        }
        if parent.kind() == "call_expression"
            && let Some(func) = parent.child_by_field_name("function")
            && let Ok(func_text) = func.utf8_text(source)
        {
            let trimmed = func_text.trim();
            if trimmed.contains("spawn") {
                return Some(true);
            }
        }
        current = parent.parent();
    }
    None
}

fn push_type_ref_edge(
    result: &mut ExtractionResult,
    file: &str,
    type_node: tree_sitter::Node,
    source_id: &str,
    module_path: &[String],
    raw_type_name: &str,
) {
    let type_name = raw_type_name.trim();
    if type_name.is_empty() || is_primitive(type_name) || type_name == "Self" {
        return;
    }

    result.edges.push(Edge {
        source: source_id.to_string(),
        target: make_id(file, module_path, type_name),
        kind: EdgeKind::TypeRef,
        confidence: 0.85,
        direction: None,
        operation: None,
        condition: None,
        async_boundary: None,
        provenance: edge_provenance(file, type_node, source_id),
    });
}

/// Extract a named symbol (struct, enum, trait, module) into a Node.
fn extract_named_item(
    node: tree_sitter::Node,
    source: &[u8],
    file: &str,
    module_path: &[String],
    kind: NodeKind,
) -> Option<Node> {
    let name = field_text(node, "name", source)?;
    let id = make_id(file, module_path, &name);
    let visibility = extract_visibility(node, source);
    let start = node.start_position();
    let end = node.end_position();

    Some(Node {
        id,
        kind,
        name,
        file: file.into(),
        span: Span {
            start: [start.row, start.column],
            end: [end.row, end.column],
        },
        visibility,
        metadata: HashMap::new(),
        role: None,
        signature: None,
        doc_comment: None,
        module: None,
        snippet: None,
    })
}

/// Extract an impl_item into a Node.
/// The node name is the type being implemented (e.g. `Foo`).
/// The ID uses `impl_{TypeName}` to avoid collisions with the type node.
fn extract_impl_item(
    node: tree_sitter::Node,
    source: &[u8],
    file: &str,
    module_path: &[String],
) -> Option<Node> {
    let type_name = field_text(node, "type", source)?;
    let impl_name = format!("impl_{}", type_name);
    let id = make_id(file, module_path, &impl_name);
    let start = node.start_position();
    let end = node.end_position();

    Some(Node {
        id,
        kind: NodeKind::Impl,
        name: type_name,
        file: file.into(),
        span: Span {
            start: [start.row, start.column],
            end: [end.row, end.column],
        },
        visibility: Visibility::Private,
        metadata: HashMap::new(),
        role: None,
        signature: None,
        doc_comment: None,
        module: None,
        snippet: None,
    })
}

fn extract_constant(
    node: tree_sitter::Node,
    source: &[u8],
    file: &str,
    module_path: &[String],
) -> Option<Node> {
    let name = field_text(node, "name", source)?;
    let id = make_id(file, module_path, &name);
    let visibility = extract_visibility(node, source);
    let start = node.start_position();
    let end = node.end_position();
    let mut metadata = HashMap::new();

    if node.kind() == "static_item" {
        metadata.insert("static".to_string(), "true".to_string());
        let mut cursor = node.walk();
        if node
            .children(&mut cursor)
            .any(|child| child.kind() == "mutable_specifier")
        {
            metadata.insert("mutable".to_string(), "true".to_string());
        }
    }

    Some(Node {
        id,
        kind: NodeKind::Constant,
        name,
        file: file.into(),
        span: Span {
            start: [start.row, start.column],
            end: [end.row, end.column],
        },
        visibility,
        metadata,
        role: None,
        signature: extract_decl_signature(node, source),
        doc_comment: extract_doc_comment(node, source),
        module: None,
        snippet: None,
    })
}

fn extract_type_alias(
    node: tree_sitter::Node,
    source: &[u8],
    file: &str,
    module_path: &[String],
) -> Option<Node> {
    let name = field_text(node, "name", source)?;
    let id = make_id(file, module_path, &name);
    let visibility = extract_visibility(node, source);
    let start = node.start_position();
    let end = node.end_position();

    Some(Node {
        id,
        kind: NodeKind::TypeAlias,
        name,
        file: file.into(),
        span: Span {
            start: [start.row, start.column],
            end: [end.row, end.column],
        },
        visibility,
        metadata: HashMap::new(),
        role: None,
        signature: extract_decl_signature(node, source),
        doc_comment: extract_doc_comment(node, source),
        module: None,
        snippet: None,
    })
}

/// Extract field_declaration children from a struct body.
fn extract_struct_fields(
    body: tree_sitter::Node,
    source: &[u8],
    file: &str,
    module_path: &[String],
    parent_id: &str,
    parent_name: &str,
    result: &mut ExtractionResult,
) {
    let mut cursor = body.walk();
    for child in body.named_children(&mut cursor) {
        if child.kind() == "field_declaration"
            && let Some(name) = field_text(child, "name", source)
        {
            let qualified = format!("{parent_name}.{name}");
            let id = make_id(file, module_path, &qualified);
            let visibility = extract_visibility(child, source);
            let start = child.start_position();
            let end = child.end_position();

            result.edges.push(Edge {
                source: parent_id.to_string(),
                target: id.clone(),
                kind: EdgeKind::Contains,
                confidence: 1.0,
                direction: None,
                operation: None,
                condition: None,
                async_boundary: None,
                provenance: edge_provenance(file, child, parent_id),
            });

            result.nodes.push(Node {
                id,
                kind: NodeKind::Field,
                name,
                file: file.into(),
                span: Span {
                    start: [start.row, start.column],
                    end: [end.row, end.column],
                },
                visibility,
                metadata: HashMap::new(),
                role: None,
                signature: None,
                doc_comment: None,
                module: None,
                snippet: None,
            });
        }
    }
}

/// Returns true if the type name is a Rust primitive.
fn is_primitive(name: &str) -> bool {
    matches!(
        name,
        "bool"
            | "i8"
            | "i16"
            | "i32"
            | "i64"
            | "i128"
            | "isize"
            | "u8"
            | "u16"
            | "u32"
            | "u64"
            | "u128"
            | "usize"
            | "f32"
            | "f64"
            | "char"
            | "str"
            | "()"
    )
}

/// Recursively scan a node tree for `call_expression` nodes, emitting Calls edges.
fn extract_calls(
    node: tree_sitter::Node,
    source: &[u8],
    file: &str,
    module_path: &[String],
    caller_id: &str,
    result: &mut ExtractionResult,
) {
    if node.kind() == "call_expression"
        && let Some(function_node) = node.child_by_field_name("function")
        && let Ok(fn_text) = function_node.utf8_text(source)
    {
        // Skip macro calls (names ending with '!')
        if !fn_text.ends_with('!') {
            let callee_name = fn_text.trim();
            if !callee_name.is_empty() {
                let target_id = if is_unqualified_call_target(callee_name) {
                    make_id(file, module_path, callee_name)
                } else {
                    callee_name.to_string()
                };
                let condition = find_enclosing_condition(node, source);
                let async_boundary = detect_async_boundary(node, source);
                result.edges.push(Edge {
                    source: caller_id.to_string(),
                    target: target_id,
                    kind: EdgeKind::Calls,
                    confidence: 0.8,
                    direction: None,
                    operation: None,
                    condition,
                    async_boundary,
                    provenance: edge_provenance(file, node, caller_id),
                });
            }
        }
    }

    // Recurse into all children
    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        extract_calls(child, source, file, module_path, caller_id, result);
    }
}

fn is_unqualified_call_target(target: &str) -> bool {
    !target.contains("::") && !target.contains('.')
}

fn extract_reads_and_writes(
    node: tree_sitter::Node,
    source: &[u8],
    file: &str,
    caller_id: &str,
    result: &mut ExtractionResult,
) {
    match node.kind() {
        "assignment_expression" | "compound_assignment_expr" => {
            if let Some(left) = node.child_by_field_name("left")
                && let Some(target) = extract_self_field_target(left, source)
            {
                let provenance = edge_provenance(file, left, caller_id);
                result.edges.push(Edge {
                    source: caller_id.to_string(),
                    target: target.clone(),
                    kind: EdgeKind::Writes,
                    confidence: 0.8,
                    direction: Some(grapha_core::graph::FlowDirection::Write),
                    operation: None,
                    condition: find_enclosing_condition(node, source),
                    async_boundary: detect_async_boundary(node, source),
                    provenance: provenance.clone(),
                });
                if node.kind() == "compound_assignment_expr" {
                    result.edges.push(Edge {
                        source: caller_id.to_string(),
                        target,
                        kind: EdgeKind::Reads,
                        confidence: 0.75,
                        direction: Some(grapha_core::graph::FlowDirection::Read),
                        operation: None,
                        condition: find_enclosing_condition(node, source),
                        async_boundary: detect_async_boundary(node, source),
                        provenance,
                    });
                }
            }

            if let Some(right) = node.child_by_field_name("right") {
                extract_reads_and_writes(right, source, file, caller_id, result);
            }
        }
        "field_expression" => {
            if should_emit_field_read(node)
                && let Some(target) = extract_self_field_target(node, source)
            {
                result.edges.push(Edge {
                    source: caller_id.to_string(),
                    target,
                    kind: EdgeKind::Reads,
                    confidence: 0.75,
                    direction: Some(grapha_core::graph::FlowDirection::Read),
                    operation: None,
                    condition: find_enclosing_condition(node, source),
                    async_boundary: detect_async_boundary(node, source),
                    provenance: edge_provenance(file, node, caller_id),
                });
            }
        }
        "identifier" | "scoped_identifier" => {
            if should_emit_constant_read(node, source) {
                let target = node
                    .utf8_text(source)
                    .unwrap_or_default()
                    .trim()
                    .to_string();
                result.edges.push(Edge {
                    source: caller_id.to_string(),
                    target,
                    kind: EdgeKind::Reads,
                    confidence: 0.7,
                    direction: Some(grapha_core::graph::FlowDirection::Read),
                    operation: None,
                    condition: find_enclosing_condition(node, source),
                    async_boundary: detect_async_boundary(node, source),
                    provenance: edge_provenance(file, node, caller_id),
                });
            }
        }
        _ => {
            let mut cursor = node.walk();
            for child in node.named_children(&mut cursor) {
                extract_reads_and_writes(child, source, file, caller_id, result);
            }
        }
    }
}

fn extract_self_field_target(node: tree_sitter::Node, source: &[u8]) -> Option<String> {
    if node.kind() != "field_expression" {
        return None;
    }

    let value = node.child_by_field_name("value")?;
    let field = node.child_by_field_name("field")?;
    let receiver = value.utf8_text(source).ok()?.trim();
    let field_name = field.utf8_text(source).ok()?.trim();
    if receiver == "self" && !field_name.is_empty() {
        Some(format!("{receiver}.{field_name}"))
    } else {
        None
    }
}

fn should_emit_field_read(node: tree_sitter::Node) -> bool {
    let Some(parent) = node.parent() else {
        return true;
    };

    if parent.kind() == "call_expression" && parent.child_by_field_name("function") == Some(node) {
        return false;
    }

    if matches!(
        parent.kind(),
        "assignment_expression" | "compound_assignment_expr"
    ) && parent.child_by_field_name("left") == Some(node)
    {
        return false;
    }

    true
}

fn should_emit_constant_read(node: tree_sitter::Node, source: &[u8]) -> bool {
    let Ok(text) = node.utf8_text(source) else {
        return false;
    };
    if !is_constant_like(text.trim()) {
        return false;
    }

    let Some(parent) = node.parent() else {
        return true;
    };

    if parent.child_by_field_name("name") == Some(node)
        || parent.child_by_field_name("field") == Some(node)
        || parent.child_by_field_name("alias") == Some(node)
        || (parent.kind() == "call_expression"
            && parent.child_by_field_name("function") == Some(node))
    {
        return false;
    }

    true
}

fn is_constant_like(text: &str) -> bool {
    let candidate = text
        .rsplit("::")
        .next()
        .unwrap_or(text)
        .trim_start_matches("r#");
    let mut has_uppercase = false;
    for ch in candidate.chars() {
        if ch.is_ascii_lowercase() {
            return false;
        }
        if ch.is_ascii_uppercase() {
            has_uppercase = true;
        }
        if !(ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_') {
            return false;
        }
    }
    has_uppercase
}

/// Extract enum_variant children from an enum body.
fn extract_enum_variants(
    body: tree_sitter::Node,
    source: &[u8],
    file: &str,
    module_path: &[String],
    parent_id: &str,
    parent_name: &str,
    result: &mut ExtractionResult,
) {
    let mut cursor = body.walk();
    for child in body.named_children(&mut cursor) {
        if child.kind() == "enum_variant"
            && let Some(name) = field_text(child, "name", source)
        {
            let qualified = format!("{parent_name}.{name}");
            let id = make_id(file, module_path, &qualified);
            let start = child.start_position();
            let end = child.end_position();

            result.edges.push(Edge {
                source: parent_id.to_string(),
                target: id.clone(),
                kind: EdgeKind::Contains,
                confidence: 1.0,
                direction: None,
                operation: None,
                condition: None,
                async_boundary: None,
                provenance: edge_provenance(file, child, parent_id),
            });

            result.nodes.push(Node {
                id,
                kind: NodeKind::Variant,
                name,
                file: file.into(),
                span: Span {
                    start: [start.row, start.column],
                    end: [end.row, end.column],
                },
                visibility: Visibility::Public,
                metadata: HashMap::new(),
                role: None,
                signature: None,
                doc_comment: None,
                module: None,
                snippet: None,
            });
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use grapha_core::graph::{EdgeKind, NodeKind, Visibility};

    fn extract(source: &str) -> ExtractionResult {
        let extractor = RustExtractor;
        extractor
            .extract(source.as_bytes(), Path::new("test.rs"))
            .unwrap()
    }

    fn find_node<'a>(result: &'a ExtractionResult, name: &str) -> &'a grapha_core::graph::Node {
        result
            .nodes
            .iter()
            .find(|n| n.name == name)
            .unwrap_or_else(|| panic!("node '{}' not found", name))
    }

    fn has_edge(result: &ExtractionResult, source: &str, target: &str, kind: EdgeKind) -> bool {
        result
            .edges
            .iter()
            .any(|e| e.source == source && e.target == target && e.kind == kind)
    }

    #[test]
    fn extracts_function() {
        let result = extract("pub fn greet(name: &str) -> String { format!(\"hi {}\", name) }");
        let node = find_node(&result, "greet");
        assert_eq!(node.kind, NodeKind::Function);
        assert_eq!(node.visibility, Visibility::Public);
    }

    #[test]
    fn extracts_async_unsafe_metadata() {
        let result = extract("pub async fn fetch() {} unsafe fn danger() {}");
        let fetch = find_node(&result, "fetch");
        assert_eq!(
            fetch.metadata.get("async").map(|s| s.as_str()),
            Some("true")
        );
        let danger = find_node(&result, "danger");
        assert_eq!(
            danger.metadata.get("unsafe").map(|s| s.as_str()),
            Some("true")
        );
    }

    #[test]
    fn extracts_struct_with_fields() {
        let result = extract(
            r#"
            pub struct Config {
                pub debug: bool,
                name: String,
            }
            "#,
        );
        let config = find_node(&result, "Config");
        assert_eq!(config.kind, NodeKind::Struct);
        assert_eq!(config.visibility, Visibility::Public);

        let debug = find_node(&result, "debug");
        assert_eq!(debug.kind, NodeKind::Field);
        assert_eq!(debug.visibility, Visibility::Public);

        let name = find_node(&result, "name");
        assert_eq!(name.kind, NodeKind::Field);
        assert_eq!(name.visibility, Visibility::Private);

        assert!(has_edge(&result, &config.id, &debug.id, EdgeKind::Contains));
        assert!(has_edge(&result, &config.id, &name.id, EdgeKind::Contains));
    }

    #[test]
    fn extracts_enum_with_variants() {
        let result = extract(
            r#"
            pub enum Color {
                Red,
                Green,
                Blue,
            }
            "#,
        );
        let color = find_node(&result, "Color");
        assert_eq!(color.kind, NodeKind::Enum);

        let red = find_node(&result, "Red");
        assert_eq!(red.kind, NodeKind::Variant);

        assert!(has_edge(&result, &color.id, &red.id, EdgeKind::Contains));
    }

    #[test]
    fn extracts_trait() {
        let result = extract(
            r#"
            pub trait Drawable {
                fn draw(&self);
            }
            "#,
        );
        let drawable = find_node(&result, "Drawable");
        assert_eq!(drawable.kind, NodeKind::Trait);
        assert_eq!(drawable.visibility, Visibility::Public);

        let draw = find_node(&result, "draw");
        assert_eq!(draw.kind, NodeKind::Function);

        assert!(has_edge(
            &result,
            &drawable.id,
            &draw.id,
            EdgeKind::Contains
        ));
    }

    #[test]
    fn extracts_impl_block() {
        let result = extract(
            r#"
            struct Foo;
            impl Foo {
                pub fn new() -> Self { Foo }
            }
            "#,
        );
        let impl_node = result
            .nodes
            .iter()
            .find(|n| n.kind == NodeKind::Impl)
            .expect("impl node not found");
        assert_eq!(impl_node.name, "Foo");

        let new_fn = find_node(&result, "new");
        assert!(has_edge(
            &result,
            &impl_node.id,
            &new_fn.id,
            EdgeKind::Contains
        ));
    }

    #[test]
    fn extracts_module() {
        let result = extract(
            r#"
            pub mod utils {
                pub fn helper() {}
            }
            "#,
        );
        let utils = find_node(&result, "utils");
        assert_eq!(utils.kind, NodeKind::Module);
        assert_eq!(utils.visibility, Visibility::Public);

        let helper = find_node(&result, "helper");
        assert!(has_edge(&result, &utils.id, &helper.id, EdgeKind::Contains));
    }

    #[test]
    fn extracts_pub_crate_visibility() {
        let result = extract("pub(crate) fn internal() {}");
        let node = find_node(&result, "internal");
        assert_eq!(node.visibility, Visibility::Crate);
    }

    #[test]
    fn extracts_calls_edges() {
        let result = extract(
            r#"
            fn helper() {}
            fn main() {
                helper();
            }
            "#,
        );
        assert!(has_edge(
            &result,
            "test.rs::main",
            "test.rs::helper",
            EdgeKind::Calls,
        ));
    }

    #[test]
    fn extracts_use_edges() {
        let result = extract("use std::collections::HashMap;");
        assert!(result.edges.iter().any(|e| e.kind == EdgeKind::Uses));
    }

    #[test]
    fn extracts_implements_edge() {
        let result = extract(
            r#"
            trait Drawable { fn draw(&self); }
            struct Circle;
            impl Drawable for Circle {
                fn draw(&self) {}
            }
            "#,
        );
        assert!(result.edges.iter().any(|e| e.kind == EdgeKind::Implements));
    }

    #[test]
    fn extracts_type_ref_edges() {
        let result = extract(
            r#"
            struct Config { debug: bool }
            fn make_config() -> Config {
                Config { debug: true }
            }
            "#,
        );
        assert!(result.edges.iter().any(|e| e.kind == EdgeKind::TypeRef));
    }

    #[test]
    fn extracts_constants_and_type_aliases() {
        let result = extract(
            r#"
            pub const STORE_SCHEMA_VERSION: &str = "6";
            static mut GLOBAL_COUNTER: usize = 0;
            pub type SchemaVersion = String;
            "#,
        );

        let const_node = find_node(&result, "STORE_SCHEMA_VERSION");
        assert_eq!(const_node.kind, NodeKind::Constant);
        assert_eq!(const_node.visibility, Visibility::Public);

        let static_node = find_node(&result, "GLOBAL_COUNTER");
        assert_eq!(static_node.kind, NodeKind::Constant);
        assert_eq!(
            static_node.metadata.get("static").map(|s| s.as_str()),
            Some("true")
        );
        assert_eq!(
            static_node.metadata.get("mutable").map(|s| s.as_str()),
            Some("true")
        );

        let alias_node = find_node(&result, "SchemaVersion");
        assert_eq!(alias_node.kind, NodeKind::TypeAlias);
        assert!(
            result
                .edges
                .iter()
                .any(|edge| { edge.source == alias_node.id && edge.kind == EdgeKind::TypeRef })
        );
    }

    #[test]
    fn extracts_self_field_reads_writes_and_constant_reads() {
        let result = extract(
            r#"
            const STORE_SCHEMA_VERSION: &str = "6";

            struct SqliteStore {
                path: String,
            }

            impl SqliteStore {
                fn open(&self) {
                    let _ = &self.path;
                    let _ = STORE_SCHEMA_VERSION;
                }

                fn set_path(&mut self, next: String) {
                    self.path = next;
                }
            }
            "#,
        );

        assert!(result.edges.iter().any(|edge| {
            edge.source == "test.rs::open"
                && edge.target == "self.path"
                && edge.kind == EdgeKind::Reads
        }));
        assert!(result.edges.iter().any(|edge| {
            edge.source == "test.rs::open"
                && edge.target == "STORE_SCHEMA_VERSION"
                && edge.kind == EdgeKind::Reads
        }));
        assert!(result.edges.iter().any(|edge| {
            edge.source == "test.rs::set_path"
                && edge.target == "self.path"
                && edge.kind == EdgeKind::Writes
        }));
    }

    #[test]
    fn extracts_structured_imports() {
        let result = extract("use std::collections::HashMap;");
        assert_eq!(result.imports.len(), 1);
        assert_eq!(result.imports[0].path, "std::collections::HashMap");
        assert_eq!(
            result.imports[0].kind,
            grapha_core::resolve::ImportKind::Named
        );
    }

    #[test]
    fn extracts_relative_imports() {
        let result = extract("use crate::graph::Node;");
        assert_eq!(result.imports.len(), 1);
        assert_eq!(
            result.imports[0].kind,
            grapha_core::resolve::ImportKind::Relative
        );
    }

    #[test]
    fn extracts_glob_imports() {
        let result = extract("use std::collections::*;");
        assert_eq!(result.imports.len(), 1);
        assert_eq!(
            result.imports[0].kind,
            grapha_core::resolve::ImportKind::Wildcard
        );
    }

    #[test]
    fn extracts_inherits_edge_for_supertraits() {
        let result = extract(
            r#"
            trait Base {}
            trait Child: Base {}
            "#,
        );
        assert!(has_edge(
            &result,
            "test.rs::Child",
            "test.rs::Base",
            EdgeKind::Inherits,
        ));
    }

    #[test]
    fn extracts_condition_on_call_inside_if() {
        let result = extract(
            r#"
            fn check() -> bool { true }
            fn run() {
                if check() {
                    helper();
                }
            }
            fn helper() {}
            "#,
        );
        let cond_edge = result
            .edges
            .iter()
            .find(|e| e.kind == EdgeKind::Calls && e.target.contains("helper"))
            .expect("should find Calls edge to helper");
        assert!(
            cond_edge.condition.is_some(),
            "condition should be set on call inside if"
        );
        assert!(
            !cond_edge.provenance.is_empty(),
            "call edges should carry provenance"
        );
        assert_eq!(cond_edge.provenance[0].symbol_id, "test.rs::run");
    }

    #[test]
    fn detects_main_as_entry_point() {
        let result = extract(
            r#"
            fn main() {
                println!("hello");
            }
            "#,
        );
        let main_node = find_node(&result, "main");
        assert_eq!(
            main_node.role,
            Some(grapha_core::graph::NodeRole::EntryPoint),
            "fn main() should be detected as EntryPoint"
        );
    }

    #[test]
    fn detects_test_as_entry_point() {
        let result = extract(
            r#"
            #[test]
            fn my_test() {
                assert!(true);
            }
            "#,
        );
        let test_node = find_node(&result, "my_test");
        assert_eq!(
            test_node.role,
            Some(grapha_core::graph::NodeRole::EntryPoint),
            "#[test] fn should be detected as EntryPoint"
        );
    }

    #[test]
    fn detects_pub_fn_at_root_as_entry_point() {
        let result = extract("pub fn api_handler() {}");
        let node = find_node(&result, "api_handler");
        assert_eq!(
            node.role,
            Some(grapha_core::graph::NodeRole::EntryPoint),
            "pub fn at root should be EntryPoint"
        );
    }

    #[test]
    fn private_fn_at_root_is_not_entry_point() {
        let result = extract("fn helper() {}");
        let node = find_node(&result, "helper");
        assert!(
            node.role.is_none() || node.role == Some(grapha_core::graph::NodeRole::Internal),
            "private fn at root should not be EntryPoint (unless it's main)"
        );
    }

    #[test]
    fn extracts_function_signature() {
        let result = extract("pub fn greet(name: &str) -> String { format!(\"hi {}\", name) }");
        let node = find_node(&result, "greet");
        assert!(node.signature.is_some(), "signature should be extracted");
        let sig = node.signature.as_ref().unwrap();
        assert!(sig.contains("fn greet"), "signature should contain fn name");
        assert!(
            sig.contains("-> String"),
            "signature should contain return type"
        );
    }

    #[test]
    fn extracts_doc_comment() {
        let result = extract(
            r#"
            /// This is a doc comment
            /// with two lines
            fn documented() {}
            "#,
        );
        let node = find_node(&result, "documented");
        assert!(
            node.doc_comment.is_some(),
            "doc_comment should be extracted"
        );
        let doc = node.doc_comment.as_ref().unwrap();
        assert!(doc.contains("doc comment"), "should contain comment text");
    }

    #[test]
    fn detects_async_boundary_on_await() {
        let result = extract(
            r#"
            async fn caller() {
                fetch().await;
            }
            async fn fetch() {}
            "#,
        );
        let await_edge = result
            .edges
            .iter()
            .find(|e| e.kind == EdgeKind::Calls && e.target.contains("fetch"));
        // Note: tree-sitter-rust may or may not produce an await_expression parent
        // depending on version. We verify the edge exists at minimum.
        assert!(await_edge.is_some(), "should find Calls edge to fetch");
    }

    #[test]
    fn extracts_condition_on_match_arm() {
        let result = extract(
            r#"
            fn process(x: i32) {
                match x {
                    0 => handle_zero(),
                    _ => handle_other(),
                }
            }
            fn handle_zero() {}
            fn handle_other() {}
            "#,
        );
        let match_edges: Vec<_> = result
            .edges
            .iter()
            .filter(|e| e.kind == EdgeKind::Calls && e.condition.is_some())
            .collect();
        // At least one call inside a match should have a condition
        assert!(
            !match_edges.is_empty(),
            "calls inside match arms should have conditions"
        );
        let cond = match_edges[0].condition.as_ref().unwrap();
        assert!(
            cond.starts_with("match"),
            "match arm condition should start with 'match'"
        );
    }
}