agcodex-core 0.1.0

Core business logic with AST-RAG engine and tree-sitter 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
//! Basic tests for AST-based agent tools
//!
//! This module provides foundational tests for the AST agent tools system.
//! As the AST tools are implemented, these tests can be expanded.

use super::CodeTool;
use super::ToolError;
use super::ast_agent_tools::*;
use std::io::Write;
use std::path::PathBuf;
use tempfile::NamedTempFile;

// Test fixtures
mod fixtures {
    use super::*;

    pub fn create_simple_rust_file() -> (NamedTempFile, String) {
        let mut file = NamedTempFile::new().unwrap();
        let content = r#"
pub struct Calculator {
    value: f64,
}

impl Calculator {
    pub fn new() -> Self {
        Self { value: 0.0 }
    }
    
    pub fn add(&mut self, x: f64) -> f64 {
        self.value += x;
        self.value
    }
    
    pub fn get_value(&self) -> f64 {
        self.value
    }
}

fn unused_function() {
    println!("This function is never called");
}
"#;
        file.write_all(content.as_bytes()).unwrap();
        (file, content.to_string())
    }
}

#[cfg(test)]
mod basic_tests {
    use super::fixtures::*;
    use super::*;

    #[tokio::test]
    async fn test_ast_agent_tools_creation() {
        let tools = ASTAgentTools::new();

        // Test that the tools can be created successfully
        // Note: Internal fields are private, just verify the tools object exists
        let _ = tools;
    }

    #[tokio::test]
    async fn test_ast_tools_with_simple_rust() {
        let tools = ASTAgentTools::new();
        let (file, _content) = create_simple_rust_file();
        let file_path = PathBuf::from(file.path());

        // Test basic functionality - this will need to be updated as the tools are implemented
        // For now, just test that the tools don't crash on valid Rust code

        // Test extract functions operation (when implemented)
        let op = AgentToolOp::ExtractFunctions {
            file: file_path.clone(),
            language: "rust".to_string(),
        };

        let result = tools.search(op);

        // The result might be an error if not implemented yet, but it shouldn't panic
        match result {
            Ok(AgentToolResult::FunctionList(functions)) => {
                // If implemented, verify we get reasonable results
                println!("Extracted {} functions", functions.len());

                // Look for expected functions
                let function_names: Vec<&str> = functions.iter().map(|f| f.name.as_str()).collect();
                println!("Function names: {:?}", function_names);

                // Check if we have any functions at all
                if !functions.is_empty() {
                    // Currently using stub implementation that returns "example_function"
                    // When real implementation is added, it should find: new, add, get_value, unused_function
                    if function_names.contains(&"example_function") {
                        // Stub implementation - just verify it returns something
                        println!("Note: Using stub implementation, found placeholder function");
                        assert_eq!(functions.len(), 1);
                        assert_eq!(functions[0].name, "example_function");
                    } else {
                        // Real implementation should find actual functions from the test file
                        assert!(
                            function_names.contains(&"new")
                                || function_names.contains(&"add")
                                || function_names.contains(&"get_value")
                                || function_names.contains(&"unused_function"),
                            "Expected to find at least one known function, but got: {:?}",
                            function_names
                        );
                    }
                }
            }
            Err(ToolError::NotImplemented(_)) => {
                // Not yet implemented - that's fine for now
                println!("Extract functions not yet implemented");
            }
            Err(e) => {
                panic!("Unexpected error: {:?}", e);
            }
            _ => {
                panic!("Unexpected result type");
            }
        }
    }

    #[tokio::test]
    async fn test_ast_tools_error_handling() {
        let tools = ASTAgentTools::new();

        // Test with nonexistent file
        let nonexistent_file = PathBuf::from("/nonexistent/file.rs");
        let op = AgentToolOp::ExtractFunctions {
            file: nonexistent_file,
            language: "rust".to_string(),
        };

        let result = tools.search(op);

        // Should handle the error gracefully
        assert!(result.is_err());

        match result.unwrap_err() {
            ToolError::Io(_) => {
                // Expected - file doesn't exist
            }
            ToolError::NotImplemented(_) => {
                // Also acceptable if not implemented
            }
            ToolError::InvalidQuery(_) => {
                // Also acceptable
            }
            e => {
                println!("Got error (acceptable): {:?}", e);
            }
        }
    }

    #[tokio::test]
    async fn test_ast_tools_language_detection() {
        let tools = ASTAgentTools::new();
        let (file, _content) = create_simple_rust_file();
        let file_path = PathBuf::from(file.path());

        // Test with different language strings
        let languages = vec!["rust", "rs", "Rust", "RUST"];

        for lang in languages {
            let op = AgentToolOp::ExtractFunctions {
                file: file_path.clone(),
                language: lang.to_string(),
            };

            let result = tools.search(op);

            // Should not panic regardless of implementation status
            match result {
                Ok(_) => {
                    // Good - language was recognized
                }
                Err(ToolError::NotImplemented(_)) => {
                    // Acceptable - not implemented yet
                }
                Err(ToolError::UnsupportedLanguage(_)) => {
                    // Acceptable - language not supported yet
                }
                Err(e) => {
                    // Other errors are also acceptable at this stage
                    println!("Language '{}' resulted in error: {:?}", lang, e);
                }
            }
        }
    }

    #[tokio::test]
    async fn test_multiple_operations() {
        let tools = ASTAgentTools::new();
        let (file, _content) = create_simple_rust_file();
        let file_path = PathBuf::from(file.path());

        let operations = vec![
            AgentToolOp::ExtractFunctions {
                file: file_path.clone(),
                language: "rust".to_string(),
            },
            AgentToolOp::ValidateSyntax {
                file: file_path.clone(),
                language: "rust".to_string(),
            },
        ];

        for op in operations {
            let result = tools.search(op);

            // None of these should panic
            match result {
                Ok(_) => {
                    // Success
                }
                Err(e) => {
                    // Error is acceptable
                    println!("Operation resulted in error (acceptable): {:?}", e);
                }
            }
        }
    }
}

#[cfg(test)]
mod performance_tests {
    use super::fixtures::*;
    use super::*;

    #[tokio::test]
    async fn test_concurrent_access() {
        let tools = std::sync::Arc::new(ASTAgentTools::new());
        let (file, _content) = create_simple_rust_file();
        let file_path = std::sync::Arc::new(PathBuf::from(file.path()));

        let mut handles = vec![];

        // Spawn multiple concurrent tasks
        for i in 0..5 {
            let tools_clone = std::sync::Arc::clone(&tools);
            let file_path_clone = std::sync::Arc::clone(&file_path);

            let handle = tokio::spawn(async move {
                let op = AgentToolOp::ExtractFunctions {
                    file: (*file_path_clone).clone(),
                    language: "rust".to_string(),
                };

                let result = tools_clone.search(op);

                // Should not panic
                match result {
                    Ok(_) => format!("Task {} succeeded", i),
                    Err(e) => format!("Task {} failed with: {:?}", i, e),
                }
            });

            handles.push(handle);
        }

        // Wait for all tasks to complete
        let results = futures::future::join_all(handles).await;

        // All tasks should complete without panicking
        for (i, result) in results.into_iter().enumerate() {
            match result {
                Ok(message) => {
                    println!("Task {}: {}", i, message);
                }
                Err(e) => {
                    panic!("Task {} panicked: {:?}", i, e);
                }
            }
        }
    }

    #[tokio::test]
    async fn test_large_file_handling() {
        let tools = ASTAgentTools::new();

        // Create a larger file
        let mut file = NamedTempFile::new().unwrap();
        let mut content = String::new();

        // Generate multiple similar functions
        for i in 0..50 {
            content.push_str(&format!(
                r#"
pub fn function_{i}(x: i32) -> i32 {{
    let result = x * 2;
    result + {i}
}}
"#,
                i = i
            ));
        }

        file.write_all(content.as_bytes()).unwrap();
        let file_path = PathBuf::from(file.path());

        let start = std::time::Instant::now();

        let op = AgentToolOp::ExtractFunctions {
            file: file_path,
            language: "rust".to_string(),
        };

        let _result = tools.search(op);

        let duration = start.elapsed();

        // Should complete within reasonable time (even if it fails)
        assert!(duration < std::time::Duration::from_secs(5));

        println!("Large file processing took: {:?}", duration);
    }
}

#[cfg(test)]
mod integration_tests {
    use super::fixtures::*;
    use super::*;

    #[tokio::test]
    async fn test_ast_tools_code_tool_trait() {
        let tools = ASTAgentTools::new();
        let (file, _content) = create_simple_rust_file();
        let file_path = PathBuf::from(file.path());

        // Test that AST tools implement the CodeTool trait correctly
        let query = AgentToolOp::ExtractFunctions {
            file: file_path,
            language: "rust".to_string(),
        };

        // This should compile and not panic
        let _result = <ASTAgentTools as CodeTool>::search(&tools, query);

        // Result content doesn't matter for this test - just that the trait works
    }

    #[tokio::test]
    async fn test_tool_error_conversion() {
        // Test that various error types can be created and converted properly
        let errors = vec![
            ToolError::NotImplemented("test operation"),
            ToolError::InvalidQuery("invalid query".to_string()),
            ToolError::ParseError("parse failed".to_string()),
            ToolError::NotFound("symbol not found".to_string()),
            ToolError::UnsupportedLanguage("unknown_lang".to_string()),
        ];

        for error in errors {
            let error_string = error.to_string();
            assert!(!error_string.is_empty());

            // Test that error implements required traits
            let _: Box<dyn std::error::Error> = Box::new(error);
        }
    }
}

// Module to test that the basic AST structure compiles
#[cfg(test)]
mod structure_tests {
    use super::*;

    #[test]
    fn test_semantic_index_creation() {
        let index = SemanticIndex {
            functions: vec![],
            classes: vec![],
            imports: vec![],
            exports: vec![],
            symbols: vec![],
            call_graph: CallGraph {
                nodes: vec![],
                edges: vec![],
            },
        };

        assert_eq!(index.functions.len(), 0);
        assert_eq!(index.classes.len(), 0);
        assert_eq!(index.symbols.len(), 0);
    }

    #[test]
    fn test_function_info_creation() {
        let func_info = FunctionInfo {
            name: "test_function".to_string(),
            signature: "fn test_function() -> bool".to_string(),
            parameters: vec!["param1".to_string(), "param2".to_string()],
            start_line: 10,
            end_line: 15,
            complexity: 3,
            is_exported: true,
        };

        assert_eq!(func_info.name, "test_function");
        assert_eq!(func_info.complexity, 3);
        assert_eq!(func_info.parameters.len(), 2);
        assert!(func_info.is_exported);
    }

    #[test]
    fn test_symbol_info_creation() {
        let symbol_types = vec![
            "function",
            "class",
            "variable",
            "constant",
            "type",
            "interface",
            "enum",
            "module",
            "namespace",
        ];

        // Test that all symbol types can be created
        for symbol_type in symbol_types {
            let symbol_info = SymbolInfo {
                name: "test_symbol".to_string(),
                symbol_type: symbol_type.to_string(),
                line: 1,
                column: 1,
                scope: "global".to_string(),
            };

            assert_eq!(symbol_info.name, "test_symbol");
            assert_eq!(symbol_info.line, 1);
            assert_eq!(symbol_info.scope, "global");
        }
    }
}