coraline 0.8.0

Coraline: semantic code knowledge graph for faster AI-assisted development.
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
#![forbid(unsafe_code)]

//! Graph query tools for exploring the code graph

use std::path::PathBuf;

use serde_json::{Value, json};

use crate::db;
use crate::graph;
use crate::types::{EdgeKind, NodeKind, TraversalDirection, TraversalOptions};

use super::{Tool, ToolError, ToolResult};

/// Tool for searching nodes by name or pattern
pub struct SearchTool {
    project_root: PathBuf,
}

impl SearchTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for SearchTool {
    fn name(&self) -> &'static str {
        "coraline_search"
    }

    fn description(&self) -> &'static str {
        "Search for code symbols by name or pattern across the indexed codebase"
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Search query (symbol name or pattern)"
                },
                "kind": {
                    "type": "string",
                    "description": "Node kind filter (function, class, method, etc.)",
                    "enum": ["function", "method", "class", "struct", "interface", "trait", "module"]
                },
                "file": {
                    "type": "string",
                    "description": "Restrict results to symbols in this file path"
                },
                "limit": {
                    "type": "number",
                    "description": "Maximum number of results to return",
                    "default": 10
                }
            },
            "required": ["query"]
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let query = params
            .get("query")
            .and_then(Value::as_str)
            .ok_or_else(|| ToolError::invalid_params("query must be a string"))?;

        let kind = params
            .get("kind")
            .and_then(Value::as_str)
            .and_then(|s| match s {
                "function" => Some(NodeKind::Function),
                "method" => Some(NodeKind::Method),
                "class" => Some(NodeKind::Class),
                "struct" => Some(NodeKind::Struct),
                "interface" => Some(NodeKind::Interface),
                "trait" => Some(NodeKind::Trait),
                "module" => Some(NodeKind::Module),
                _ => None,
            });

        let limit = params
            .get("limit")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok())
            .unwrap_or(10);

        let file_filter = params.get("file").and_then(Value::as_str);

        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to open database: {e}")))?;

        // Fetch extra results when file-filtering so we still hit the requested limit.
        let fetch_limit = if file_filter.is_some() {
            limit * 5
        } else {
            limit
        };
        let results = db::search_nodes(&conn, query, kind, fetch_limit)
            .map_err(|e| ToolError::internal_error(format!("Search failed: {e}")))?;

        let abs_file = file_filter.map(|f| {
            if std::path::Path::new(f).is_absolute() {
                f.to_string()
            } else {
                self.project_root.join(f).to_string_lossy().to_string()
            }
        });

        let results_json: Vec<Value> = results
            .into_iter()
            .filter(|r| {
                abs_file.as_ref().is_none_or(|af| {
                    r.node.file_path == *af || file_filter.is_some_and(|f| r.node.file_path == f)
                })
            })
            .take(limit)
            .map(|r| {
                json!({
                    "node": {
                        "id": r.node.id,
                        "kind": r.node.kind,
                        "name": r.node.name,
                        "qualified_name": r.node.qualified_name,
                        "file_path": r.node.file_path,
                        "start_line": r.node.start_line,
                        "end_line": r.node.end_line,
                        "language": r.node.language,
                        "signature": r.node.signature,
                    },
                    "score": r.score,
                })
            })
            .collect();

        Ok(json!({
            "results": results_json,
            "count": results_json.len(),
        }))
    }
}

/// Tool for finding callers of a function/method
pub struct CallersTool {
    project_root: PathBuf,
}

impl CallersTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for CallersTool {
    fn name(&self) -> &'static str {
        "coraline_callers"
    }

    fn description(&self) -> &'static str {
        "Find all functions/methods that call a given symbol"
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "node_id": {
                    "type": "string",
                    "description": "ID of the node to find callers for"
                },
                "name": {
                    "type": "string",
                    "description": "Symbol name (alternative to node_id). If ambiguous, add 'file'."
                },
                "file": {
                    "type": "string",
                    "description": "File path to disambiguate when using 'name'"
                },
                "limit": {
                    "type": "number",
                    "description": "Maximum number of callers to return",
                    "default": 20
                }
            }
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to open database: {e}")))?;

        let node_id = resolve_node_id(&conn, &self.project_root, &params, "node_id")?;

        let limit = params
            .get("limit")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok())
            .unwrap_or(20);

        // Get edges where this node is the target and edge kind is "calls"
        let edges = db::get_edges_by_target(&conn, &node_id, Some(EdgeKind::Calls), limit)
            .map_err(|e| ToolError::internal_error(format!("Failed to get edges: {e}")))?;

        let mut callers = Vec::new();
        for edge in edges {
            if let Some(caller) = db::get_node_by_id(&conn, &edge.source)
                .map_err(|e| ToolError::internal_error(format!("Failed to get node: {e}")))?
            {
                callers.push(json!({
                    "id": caller.id,
                    "kind": caller.kind,
                    "name": caller.name,
                    "qualified_name": caller.qualified_name,
                    "file_path": caller.file_path,
                    "start_line": caller.start_line,
                    "line": edge.line,
                }));
            }
        }

        Ok(json!({
            "callers": callers,
            "count": callers.len(),
        }))
    }
}

/// Tool for finding callees (what a function calls)
pub struct CalleesTool {
    project_root: PathBuf,
}

impl CalleesTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for CalleesTool {
    fn name(&self) -> &'static str {
        "coraline_callees"
    }

    fn description(&self) -> &'static str {
        "Find all functions/methods that a given symbol calls"
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "node_id": {
                    "type": "string",
                    "description": "ID of the node to find callees for"
                },
                "name": {
                    "type": "string",
                    "description": "Symbol name (alternative to node_id). If ambiguous, add 'file'."
                },
                "file": {
                    "type": "string",
                    "description": "File path to disambiguate when using 'name'"
                },
                "limit": {
                    "type": "number",
                    "description": "Maximum number of callees to return",
                    "default": 20
                }
            }
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to open database: {e}")))?;

        let node_id = resolve_node_id(&conn, &self.project_root, &params, "node_id")?;

        let limit = params
            .get("limit")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok())
            .unwrap_or(20);

        // Get edges where this node is the source and edge kind is "calls"
        let edges = db::get_edges_by_source(&conn, &node_id, Some(EdgeKind::Calls), limit)
            .map_err(|e| ToolError::internal_error(format!("Failed to get edges: {e}")))?;

        let mut callees = Vec::new();
        for edge in edges {
            if let Some(callee) = db::get_node_by_id(&conn, &edge.target)
                .map_err(|e| ToolError::internal_error(format!("Failed to get node: {e}")))?
            {
                callees.push(json!({
                    "id": callee.id,
                    "kind": callee.kind,
                    "name": callee.name,
                    "qualified_name": callee.qualified_name,
                    "file_path": callee.file_path,
                    "start_line": callee.start_line,
                    "line": edge.line,
                }));
            }
        }

        Ok(json!({
            "callees": callees,
            "count": callees.len(),
        }))
    }
}

/// Tool for impact radius analysis
pub struct ImpactTool {
    project_root: PathBuf,
}

impl ImpactTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for ImpactTool {
    fn name(&self) -> &'static str {
        "coraline_impact"
    }

    fn description(&self) -> &'static str {
        "Analyze the impact radius of changing a symbol - what might be affected"
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "node_id": {
                    "type": "string",
                    "description": "ID of the node to analyze impact for"
                },
                "name": {
                    "type": "string",
                    "description": "Symbol name (alternative to node_id). If ambiguous, add 'file'."
                },
                "file": {
                    "type": "string",
                    "description": "File path to disambiguate when using 'name'"
                },
                "max_depth": {
                    "type": "number",
                    "description": "Maximum traversal depth",
                    "default": 2
                },
                "max_nodes": {
                    "type": "number",
                    "description": "Maximum nodes to include in result",
                    "default": 50
                }
            }
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to open database: {e}")))?;

        let node_id = resolve_node_id(&conn, &self.project_root, &params, "node_id")?;

        let max_depth = params
            .get("max_depth")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok());
        let max_nodes = params
            .get("max_nodes")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok());

        let traversal_options = TraversalOptions {
            max_depth,
            edge_kinds: Some(vec![EdgeKind::Calls, EdgeKind::References]),
            node_kinds: None,
            direction: Some(TraversalDirection::Incoming), // Find what depends on this
            limit: max_nodes,
            include_start: Some(true),
        };

        let subgraph = graph::build_subgraph(&conn, &[node_id], &traversal_options)
            .map_err(|e| ToolError::internal_error(format!("Failed to build subgraph: {e}")))?;

        let nodes: Vec<Value> = subgraph
            .nodes
            .values()
            .map(|node| {
                json!({
                    "id": node.id,
                    "kind": node.kind,
                    "name": node.name,
                    "qualified_name": node.qualified_name,
                    "file_path": node.file_path,
                    "start_line": node.start_line,
                })
            })
            .collect();

        let edges: Vec<Value> = subgraph
            .edges
            .iter()
            .map(|edge| {
                json!({
                    "source": edge.source,
                    "target": edge.target,
                    "kind": edge.kind,
                    "line": edge.line,
                })
            })
            .collect();

        let files: std::collections::HashSet<_> =
            subgraph.nodes.values().map(|n| &n.file_path).collect();

        Ok(json!({
            "nodes": nodes,
            "edges": edges,
            "stats": {
                "node_count": nodes.len(),
                "edge_count": edges.len(),
                "file_count": files.len(),
                "max_depth": max_depth.unwrap_or(2),
            }
        }))
    }
}

/// Tool for finding a symbol by name pattern (richer than search — returns hierarchy/depth info)
pub struct FindSymbolTool {
    project_root: PathBuf,
}

impl FindSymbolTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for FindSymbolTool {
    fn name(&self) -> &'static str {
        "coraline_find_symbol"
    }

    fn description(&self) -> &'static str {
        "Find symbols by exact name or substring pattern. Returns node metadata and optionally the source code body."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "name_pattern": {
                    "type": "string",
                    "description": "Symbol name or substring to search for"
                },
                "kind": {
                    "type": "string",
                    "description": "Optional node kind filter",
                    "enum": ["function", "method", "class", "struct", "interface", "trait", "module"]
                },
                "file": {
                    "type": "string",
                    "description": "Restrict results to symbols in this file path"
                },
                "include_body": {
                    "type": "boolean",
                    "description": "Whether to include the source code body of the symbol",
                    "default": false
                },
                "limit": {
                    "type": "number",
                    "description": "Maximum results to return",
                    "default": 10
                }
            },
            "required": ["name_pattern"]
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let pattern = params
            .get("name_pattern")
            .and_then(Value::as_str)
            .ok_or_else(|| ToolError::invalid_params("name_pattern must be a string"))?;

        let kind = params
            .get("kind")
            .and_then(Value::as_str)
            .and_then(str_to_node_kind);

        let include_body = params
            .get("include_body")
            .and_then(Value::as_bool)
            .unwrap_or(false);

        let limit = params
            .get("limit")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok())
            .unwrap_or(10);

        let file_filter = params.get("file").and_then(Value::as_str);

        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to open database: {e}")))?;

        // Fetch extra results when file-filtering so we still hit the requested limit.
        let fetch_limit = if file_filter.is_some() {
            limit * 5
        } else {
            limit
        };
        let results = db::search_nodes(&conn, pattern, kind, fetch_limit)
            .map_err(|e| ToolError::internal_error(format!("Search failed: {e}")))?;

        let abs_file = file_filter.map(|f| {
            if std::path::Path::new(f).is_absolute() {
                f.to_string()
            } else {
                self.project_root.join(f).to_string_lossy().to_string()
            }
        });

        let symbols: Vec<Value> = results
            .into_iter()
            .filter(|r| {
                abs_file.as_ref().is_none_or(|af| {
                    r.node.file_path == *af || file_filter.is_some_and(|f| r.node.file_path == f)
                })
            })
            .take(limit)
            .map(|r| {
                let body = if include_body {
                    read_node_source(&self.project_root, &r.node)
                } else {
                    None
                };
                json!({
                    "id": r.node.id,
                    "kind": r.node.kind,
                    "name": r.node.name,
                    "qualified_name": r.node.qualified_name,
                    "file_path": r.node.file_path,
                    "language": r.node.language,
                    "start_line": r.node.start_line,
                    "end_line": r.node.end_line,
                    "signature": r.node.signature,
                    "docstring": r.node.docstring,
                    "is_exported": r.node.is_exported,
                    "is_async": r.node.is_async,
                    "is_static": r.node.is_static,
                    "score": r.score,
                    "body": body,
                })
            })
            .collect();

        Ok(json!({ "symbols": symbols, "count": symbols.len() }))
    }
}

/// Tool for getting a symbol overview for a file
pub struct GetSymbolsOverviewTool {
    project_root: PathBuf,
}

impl GetSymbolsOverviewTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for GetSymbolsOverviewTool {
    fn name(&self) -> &'static str {
        "coraline_get_symbols_overview"
    }

    fn description(&self) -> &'static str {
        "Get an overview of all symbols in a file, grouped by kind and ordered by line number."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "file_path": {
                    "type": "string",
                    "description": "Path to the file (relative to project root or absolute)"
                }
            },
            "required": ["file_path"]
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let file_path = params
            .get("file_path")
            .and_then(Value::as_str)
            .ok_or_else(|| ToolError::invalid_params("file_path must be a string"))?;

        // Normalise: if relative, make absolute using project root
        let abs_path = if std::path::Path::new(file_path).is_absolute() {
            file_path.to_string()
        } else {
            self.project_root
                .join(file_path)
                .to_string_lossy()
                .to_string()
        };

        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to open database: {e}")))?;

        let nodes = db::get_nodes_by_file(&conn, &abs_path, None)
            .map_err(|e| ToolError::internal_error(format!("Failed to get nodes: {e}")))?;

        if nodes.is_empty() {
            // Try with the path as-is (might be stored relative)
            let nodes_fallback = db::get_nodes_by_file(&conn, file_path, None)
                .map_err(|e| ToolError::internal_error(format!("Failed to get nodes: {e}")))?;

            return build_overview_response(&nodes_fallback, file_path);
        }

        build_overview_response(&nodes, &abs_path)
    }
}

#[allow(clippy::unnecessary_wraps)]
fn build_overview_response(nodes: &[crate::types::Node], file_path: &str) -> ToolResult {
    use std::collections::HashMap;

    let mut by_kind: HashMap<String, Vec<Value>> = HashMap::new();

    for node in nodes {
        let kind_str = format!("{:?}", node.kind).to_lowercase();
        by_kind.entry(kind_str).or_default().push(json!({
            "id": node.id,
            "name": node.name,
            "qualified_name": node.qualified_name,
            "start_line": node.start_line,
            "end_line": node.end_line,
            "signature": node.signature,
            "is_exported": node.is_exported,
        }));
    }

    let symbols: Vec<Value> = nodes
        .iter()
        .map(|n| {
            json!({
                "id": n.id,
                "kind": n.kind,
                "name": n.name,
                "start_line": n.start_line,
                "end_line": n.end_line,
                "signature": n.signature,
            })
        })
        .collect();

    Ok(json!({
        "file_path": file_path,
        "symbol_count": nodes.len(),
        "by_kind": by_kind,
        "symbols": symbols,
    }))
}

/// Tool for finding all references to a node
pub struct FindReferencesTool {
    project_root: PathBuf,
}

impl FindReferencesTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for FindReferencesTool {
    fn name(&self) -> &'static str {
        "coraline_find_references"
    }

    fn description(&self) -> &'static str {
        "Find all nodes that reference (call, import, extend, implement, etc.) a given symbol."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "node_id": {
                    "type": "string",
                    "description": "ID of the node to find references to"
                },
                "name": {
                    "type": "string",
                    "description": "Symbol name (alternative to node_id). If ambiguous, add 'file'."
                },
                "file": {
                    "type": "string",
                    "description": "File path to disambiguate when using 'name'"
                },
                "edge_kind": {
                    "type": "string",
                    "description": "Filter by edge kind (calls, imports, extends, implements, references)",
                    "enum": ["calls", "imports", "extends", "implements", "references"]
                },
                "limit": {
                    "type": "number",
                    "description": "Maximum number of references to return",
                    "default": 50
                }
            }
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to open database: {e}")))?;

        let node_id = resolve_node_id(&conn, &self.project_root, &params, "node_id")?;

        let edge_kind = params
            .get("edge_kind")
            .and_then(Value::as_str)
            .and_then(|s| match s {
                "calls" => Some(EdgeKind::Calls),
                "imports" => Some(EdgeKind::Imports),
                "extends" => Some(EdgeKind::Extends),
                "implements" => Some(EdgeKind::Implements),
                "references" => Some(EdgeKind::References),
                _ => None,
            });

        let limit = params
            .get("limit")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok())
            .unwrap_or(50);

        let edges = db::get_edges_by_target(&conn, &node_id, edge_kind, limit)
            .map_err(|e| ToolError::internal_error(format!("Failed to get edges: {e}")))?;

        let mut references = Vec::new();
        for edge in &edges {
            if let Some(node) = db::get_node_by_id(&conn, &edge.source)
                .map_err(|e| ToolError::internal_error(format!("Failed to get node: {e}")))?
            {
                references.push(json!({
                    "id": node.id,
                    "kind": node.kind,
                    "name": node.name,
                    "qualified_name": node.qualified_name,
                    "file_path": node.file_path,
                    "start_line": node.start_line,
                    "edge_kind": edge.kind,
                    "edge_line": edge.line,
                }));
            }
        }

        Ok(json!({
            "node_id": node_id,
            "references": references,
            "count": references.len(),
        }))
    }
}

/// Tool for getting full node details including source code
pub struct GetNodeTool {
    project_root: PathBuf,
}

impl GetNodeTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for GetNodeTool {
    fn name(&self) -> &'static str {
        "coraline_node"
    }

    fn description(&self) -> &'static str {
        "Get complete details for a specific node by ID, including its source code body."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "node_id": {
                    "type": "string",
                    "description": "The node ID to retrieve"
                },
                "name": {
                    "type": "string",
                    "description": "Symbol name (alternative to node_id). If ambiguous, add 'file'."
                },
                "file": {
                    "type": "string",
                    "description": "File path to disambiguate when using 'name'"
                },
                "include_edges": {
                    "type": "boolean",
                    "description": "Whether to include outgoing and incoming edge counts",
                    "default": false
                }
            }
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to open database: {e}")))?;

        let node_id = resolve_node_id(&conn, &self.project_root, &params, "node_id")?;

        let include_edges = params
            .get("include_edges")
            .and_then(Value::as_bool)
            .unwrap_or(false);

        let node = db::get_node_by_id(&conn, &node_id)
            .map_err(|e| ToolError::internal_error(format!("Failed to get node: {e}")))?
            .ok_or_else(|| ToolError::not_found(format!("Node not found: {node_id}")))?;

        let body = read_node_source(&self.project_root, &node);

        let mut result = json!({
            "id": node.id,
            "kind": node.kind,
            "name": node.name,
            "qualified_name": node.qualified_name,
            "file_path": node.file_path,
            "language": node.language,
            "start_line": node.start_line,
            "end_line": node.end_line,
            "start_column": node.start_column,
            "end_column": node.end_column,
            "signature": node.signature,
            "docstring": node.docstring,
            "visibility": node.visibility,
            "is_exported": node.is_exported,
            "is_async": node.is_async,
            "is_static": node.is_static,
            "is_abstract": node.is_abstract,
            "decorators": node.decorators,
            "type_parameters": node.type_parameters,
            "body": body,
        });

        if include_edges {
            let out_edges = db::get_edges_by_source(&conn, &node_id, None, 200)
                .map_err(|e| ToolError::internal_error(format!("Failed to get edges: {e}")))?;
            let in_edges = db::get_edges_by_target(&conn, &node_id, None, 200)
                .map_err(|e| ToolError::internal_error(format!("Failed to get edges: {e}")))?;
            if let Some(obj) = result.as_object_mut() {
                obj.insert("outgoing_edge_count".to_string(), json!(out_edges.len()));
                obj.insert("incoming_edge_count".to_string(), json!(in_edges.len()));
            }
        }

        Ok(result)
    }
}

/// Tool for the outgoing dependency graph — everything a node depends on.
pub struct DependenciesTool {
    project_root: PathBuf,
}

impl DependenciesTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for DependenciesTool {
    fn name(&self) -> &'static str {
        "coraline_dependencies"
    }

    fn description(&self) -> &'static str {
        "Get the outgoing dependency graph for a node — everything this symbol \
         depends on (calls, imports, references, etc.), traversed up to a given depth. \
         Broader than coraline_callees: follows all edge kinds, multiple hops."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "node_id": {
                    "type": "string",
                    "description": "ID of the node to find dependencies for"
                },
                "name": {
                    "type": "string",
                    "description": "Symbol name (alternative to node_id). If ambiguous, add 'file'."
                },
                "file": {
                    "type": "string",
                    "description": "File path to disambiguate when using 'name'"
                },
                "depth": {
                    "type": "number",
                    "description": "Traversal depth (default 2)",
                    "default": 2
                },
                "limit": {
                    "type": "number",
                    "description": "Maximum number of nodes to return (default 50)",
                    "default": 50
                }
            }
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to open database: {e}")))?;

        let node_id = resolve_node_id(&conn, &self.project_root, &params, "node_id")?;

        let depth = params
            .get("depth")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok());
        let limit = params
            .get("limit")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok());

        let options = TraversalOptions {
            max_depth: depth.or(Some(2)),
            edge_kinds: None,
            node_kinds: None,
            direction: Some(TraversalDirection::Outgoing),
            limit: limit.or(Some(50)),
            include_start: Some(false),
        };

        let subgraph = graph::build_subgraph(&conn, std::slice::from_ref(&node_id), &options)
            .map_err(|e| ToolError::internal_error(format!("Graph traversal failed: {e}")))?;

        let nodes: Vec<Value> = subgraph
            .nodes
            .values()
            .map(|n| {
                json!({
                    "id": n.id,
                    "kind": n.kind,
                    "name": n.name,
                    "qualified_name": n.qualified_name,
                    "file_path": n.file_path,
                    "start_line": n.start_line,
                })
            })
            .collect();

        let edges: Vec<Value> = subgraph
            .edges
            .iter()
            .map(|e| {
                json!({
                    "source": e.source,
                    "target": e.target,
                    "kind": e.kind,
                    "line": e.line,
                })
            })
            .collect();

        Ok(json!({
            "node_id": node_id,
            "dependencies": nodes,
            "edges": edges,
            "count": nodes.len(),
        }))
    }
}

/// Tool for the incoming dependency graph — everything that depends on a node.
pub struct DependentsTool {
    project_root: PathBuf,
}

impl DependentsTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for DependentsTool {
    fn name(&self) -> &'static str {
        "coraline_dependents"
    }

    fn description(&self) -> &'static str {
        "Get the incoming dependency graph for a node — everything that depends on this \
         symbol (all callers, importers, referencers), traversed up to a given depth. \
         Broader than coraline_callers: follows all edge kinds, multiple hops."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "node_id": {
                    "type": "string",
                    "description": "ID of the node"
                },
                "name": {
                    "type": "string",
                    "description": "Symbol name (alternative to node_id). If ambiguous, add 'file'."
                },
                "file": {
                    "type": "string",
                    "description": "File path to disambiguate when using 'name'"
                },
                "depth": {
                    "type": "number",
                    "description": "Traversal depth (default 2)",
                    "default": 2
                },
                "limit": {
                    "type": "number",
                    "description": "Maximum number of nodes to return (default 50)",
                    "default": 50
                }
            }
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to open database: {e}")))?;

        let node_id = resolve_node_id(&conn, &self.project_root, &params, "node_id")?;

        let depth = params
            .get("depth")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok());
        let limit = params
            .get("limit")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok());

        let options = TraversalOptions {
            max_depth: depth.or(Some(2)),
            edge_kinds: None,
            node_kinds: None,
            direction: Some(TraversalDirection::Incoming),
            limit: limit.or(Some(50)),
            include_start: Some(false),
        };

        let subgraph = graph::build_subgraph(&conn, std::slice::from_ref(&node_id), &options)
            .map_err(|e| ToolError::internal_error(format!("Graph traversal failed: {e}")))?;

        let nodes: Vec<Value> = subgraph
            .nodes
            .values()
            .map(|n| {
                json!({
                    "id": n.id,
                    "kind": n.kind,
                    "name": n.name,
                    "qualified_name": n.qualified_name,
                    "file_path": n.file_path,
                    "start_line": n.start_line,
                })
            })
            .collect();

        let edges: Vec<Value> = subgraph
            .edges
            .iter()
            .map(|e| {
                json!({
                    "source": e.source,
                    "target": e.target,
                    "kind": e.kind,
                    "line": e.line,
                })
            })
            .collect();

        Ok(json!({
            "node_id": node_id,
            "dependents": nodes,
            "edges": edges,
            "count": nodes.len(),
        }))
    }
}

/// Tool for finding the shortest directed path between two nodes.
pub struct PathTool {
    project_root: PathBuf,
}

impl PathTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for PathTool {
    fn name(&self) -> &'static str {
        "coraline_path"
    }

    fn description(&self) -> &'static str {
        "Find the shortest directed path through the call/reference graph between two symbols. \
         Useful for understanding indirect dependencies — how does symbol A transitively lead to B?"
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "from_id": {
                    "type": "string",
                    "description": "Starting node ID"
                },
                "from_name": {
                    "type": "string",
                    "description": "Starting symbol name (alternative to from_id)"
                },
                "from_file": {
                    "type": "string",
                    "description": "File path to disambiguate from_name"
                },
                "to_id": {
                    "type": "string",
                    "description": "Target node ID"
                },
                "to_name": {
                    "type": "string",
                    "description": "Target symbol name (alternative to to_id)"
                },
                "to_file": {
                    "type": "string",
                    "description": "File path to disambiguate to_name"
                },
                "max_depth": {
                    "type": "number",
                    "description": "Maximum path length to search (default 6)",
                    "default": 6
                }
            }
        })
    }

    fn execute(&self, params: Value) -> ToolResult {
        use std::collections::{HashMap, VecDeque};

        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to open database: {e}")))?;

        // Resolve from: use from_id directly, or from_name+from_file
        let from_params = {
            let mut p = serde_json::Map::new();
            if let Some(v) = params.get("from_id") {
                p.insert("node_id".to_string(), v.clone());
            }
            if let Some(v) = params.get("from_name") {
                p.insert("name".to_string(), v.clone());
            }
            if let Some(v) = params.get("from_file") {
                p.insert("file".to_string(), v.clone());
            }
            Value::Object(p)
        };
        let from_id = resolve_node_id(&conn, &self.project_root, &from_params, "node_id")?;

        // Resolve to: use to_id directly, or to_name+to_file
        let to_params = {
            let mut p = serde_json::Map::new();
            if let Some(v) = params.get("to_id") {
                p.insert("node_id".to_string(), v.clone());
            }
            if let Some(v) = params.get("to_name") {
                p.insert("name".to_string(), v.clone());
            }
            if let Some(v) = params.get("to_file") {
                p.insert("file".to_string(), v.clone());
            }
            Value::Object(p)
        };
        let to_id = resolve_node_id(&conn, &self.project_root, &to_params, "node_id")?;

        let max_depth = params
            .get("max_depth")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok())
            .unwrap_or(6);

        // BFS following outgoing edges, recording parents for path reconstruction.

        // Maps node_id → parent_id (empty string for the root).
        let mut parent: HashMap<String, String> = HashMap::new();
        parent.insert(from_id.clone(), String::new());

        let mut queue: VecDeque<(String, usize)> = VecDeque::new();
        queue.push_back((from_id.clone(), 0));

        let mut found = false;
        'bfs: while let Some((current, depth)) = queue.pop_front() {
            if depth >= max_depth {
                continue;
            }
            let edges = db::get_edges_by_source(&conn, &current, None, 500)
                .map_err(|e| ToolError::internal_error(format!("Edge query failed: {e}")))?;
            for edge in edges {
                if parent.contains_key(&edge.target) {
                    continue;
                }
                parent.insert(edge.target.clone(), current.clone());
                if edge.target == to_id {
                    found = true;
                    break 'bfs;
                }
                queue.push_back((edge.target.clone(), depth + 1));
            }
        }

        if !found {
            return Ok(json!({
                "from_id": from_id,
                "to_id": to_id,
                "path_found": false,
                "path": [],
                "message": format!(
                    "No directed path found from {from_id} to {to_id} within depth {max_depth}"
                ),
            }));
        }

        // Reconstruct path by walking parents backward from to_id.
        let mut path_ids: Vec<String> = Vec::new();
        let mut cursor = to_id.clone();
        while !cursor.is_empty() {
            path_ids.push(cursor.clone());
            cursor = parent.get(&cursor).cloned().unwrap_or_default();
        }
        path_ids.reverse();

        let path: Vec<Value> = path_ids
            .iter()
            .filter_map(|id| db::get_node_by_id(&conn, id).ok().flatten())
            .map(|n| {
                json!({
                    "id": n.id,
                    "kind": n.kind,
                    "name": n.name,
                    "qualified_name": n.qualified_name,
                    "file_path": n.file_path,
                    "start_line": n.start_line,
                })
            })
            .collect();

        Ok(json!({
            "from_id": from_id,
            "to_id": to_id,
            "path_found": true,
            "path": path,
            "length": path.len(),
        }))
    }
}

/// Tool for detailed graph statistics broken down by language, node kind, and edge kind.
pub struct StatsTool {
    project_root: PathBuf,
}

impl StatsTool {
    pub const fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }
}

impl Tool for StatsTool {
    fn name(&self) -> &'static str {
        "coraline_stats"
    }

    fn description(&self) -> &'static str {
        "Return detailed graph statistics: total counts, per-language file breakdown, node kind breakdown, and edge kind breakdown."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {}
        })
    }

    fn execute(&self, _params: Value) -> ToolResult {
        let conn = db::open_database(&self.project_root)
            .map_err(|e| ToolError::internal_error(format!("Failed to open database: {e}")))?;

        // Basic counts
        let node_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM nodes", [], |r| r.get(0))
            .map_err(|e| ToolError::internal_error(format!("Query failed: {e}")))?;
        let edge_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM edges", [], |r| r.get(0))
            .map_err(|e| ToolError::internal_error(format!("Query failed: {e}")))?;
        let file_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM files", [], |r| r.get(0))
            .map_err(|e| ToolError::internal_error(format!("Query failed: {e}")))?;
        let unresolved_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM unresolved_refs", [], |r| r.get(0))
            .map_err(|e| ToolError::internal_error(format!("Query failed: {e}")))?;
        let vector_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM vectors", [], |r| r.get(0))
            .map_err(|e| ToolError::internal_error(format!("Query failed: {e}")))?;

        // Files by language
        let mut by_language = serde_json::Map::new();
        {
            let mut stmt = conn
                .prepare("SELECT language, COUNT(*) FROM files GROUP BY language ORDER BY 2 DESC")
                .map_err(|e| ToolError::internal_error(format!("Query failed: {e}")))?;
            let rows = stmt
                .query_map([], |row| {
                    Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
                })
                .map_err(|e| ToolError::internal_error(format!("Query failed: {e}")))?;
            for row in rows.flatten() {
                by_language.insert(row.0, Value::Number(row.1.into()));
            }
        }

        // Nodes by kind
        let mut by_kind = serde_json::Map::new();
        {
            let mut stmt = conn
                .prepare("SELECT kind, COUNT(*) FROM nodes GROUP BY kind ORDER BY 2 DESC")
                .map_err(|e| ToolError::internal_error(format!("Query failed: {e}")))?;
            let rows = stmt
                .query_map([], |row| {
                    Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
                })
                .map_err(|e| ToolError::internal_error(format!("Query failed: {e}")))?;
            for row in rows.flatten() {
                by_kind.insert(row.0, Value::Number(row.1.into()));
            }
        }

        // Edges by kind
        let mut by_edge_kind = serde_json::Map::new();
        {
            let mut stmt = conn
                .prepare("SELECT kind, COUNT(*) FROM edges GROUP BY kind ORDER BY 2 DESC")
                .map_err(|e| ToolError::internal_error(format!("Query failed: {e}")))?;
            let rows = stmt
                .query_map([], |row| {
                    Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
                })
                .map_err(|e| ToolError::internal_error(format!("Query failed: {e}")))?;
            for row in rows.flatten() {
                by_edge_kind.insert(row.0, Value::Number(row.1.into()));
            }
        }

        Ok(json!({
            "totals": {
                "nodes": node_count,
                "edges": edge_count,
                "files": file_count,
                "unresolved_references": unresolved_count,
                "vectors": vector_count,
            },
            "files_by_language": by_language,
            "nodes_by_kind": by_kind,
            "edges_by_kind": by_edge_kind,
        }))
    }
}

// ── Helpers ──────────────────────────────────────────────────────────────────

/// Resolve a node ID from tool params.
///
/// Accepts either:
///  - `node_id` directly, **or**
///  - `name` (+ optional `file` for disambiguation)
///
/// When `name` matches multiple nodes and no `file` is given, returns an error
/// listing all candidates so the caller can retry with a `file` hint.
fn resolve_node_id(
    conn: &rusqlite::Connection,
    project_root: &std::path::Path,
    params: &Value,
    id_field: &str,
) -> Result<String, ToolError> {
    // Fast path: explicit node_id
    if let Some(id) = params
        .get(id_field)
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
    {
        return Ok(id.to_string());
    }

    // Slow path: resolve by name (+ optional file)
    let name = params.get("name").and_then(Value::as_str).ok_or_else(|| {
        ToolError::invalid_params(format!("Either '{id_field}' or 'name' must be provided"))
    })?;

    let file_hint = params.get("file").and_then(Value::as_str);

    let mut candidates = db::find_nodes_by_name(conn, name)
        .map_err(|e| ToolError::internal_error(format!("Name lookup failed: {e}")))?;

    // Narrow by file if provided
    if let Some(file) = file_hint {
        let abs_hint = if std::path::Path::new(file).is_absolute() {
            file.to_string()
        } else {
            project_root.join(file).to_string_lossy().to_string()
        };
        candidates.retain(|n| n.file_path == abs_hint || n.file_path == file);
    }

    match candidates.len() {
        0 => Err(ToolError::not_found(format!(
            "No symbol named '{name}' found{}",
            file_hint.map_or_else(String::new, |f| format!(" in file '{f}'"))
        ))),
        1 => candidates
            .into_iter()
            .next()
            .map(|n| n.id)
            .ok_or_else(|| ToolError::internal_error("internal: candidate count mismatch")),
        _ => {
            let listing: Vec<String> = candidates
                .iter()
                .map(|n| {
                    format!(
                        "  {} ({:?}) — {}:{}",
                        n.id, n.kind, n.file_path, n.start_line
                    )
                })
                .collect();
            Err(ToolError::invalid_params(format!(
                "Ambiguous: {count} symbols named '{name}'. \
                 Supply '{id_field}' or add 'file' to disambiguate:\n{list}",
                count = candidates.len(),
                list = listing.join("\n"),
            )))
        }
    }
}

/// Read the source lines for a node from its file on disk.
fn read_node_source(project_root: &std::path::Path, node: &crate::types::Node) -> Option<String> {
    let path = if std::path::Path::new(&node.file_path).is_absolute() {
        std::path::PathBuf::from(&node.file_path)
    } else {
        project_root.join(&node.file_path)
    };

    let text = std::fs::read_to_string(&path).ok()?;
    let lines: Vec<&str> = text.lines().collect();

    let start = usize::try_from(node.start_line)
        .unwrap_or(0)
        .saturating_sub(1);
    let end = usize::try_from(node.end_line).unwrap_or(0).min(lines.len());

    lines.get(start..end).map(|l| l.join("\n"))
}

/// Convert a string to a [`NodeKind`] (shared helper).
fn str_to_node_kind(s: &str) -> Option<NodeKind> {
    match s {
        "function" => Some(NodeKind::Function),
        "method" => Some(NodeKind::Method),
        "class" => Some(NodeKind::Class),
        "struct" => Some(NodeKind::Struct),
        "interface" => Some(NodeKind::Interface),
        "trait" => Some(NodeKind::Trait),
        "module" => Some(NodeKind::Module),
        _ => None,
    }
}