loregrep 0.5.0

Repository indexing library for AI coding assistants. Tree-sitter parsing, fast in-memory indexing, and tool APIs for LLM integration.
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
use crate::{analyzers::registry::RegistryHandle, storage::memory::RepoMap};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::sync::{Arc, Mutex};

use crate::core::types::ToolSchema;

#[derive(Clone)]
pub struct LocalAnalysisTools {
    repo_map: Arc<Mutex<RepoMap>>,
    /// Handle into the language-analyzer registry. Analysis is dispatched to the
    /// analyzer that matches each file's language, rather than a single
    /// hard-coded analyzer.
    registry: RegistryHandle,
}

impl LocalAnalysisTools {
    pub fn new(repo_map: Arc<Mutex<RepoMap>>, registry: RegistryHandle) -> Self {
        Self { repo_map, registry }
    }

    pub fn get_tool_schemas(&self) -> Vec<ToolSchema> {
        vec![
            ToolSchema {
                name: "search_functions".to_string(),
                description: "Look up functions by name or regex and return their structured signature: parameters, return type, visibility, async/const/static flags, and the definition's file path and line range.".to_string(),
                input_schema: json!({
                    "type": "object",
                    "properties": {
                        "pattern": {
                            "type": "string",
                            "description": "Name or regex pattern to match function names"
                        },
                        "limit": {
                            "type": "integer",
                            "description": "Maximum number of results to return",
                            "default": 20
                        },
                        "language": {
                            "type": "string",
                            "description": "Filter by programming language (optional)"
                        }
                    },
                    "required": ["pattern"]
                }),
            },
            ToolSchema {
                name: "search_structs".to_string(),
                description: "Look up structs, classes, and interfaces by name or regex and return their fields, generics, visibility, and definition location.".to_string(),
                input_schema: json!({
                    "type": "object", 
                    "properties": {
                        "pattern": {
                            "type": "string",
                            "description": "Name or regex pattern to match struct/class names"
                        },
                        "limit": {
                            "type": "integer",
                            "description": "Maximum number of results to return",
                            "default": 20
                        },
                        "language": {
                            "type": "string",
                            "description": "Filter by programming language (optional)"
                        }
                    },
                    "required": ["pattern"]
                }),
            },
            ToolSchema {
                name: "analyze_file".to_string(),
                description: "Get a file's structural skeleton — its functions, structs, imports, exports, and calls with signatures and line numbers — without reading the whole file into context.".to_string(),
                input_schema: json!({
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": "Path to the file to analyze"
                        },
                        "include_content": {
                            "type": "boolean",
                            "description": "Whether to include file content in the response",
                            "default": false
                        }
                    },
                    "required": ["file_path"]
                }),
            },
            ToolSchema {
                name: "get_dependencies".to_string(),
                description: "Get a file's import/export edges from the dependency graph — what it depends on and what it exposes — without reading the file.".to_string(),
                input_schema: json!({
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": "Path to the file to analyze dependencies for"
                        }
                    },
                    "required": ["file_path"]
                }),
            },
            ToolSchema {
                name: "find_callers".to_string(),
                description: "Return the direct call sites of a function across the repository, each with file path and line, resolved from the parsed call graph — call expressions only (not comments, string literals, imports, or the definition).".to_string(),
                input_schema: json!({
                    "type": "object",
                    "properties": {
                        "function_name": {
                            "type": "string",
                            "description": "Name of the function to find callers for"
                        },
                        "limit": {
                            "type": "integer",
                            "description": "Maximum number of results to return",
                            "default": 50
                        }
                    },
                    "required": ["function_name"]
                }),
            },
            ToolSchema {
                name: "get_repository_tree".to_string(),
                description: "Get a structural map of the repository — directories, files, and per-file symbol skeletons — for fast orientation without reading files. Use include_file_details=false and max_depth=1 for an overview, or full defaults for a comprehensive map.".to_string(),
                input_schema: json!({
                    "type": "object",
                    "properties": {
                        "include_file_details": {
                            "type": "boolean",
                            "description": "Whether to include detailed file skeletons with functions and structs. Set to false for overview-style information.",
                            "default": true
                        },
                        "max_depth": {
                            "type": "integer",
                            "description": "Maximum directory depth to include (0 for unlimited). Use 1 for overview-style information.",
                            "default": 0
                        }
                    }
                })
            },
        ]
    }

    pub async fn execute_tool(&self, tool_name: &str, input: Value) -> Result<ToolResult> {
        match tool_name {
            "search_functions" => self.search_functions(input).await,
            "search_structs" => self.search_structs(input).await,
            "analyze_file" => self.analyze_file(input).await,
            "get_dependencies" => self.get_dependencies(input).await,
            "find_callers" => self.find_callers(input).await,
            "get_repository_tree" => self.get_repository_tree(input).await,
            _ => Ok(ToolResult::error(format!("Unknown tool: {}", tool_name))),
        }
    }

    async fn search_functions(&self, input: Value) -> Result<ToolResult> {
        let search_input: SearchFunctionsInput =
            serde_json::from_value(input).context("Invalid search_functions input")?;

        let repo_map = self.repo_map.lock().unwrap();
        let results = repo_map.find_functions(&search_input.pattern);
        // Apply the optional language filter: keep only functions defined in a
        // file whose analyzer language matches (case-insensitive). Each result's
        // owning file is looked up in the repo map to recover its language, since
        // FunctionSignature does not carry the language directly. A filter for a
        // language absent from the repo therefore yields an empty set.
        let language_filter = search_input.language.as_deref();
        let limited_results: Vec<_> = results
            .items
            .into_iter()
            .filter(|func| match language_filter {
                Some(lang) => repo_map
                    .get_file(&func.file_path)
                    .map(|node| node.language.eq_ignore_ascii_case(lang))
                    .unwrap_or(false),
                None => true,
            })
            .take(search_input.limit.unwrap_or(20))
            .collect();

        let result = json!({
            "status": "success",
            "pattern": search_input.pattern,
            "results": limited_results,
            "count": limited_results.len()
        });

        Ok(ToolResult::success(result))
    }

    async fn search_structs(&self, input: Value) -> Result<ToolResult> {
        let search_input: SearchStructsInput =
            serde_json::from_value(input).context("Invalid search_structs input")?;

        let repo_map = self.repo_map.lock().unwrap();
        let results = repo_map.find_structs(&search_input.pattern);
        // Apply the optional language filter (see search_functions above).
        let language_filter = search_input.language.as_deref();
        let limited_results: Vec<_> = results
            .items
            .into_iter()
            .filter(|struct_def| match language_filter {
                Some(lang) => repo_map
                    .get_file(&struct_def.file_path)
                    .map(|node| node.language.eq_ignore_ascii_case(lang))
                    .unwrap_or(false),
                None => true,
            })
            .take(search_input.limit.unwrap_or(20))
            .collect();

        let result = json!({
            "status": "success",
            "pattern": search_input.pattern,
            "results": limited_results,
            "count": limited_results.len()
        });

        Ok(ToolResult::success(result))
    }

    async fn analyze_file(&self, input: Value) -> Result<ToolResult> {
        let analyze_input: AnalyzeFileInput =
            serde_json::from_value(input).context("Invalid analyze_file input")?;

        // Resolve the analyzer for this file's language via the registry. If no
        // analyzer is registered for the file's extension, report a clear error
        // instead of silently analyzing it with the wrong language.
        let analyzer = match self
            .registry
            .get_analyzer_for_path(&analyze_input.file_path)
        {
            Some(analyzer) => analyzer,
            None => {
                return Ok(ToolResult::error(format!(
                    "unsupported language for {}",
                    analyze_input.file_path
                )));
            }
        };

        // Try to read the file and analyze it
        match tokio::fs::read_to_string(&analyze_input.file_path).await {
            Ok(content) => {
                let file_analysis = analyzer
                    .analyze_file(&content, &analyze_input.file_path)
                    .await?;

                let tree_node = &file_analysis.tree_node;
                let mut result = json!({
                    "status": "success",
                    "file_path": analyze_input.file_path,
                    // Expose the analysis fields at the top level so consumers
                    // (CLI display, public API callers) can read them directly.
                    "language": tree_node.language,
                    "functions": tree_node.functions,
                    "structs": tree_node.structs,
                    "imports": tree_node.imports,
                    "exports": tree_node.exports,
                    "function_calls": tree_node.function_calls
                });

                if analyze_input.include_content.unwrap_or(false) {
                    result
                        .as_object_mut()
                        .unwrap()
                        .insert("content".to_string(), json!(content));
                }

                Ok(ToolResult::success(result))
            }
            Err(e) => {
                let result = json!({
                    "status": "error",
                    "file_path": analyze_input.file_path,
                    "error": format!("Failed to read file: {}", e)
                });
                Ok(ToolResult::error_with_data(result))
            }
        }
    }

    async fn get_dependencies(&self, input: Value) -> Result<ToolResult> {
        let deps_input: GetDependenciesInput =
            serde_json::from_value(input).context("Invalid get_dependencies input")?;

        let dependencies = self
            .repo_map
            .lock()
            .unwrap()
            .get_file_dependencies(&deps_input.file_path);

        let result = json!({
            "status": "success",
            "file_path": deps_input.file_path,
            "dependencies": dependencies
        });

        Ok(ToolResult::success(result))
    }

    async fn find_callers(&self, input: Value) -> Result<ToolResult> {
        let callers_input: FindCallersInput =
            serde_json::from_value(input).context("Invalid find_callers input")?;

        let callers = self
            .repo_map
            .lock()
            .unwrap()
            .find_function_callers(&callers_input.function_name);
        let limited_callers: Vec<_> = callers
            .into_iter()
            .take(callers_input.limit.unwrap_or(50))
            .collect();

        let result = json!({
            "status": "success",
            "function_name": callers_input.function_name,
            "callers": limited_callers,
            "count": limited_callers.len()
        });

        Ok(ToolResult::success(result))
    }

    async fn get_repository_tree(&self, input: Value) -> Result<ToolResult> {
        let tree_input: GetRepositoryTreeInput =
            serde_json::from_value(input).unwrap_or_else(|_| GetRepositoryTreeInput {
                include_file_details: Some(true),
                max_depth: None,
            });

        // Get the actual repository tree structure from repo_map
        // This will build the full hierarchical structure if it doesn't exist
        let (repository_tree_opt, file_count, metadata) = {
            let mut repo_map = self.repo_map.lock().unwrap();

            // Ensure repository tree is built if needed
            if let Err(e) = repo_map.build_repository_tree_if_needed() {
                eprintln!("Warning: Failed to build repository tree: {}", e);
            }

            (
                repo_map.get_repository_tree(),
                repo_map.file_count(),
                repo_map.get_metadata().clone(),
            )
        };

        match repository_tree_opt {
            Some(repository_tree) => {
                // Apply depth filtering if requested
                let filtered_tree_root = if let Some(max_depth) = tree_input.max_depth {
                    if max_depth > 0 {
                        self.apply_depth_filter(&repository_tree.root, max_depth)
                    } else {
                        repository_tree.root.clone()
                    }
                } else {
                    repository_tree.root.clone()
                };

                // Apply file detail filtering if requested
                let final_tree_root = if tree_input.include_file_details.unwrap_or(true) {
                    filtered_tree_root
                } else {
                    self.remove_file_details(&filtered_tree_root)
                };

                let result = json!({
                    "status": "success",
                    "repository_tree": final_tree_root,
                    "metadata": {
                        "total_files": final_tree_root.file_count,
                        "total_lines": final_tree_root.total_lines,
                        "languages": final_tree_root.languages.iter().collect::<Vec<_>>(),
                        "root_path": final_tree_root.path,
                        "include_file_details": tree_input.include_file_details.unwrap_or(true),
                        "max_depth": tree_input.max_depth
                    }
                });

                Ok(ToolResult::success(result))
            }
            None => {
                // Instead of returning an error, provide useful information about the empty repository
                let result = json!({
                    "status": "success",
                    "repository_tree": {
                        "name": "empty_repository",
                        "path": ".",
                        "children": [],
                        "file_count": 0,
                        "total_lines": 0,
                        "languages": []
                    },
                    "metadata": {
                        "total_files": file_count,
                        "total_lines": 0,
                        "languages": metadata.languages.iter().collect::<Vec<_>>(),
                        "root_path": ".",
                        "include_file_details": tree_input.include_file_details.unwrap_or(true),
                        "max_depth": tree_input.max_depth,
                        "note": "Repository is empty. Files need to be analyzed through the CLI scan command before they appear in the repository tree.",
                        "available_files": file_count
                    }
                });
                Ok(ToolResult::success(result))
            }
        }
    }

    /// Apply depth filtering to repository tree
    fn apply_depth_filter(
        &self,
        tree: &crate::storage::memory::DirectoryNode,
        max_depth: usize,
    ) -> crate::storage::memory::DirectoryNode {
        self.apply_depth_filter_recursive(tree, max_depth, 0)
    }

    fn apply_depth_filter_recursive(
        &self,
        node: &crate::storage::memory::DirectoryNode,
        max_depth: usize,
        current_depth: usize,
    ) -> crate::storage::memory::DirectoryNode {
        let mut filtered_node = crate::storage::memory::DirectoryNode {
            name: node.name.clone(),
            path: node.path.clone(),
            children: Vec::new(),
            file_count: 0,
            total_lines: 0,
            languages: std::collections::HashSet::new(),
        };

        if current_depth < max_depth {
            for child in &node.children {
                match child {
                    crate::storage::memory::RepositoryTreeNode::File(file_node) => {
                        filtered_node.children.push(
                            crate::storage::memory::RepositoryTreeNode::File(file_node.clone()),
                        );
                        filtered_node.file_count += 1;
                        filtered_node.total_lines += file_node.skeleton.line_count;
                        if !file_node.skeleton.language.is_empty() {
                            filtered_node
                                .languages
                                .insert(file_node.skeleton.language.clone());
                        }
                    }
                    crate::storage::memory::RepositoryTreeNode::Directory(dir_node) => {
                        let filtered_subdir = self.apply_depth_filter_recursive(
                            dir_node,
                            max_depth,
                            current_depth + 1,
                        );
                        filtered_node.file_count += filtered_subdir.file_count;
                        filtered_node.total_lines += filtered_subdir.total_lines;
                        for lang in &filtered_subdir.languages {
                            filtered_node.languages.insert(lang.clone());
                        }
                        filtered_node.children.push(
                            crate::storage::memory::RepositoryTreeNode::Directory(filtered_subdir),
                        );
                    }
                }
            }
        }

        filtered_node
    }

    /// Remove file details (skeletons) from tree to provide just structure
    fn remove_file_details(
        &self,
        tree: &crate::storage::memory::DirectoryNode,
    ) -> crate::storage::memory::DirectoryNode {
        let mut simplified_node = crate::storage::memory::DirectoryNode {
            name: tree.name.clone(),
            path: tree.path.clone(),
            children: Vec::new(),
            file_count: tree.file_count,
            total_lines: tree.total_lines,
            languages: tree.languages.clone(),
        };

        for child in &tree.children {
            match child {
                crate::storage::memory::RepositoryTreeNode::File(file_node) => {
                    // Create a simplified file node without detailed skeleton
                    let simplified_skeleton = crate::storage::memory::FileSkeleton {
                        path: file_node.skeleton.path.clone(),
                        language: file_node.skeleton.language.clone(),
                        size_bytes: file_node.skeleton.size_bytes,
                        line_count: file_node.skeleton.line_count,
                        functions: Vec::new(), // Remove function details
                        structs: Vec::new(),   // Remove struct details
                        imports: Vec::new(),   // Remove import details
                        exports: Vec::new(),   // Remove export details
                        is_public: file_node.skeleton.is_public,
                        is_test: file_node.skeleton.is_test,
                        last_modified: file_node.skeleton.last_modified,
                    };

                    let simplified_file = crate::storage::memory::FileNode {
                        name: file_node.name.clone(),
                        path: file_node.path.clone(),
                        skeleton: simplified_skeleton,
                    };

                    simplified_node.children.push(
                        crate::storage::memory::RepositoryTreeNode::File(simplified_file),
                    );
                }
                crate::storage::memory::RepositoryTreeNode::Directory(dir_node) => {
                    let simplified_subdir = self.remove_file_details(dir_node);
                    simplified_node.children.push(
                        crate::storage::memory::RepositoryTreeNode::Directory(simplified_subdir),
                    );
                }
            }
        }

        simplified_node
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResult {
    pub success: bool,
    pub data: Value,
    pub error: Option<String>,
}

impl ToolResult {
    pub fn success(data: Value) -> Self {
        Self {
            success: true,
            data,
            error: None,
        }
    }

    pub fn error(message: String) -> Self {
        Self {
            success: false,
            data: json!({}),
            error: Some(message),
        }
    }

    pub fn error_with_data(data: Value) -> Self {
        Self {
            success: false,
            data,
            error: None,
        }
    }
}

// Input types for tool functions
#[derive(Debug, Deserialize)]
struct SearchFunctionsInput {
    pattern: String,
    limit: Option<usize>,
    language: Option<String>,
}

#[derive(Debug, Deserialize)]
struct SearchStructsInput {
    pattern: String,
    limit: Option<usize>,
    language: Option<String>,
}

#[derive(Debug, Deserialize)]
struct AnalyzeFileInput {
    file_path: String,
    include_content: Option<bool>,
}

#[derive(Debug, Deserialize)]
struct GetDependenciesInput {
    file_path: String,
}

#[derive(Debug, Deserialize)]
struct FindCallersInput {
    function_name: String,
    limit: Option<usize>,
}

#[derive(Debug, Deserialize, Default)]
struct GetRepositoryTreeInput {
    include_file_details: Option<bool>,
    max_depth: Option<usize>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analyzers::registry::{DefaultLanguageRegistry, LanguageAnalyzerRegistry};
    use crate::analyzers::rust::RustAnalyzer;
    use crate::internal::config::FileScanningConfig;

    // Helper to create minimal test instances
    fn create_test_repo_map() -> Arc<Mutex<RepoMap>> {
        Arc::new(Mutex::new(RepoMap::new()))
    }

    // Build a registry handle with the Rust analyzer registered, mirroring the
    // default configuration used throughout the crate.
    fn create_test_registry() -> RegistryHandle {
        let mut registry = DefaultLanguageRegistry::new();
        registry
            .register(Box::new(RustAnalyzer::new().unwrap()))
            .unwrap();
        RegistryHandle::new(&registry)
    }

    fn create_mock_tools() -> LocalAnalysisTools {
        let repo_map = create_test_repo_map();
        LocalAnalysisTools::new(repo_map, create_test_registry())
    }

    // === Tool Schema Tests ===

    #[test]
    fn test_tool_schemas_creation() {
        let tools = create_mock_tools();
        let schemas = tools.get_tool_schemas();

        assert_eq!(schemas.len(), 6, "Should have exactly 6 tool schemas");

        let tool_names: Vec<_> = schemas.iter().map(|s| &s.name).collect();
        assert!(tool_names.contains(&&"search_functions".to_string()));
        assert!(tool_names.contains(&&"search_structs".to_string()));
        assert!(tool_names.contains(&&"analyze_file".to_string()));
        assert!(tool_names.contains(&&"get_dependencies".to_string()));
        assert!(tool_names.contains(&&"find_callers".to_string()));
        assert!(tool_names.contains(&&"get_repository_tree".to_string()));
    }

    #[test]
    fn test_tool_schemas_have_required_fields() {
        let tools = create_mock_tools();
        let schemas = tools.get_tool_schemas();

        for schema in schemas {
            assert!(!schema.name.is_empty(), "Tool name should not be empty");
            assert!(
                !schema.description.is_empty(),
                "Tool description should not be empty"
            );
            assert!(
                schema.input_schema.is_object(),
                "Input schema should be an object"
            );

            // Check that input schema has proper structure
            let input_schema = schema.input_schema.as_object().unwrap();
            assert_eq!(input_schema.get("type").unwrap(), "object");
            assert!(input_schema.contains_key("properties"));
        }
    }

    // === Search Functions Tests ===

    #[tokio::test]
    async fn test_search_functions_tool() {
        let tools = create_mock_tools();
        let input = json!({
            "pattern": "test_*",
            "limit": 10
        });

        let result = tools.execute_tool("search_functions", input).await.unwrap();
        assert!(result.success);
        assert_eq!(result.data["status"], "success");
        assert_eq!(result.data["pattern"], "test_*");
        assert!(result.data["count"].as_u64().unwrap() <= 10);
    }

    #[tokio::test]
    async fn test_search_functions_with_language_filter() {
        let tools = create_mock_tools();
        let input = json!({
            "pattern": "main",
            "limit": 5,
            "language": "rust"
        });

        let result = tools.execute_tool("search_functions", input).await.unwrap();
        assert!(result.success);
        assert_eq!(result.data["pattern"], "main");
        assert!(result.data["count"].as_u64().unwrap() <= 5);
    }

    #[tokio::test]
    async fn test_search_functions_minimal_input() {
        let tools = create_mock_tools();
        let input = json!({
            "pattern": ".*"
        });

        let result = tools.execute_tool("search_functions", input).await.unwrap();
        assert!(result.success);
        assert_eq!(result.data["pattern"], ".*");
        // Should use default limit of 20
        assert!(result.data["count"].as_u64().unwrap() <= 20);
    }

    // === Search Structs Tests ===

    #[tokio::test]
    async fn test_search_structs_tool() {
        let tools = create_mock_tools();
        let input = json!({
            "pattern": "Config*",
            "limit": 15
        });

        let result = tools.execute_tool("search_structs", input).await.unwrap();
        assert!(result.success);
        assert_eq!(result.data["status"], "success");
        assert_eq!(result.data["pattern"], "Config*");
        assert!(result.data["count"].as_u64().unwrap() <= 15);
    }

    #[tokio::test]
    async fn test_search_structs_with_language_filter() {
        let tools = create_mock_tools();
        let input = json!({
            "pattern": "Tool.*",
            "limit": 10,
            "language": "rust"
        });

        let result = tools.execute_tool("search_structs", input).await.unwrap();
        assert!(result.success);
        assert_eq!(result.data["pattern"], "Tool.*");
        assert!(result.data["count"].as_u64().unwrap() <= 10);
    }

    #[tokio::test]
    async fn test_search_structs_minimal_input() {
        let tools = create_mock_tools();
        let input = json!({
            "pattern": ".*Result"
        });

        let result = tools.execute_tool("search_structs", input).await.unwrap();
        assert!(result.success);
        assert_eq!(result.data["pattern"], ".*Result");
        // Should use default limit of 20
        assert!(result.data["count"].as_u64().unwrap() <= 20);
    }

    // === Analyze File Tests ===

    #[tokio::test]
    async fn test_analyze_file_with_nonexistent_file() {
        let tools = create_mock_tools();
        let input = json!({
            "file_path": "/nonexistent/file.rs",
            "include_content": false
        });

        let result = tools.execute_tool("analyze_file", input).await.unwrap();
        assert!(!result.success);
        assert_eq!(result.data["status"], "error");
        assert!(
            result.data["error"]
                .as_str()
                .unwrap()
                .contains("Failed to read file")
        );
    }

    #[tokio::test]
    async fn test_analyze_file_minimal_input() {
        let tools = create_mock_tools();
        let input = json!({
            "file_path": "/nonexistent/file.rs"
        });

        let result = tools.execute_tool("analyze_file", input).await.unwrap();
        assert!(!result.success); // Will fail because file doesn't exist
        assert_eq!(result.data["status"], "error");
    }

    #[tokio::test]
    async fn test_analyze_file_invalid_input() {
        let tools = create_mock_tools();
        let input = json!({
            "wrong_field": "value"
        });

        let result = tools.execute_tool("analyze_file", input).await;
        assert!(result.is_err());
    }

    // === Get Dependencies Tests ===

    #[tokio::test]
    async fn test_get_dependencies_tool() {
        let tools = create_mock_tools();
        let input = json!({
            "file_path": "src/main.rs"
        });

        let result = tools.execute_tool("get_dependencies", input).await.unwrap();
        assert!(result.success);
        assert_eq!(result.data["status"], "success");
        assert_eq!(result.data["file_path"], "src/main.rs");
        assert!(result.data.get("dependencies").is_some());
    }

    #[tokio::test]
    async fn test_get_dependencies_invalid_input() {
        let tools = create_mock_tools();
        let input = json!({
            "wrong_field": "value"
        });

        let result = tools.execute_tool("get_dependencies", input).await;
        assert!(result.is_err());
    }

    // === Find Callers Tests ===

    #[tokio::test]
    async fn test_find_callers_tool() {
        let tools = create_mock_tools();
        let input = json!({
            "function_name": "test_function",
            "limit": 25
        });

        let result = tools.execute_tool("find_callers", input).await.unwrap();
        assert!(result.success);
        assert_eq!(result.data["status"], "success");
        assert_eq!(result.data["function_name"], "test_function");
        assert!(result.data["count"].as_u64().unwrap() <= 25);
    }

    #[tokio::test]
    async fn test_find_callers_minimal_input() {
        let tools = create_mock_tools();
        let input = json!({
            "function_name": "main"
        });

        let result = tools.execute_tool("find_callers", input).await.unwrap();
        assert!(result.success);
        assert_eq!(result.data["function_name"], "main");
        // Should use default limit of 50
        assert!(result.data["count"].as_u64().unwrap() <= 50);
    }

    #[tokio::test]
    async fn test_find_callers_invalid_input() {
        let tools = create_mock_tools();
        let input = json!({
            "wrong_field": "value"
        });

        let result = tools.execute_tool("find_callers", input).await;
        assert!(result.is_err());
    }

    // === Repository Tree Tests ===

    #[tokio::test]
    async fn test_get_repository_tree_tool() {
        let tools = create_mock_tools();
        let input = json!({
            "include_file_details": true,
            "max_depth": 3
        });

        let result = tools
            .execute_tool("get_repository_tree", input)
            .await
            .unwrap();
        assert!(result.success);
        assert_eq!(result.data["status"], "success");
        assert!(result.data.get("repository_tree").is_some());
        assert!(result.data.get("metadata").is_some());

        let metadata = &result.data["metadata"];
        assert!(metadata.get("total_files").is_some());
        assert!(metadata.get("total_lines").is_some());
        assert!(metadata.get("languages").is_some());
        assert_eq!(metadata["max_depth"], 3);
        assert_eq!(metadata["include_file_details"], true);
    }

    #[tokio::test]
    async fn test_get_repository_tree_minimal_details() {
        let tools = create_mock_tools();
        let input = json!({
            "include_file_details": false
        });

        let result = tools
            .execute_tool("get_repository_tree", input)
            .await
            .unwrap();
        assert!(result.success);
        assert!(result.data.get("repository_tree").is_some());

        let metadata = &result.data["metadata"];
        assert_eq!(metadata["include_file_details"], false);
        // Since we're using simplified tree without details, the structure should be simpler
    }

    #[tokio::test]
    async fn test_get_repository_tree_empty_input() {
        let tools = create_mock_tools();
        let input = json!({});

        let result = tools
            .execute_tool("get_repository_tree", input)
            .await
            .unwrap();
        assert!(result.success);
        assert_eq!(result.data["status"], "success");
        assert!(result.data.get("repository_tree").is_some());
        assert!(result.data.get("metadata").is_some());

        let metadata = &result.data["metadata"];
        // Should use defaults: include_file_details = true, max_depth = None
        assert_eq!(metadata["include_file_details"], true);
        assert!(metadata["max_depth"].is_null());
    }

    // === Error Handling Tests ===

    #[tokio::test]
    async fn test_unknown_tool() {
        let tools = create_mock_tools();
        let input = json!({});

        let result = tools.execute_tool("unknown_tool", input).await.unwrap();
        assert!(!result.success);
        assert!(result.error.is_some());
        assert!(result.error.unwrap().contains("Unknown tool"));
    }

    #[tokio::test]
    async fn test_tool_execution_with_invalid_json() {
        let tools = create_mock_tools();

        // Test with malformed input for each tool that requires specific structure
        let test_cases = vec![
            ("search_functions", json!({"pattern": 123})), // pattern should be string
            ("search_structs", json!({"limit": "not_a_number"})), // limit should be number
            ("analyze_file", json!({"include_content": "not_a_bool"})), // include_content should be bool
        ];

        for (tool_name, invalid_input) in test_cases {
            let result = tools.execute_tool(tool_name, invalid_input).await;
            // These should either return an error or handle gracefully
            match result {
                Ok(tool_result) => {
                    // If it succeeds, it should either be an error result or handle the invalid input gracefully
                    if !tool_result.success {
                        // This is acceptable - the tool handled the invalid input gracefully
                    }
                }
                Err(_) => {
                    // This is also acceptable - the tool properly rejected invalid input
                }
            }
        }
    }

    #[tokio::test]
    async fn test_repository_tree_builds_with_scanned_files() {
        // Test that the repository tree tool properly builds the tree when files are present
        let repo_map = create_test_repo_map();
        let tools = LocalAnalysisTools::new(repo_map.clone(), create_test_registry());

        // Add some test files to the repo map
        {
            let mut map = repo_map.lock().unwrap();

            // Create a test file with functions and structs
            let mut tree_node =
                crate::types::TreeNode::new("/test/example.rs".to_string(), "rust".to_string());
            tree_node
                .functions
                .push(crate::types::FunctionSignature::new(
                    "test_function".to_string(),
                    "/test/example.rs".to_string(),
                ));
            tree_node.structs.push(crate::types::StructSignature::new(
                "TestStruct".to_string(),
                "/test/example.rs".to_string(),
            ));

            map.add_file(tree_node).unwrap();

            // Add another test file in a different directory
            let mut tree_node2 = crate::types::TreeNode::new(
                "/test/subdir/another.rs".to_string(),
                "rust".to_string(),
            );
            tree_node2
                .functions
                .push(crate::types::FunctionSignature::new(
                    "another_function".to_string(),
                    "/test/subdir/another.rs".to_string(),
                ));

            map.add_file(tree_node2).unwrap();

            // Verify files were added
            assert_eq!(map.file_count(), 2);
        }

        // Test the get_repository_tree tool
        let input = json!({
            "include_file_details": true
        });

        let result = tools
            .execute_tool("get_repository_tree", input)
            .await
            .unwrap();
        assert!(result.success);
        assert_eq!(result.data["status"], "success");

        // Verify that repository_tree is not the empty repository placeholder
        let repo_tree = &result.data["repository_tree"];
        assert_ne!(repo_tree["name"], "empty_repository");

        // Verify metadata shows the correct number of files
        let metadata = &result.data["metadata"];
        assert!(metadata["total_files"].as_u64().unwrap() > 0);

        // Verify that the note about empty repository is not present
        assert!(metadata.get("note").is_none());

        // Verify the repository tree structure is correct
        assert_eq!(metadata["root_path"], "/test");
        assert!(
            metadata["languages"]
                .as_array()
                .unwrap()
                .contains(&json!("rust"))
        );
    }

    // === ToolResult Tests ===

    #[test]
    fn test_tool_result_creation() {
        let success_result = ToolResult::success(json!({"key": "value"}));
        assert!(success_result.success);
        assert_eq!(success_result.data["key"], "value");
        assert!(success_result.error.is_none());

        let error_result = ToolResult::error("Test error".to_string());
        assert!(!error_result.success);
        assert!(error_result.error.is_some());
        assert_eq!(error_result.error.unwrap(), "Test error");
        assert_eq!(error_result.data, json!({}));

        let error_with_data = ToolResult::error_with_data(json!({"error_code": 404}));
        assert!(!error_with_data.success);
        assert!(error_with_data.error.is_none());
        assert_eq!(error_with_data.data["error_code"], 404);
    }

    // === Integration Tests ===

    #[tokio::test]
    async fn test_all_tools_execute_without_panic() {
        let tools = create_mock_tools();
        let tool_names = vec![
            "search_functions",
            "search_structs",
            "analyze_file",
            "get_dependencies",
            "find_callers",
            "get_repository_tree",
        ];

        for tool_name in tool_names {
            let minimal_input = match tool_name {
                "search_functions" => json!({"pattern": "test"}),
                "search_structs" => json!({"pattern": "Test"}),
                "analyze_file" => json!({"file_path": "/test.rs"}),
                "get_dependencies" => json!({"file_path": "/test.rs"}),
                "find_callers" => json!({"function_name": "test"}),
                "get_repository_tree" => json!({}),
                _ => json!({}),
            };

            let result = tools.execute_tool(tool_name, minimal_input).await;
            assert!(result.is_ok(), "Tool {} should not panic", tool_name);
        }
    }

    #[test]
    fn test_tool_schemas_json_validity() {
        let tools = create_mock_tools();
        let schemas = tools.get_tool_schemas();

        for schema in schemas {
            // Ensure the input schema is valid JSON
            let schema_str = serde_json::to_string(&schema.input_schema).unwrap();
            let _: Value = serde_json::from_str(&schema_str).unwrap();

            // Ensure we can serialize the schema (ToolSchema only implements Serialize, not Deserialize)
            let _serialized = serde_json::to_string(&schema).unwrap();
        }
    }
}