coderlib 0.1.0

A Rust library for AI-powered code assistance and agentic system
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
//! Fast file pattern matching tool

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use tokio::fs;

use crate::integration::HostIntegration;
use crate::tools::{Tool, ToolError, ToolResponse, Permission};

/// Fast file pattern matching tool
pub struct GlobTool;

/// Parameters for the glob tool
#[derive(Debug, Deserialize)]
struct GlobParams {
    /// Glob pattern to match against file paths
    pattern: String,
    /// Starting directory (default: current working directory)
    path: Option<PathBuf>,
    /// Maximum number of results to return (default: 100)
    limit: Option<usize>,
    /// Whether to include hidden files (default: false)
    include_hidden: Option<bool>,
    /// Whether to follow symbolic links (default: false)
    follow_symlinks: Option<bool>,
    /// File type filter: "file", "dir", or "any" (default: "any")
    file_type: Option<String>,
}

/// Glob operation metadata
#[derive(Debug, Serialize)]
struct GlobMetadata {
    /// Pattern used for matching
    pattern: String,
    /// Search directory
    search_path: String,
    /// Total matches found
    total_matches: usize,
    /// Whether results were truncated
    truncated: bool,
    /// Search time in milliseconds
    search_time_ms: u64,
    /// File type filter applied
    file_type_filter: String,
}

/// File match result
#[derive(Debug, Serialize)]
struct FileMatch {
    /// File path relative to search directory
    path: String,
    /// File type: "file" or "directory"
    file_type: String,
    /// File size in bytes (for files)
    size: Option<u64>,
    /// Last modified time (Unix timestamp)
    modified: Option<u64>,
}

impl GlobTool {
    /// Create a new glob tool
    pub fn new() -> Self {
        Self
    }
    
    /// Find files matching the glob pattern
    async fn find_matches(&self, params: &GlobParams) -> Result<(Vec<FileMatch>, GlobMetadata), ToolError> {
        let start_time = std::time::Instant::now();
        
        // Validate pattern
        if params.pattern.trim().is_empty() {
            return Err(ToolError::InvalidParameters("pattern is required".to_string()));
        }
        
        // Get search path
        let search_path = params.path.as_ref()
            .map(|p| p.clone())
            .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
        
        // Validate search path exists
        if !search_path.exists() {
            return Err(ToolError::ExecutionFailed(format!(
                "Search path does not exist: {}", search_path.display()
            )));
        }
        
        let limit = params.limit.unwrap_or(100);
        let include_hidden = params.include_hidden.unwrap_or(false);
        let follow_symlinks = params.follow_symlinks.unwrap_or(false);
        let file_type_filter = params.file_type.as_deref().unwrap_or("any");
        
        // Validate file type filter
        if !["file", "dir", "any"].contains(&file_type_filter) {
            return Err(ToolError::InvalidParameters(format!(
                "Invalid file_type '{}'. Must be 'file', 'dir', or 'any'", file_type_filter
            )));
        }
        
        // Compile glob pattern
        let glob_pattern = glob::Pattern::new(&params.pattern)
            .map_err(|e| ToolError::InvalidParameters(format!("Invalid glob pattern: {}", e)))?;
        
        // Find matching files
        let mut matches = Vec::new();
        let mut total_found = 0;
        
        self.search_directory(
            &search_path,
            &search_path,
            &glob_pattern,
            &mut matches,
            &mut total_found,
            limit,
            include_hidden,
            follow_symlinks,
            file_type_filter,
        ).await?;
        
        // Sort by modification time (newest first)
        matches.sort_by(|a, b| {
            b.modified.unwrap_or(0).cmp(&a.modified.unwrap_or(0))
        });
        
        let search_time = start_time.elapsed();
        let truncated = total_found > limit;
        
        let metadata = GlobMetadata {
            pattern: params.pattern.clone(),
            search_path: search_path.display().to_string(),
            total_matches: total_found,
            truncated,
            search_time_ms: search_time.as_millis() as u64,
            file_type_filter: file_type_filter.to_string(),
        };
        
        Ok((matches, metadata))
    }
    
    /// Recursively search directory for matches
    #[async_recursion::async_recursion]
    async fn search_directory(
        &self,
        current_dir: &Path,
        base_dir: &Path,
        pattern: &glob::Pattern,
        matches: &mut Vec<FileMatch>,
        total_found: &mut usize,
        limit: usize,
        include_hidden: bool,
        follow_symlinks: bool,
        file_type_filter: &str,
    ) -> Result<(), ToolError> {
        if matches.len() >= limit {
            return Ok(());
        }
        
        let mut entries = fs::read_dir(current_dir).await
            .map_err(|e| ToolError::ExecutionFailed(format!("Failed to read directory {}: {}", current_dir.display(), e)))?;
        
        while let Some(entry) = entries.next_entry().await
            .map_err(|e| ToolError::ExecutionFailed(format!("Failed to read directory entry: {}", e)))? {
            
            if matches.len() >= limit {
                break;
            }
            
            let path = entry.path();
            let file_name = path.file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("");
            
            // Skip hidden files if not requested
            if !include_hidden && file_name.starts_with('.') {
                continue;
            }
            
            // Get file metadata
            let metadata = if follow_symlinks {
                fs::metadata(&path).await
            } else {
                fs::symlink_metadata(&path).await
            };
            
            let metadata = match metadata {
                Ok(m) => m,
                Err(_) => continue, // Skip files we can't read
            };
            
            let is_dir = metadata.is_dir();
            let is_file = metadata.is_file();
            
            // Apply file type filter
            let matches_filter = match file_type_filter {
                "file" => is_file,
                "dir" => is_dir,
                "any" => true,
                _ => true,
            };
            
            if !matches_filter {
                if is_dir {
                    // Still recurse into directories even if we're not matching them
                    self.search_directory(
                        &path,
                        base_dir,
                        pattern,
                        matches,
                        total_found,
                        limit,
                        include_hidden,
                        follow_symlinks,
                        file_type_filter,
                    ).await?;
                }
                continue;
            }
            
            // Get relative path for pattern matching
            let relative_path = path.strip_prefix(base_dir)
                .unwrap_or(&path)
                .to_string_lossy();
            
            // Check if path matches pattern
            if pattern.matches(&relative_path) {
                *total_found += 1;
                
                if matches.len() < limit {
                    let file_match = FileMatch {
                        path: relative_path.to_string(),
                        file_type: if is_dir { "directory" } else { "file" }.to_string(),
                        size: if is_file { Some(metadata.len()) } else { None },
                        modified: metadata.modified()
                            .ok()
                            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                            .map(|d| d.as_secs()),
                    };
                    matches.push(file_match);
                }
            }
            
            // Recurse into directories
            if is_dir {
                self.search_directory(
                    &path,
                    base_dir,
                    pattern,
                    matches,
                    total_found,
                    limit,
                    include_hidden,
                    follow_symlinks,
                    file_type_filter,
                ).await?;
            }
        }
        
        Ok(())
    }
    
    /// Format the glob response
    fn format_response(&self, matches: &[FileMatch], metadata: &GlobMetadata) -> String {
        let mut response = String::new();
        
        response.push_str(&format!("Found {} file(s) matching pattern '{}'\n", 
            metadata.total_matches, metadata.pattern));
        response.push_str(&format!("Search path: {}\n", metadata.search_path));
        response.push_str(&format!("Search time: {}ms\n", metadata.search_time_ms));
        
        if metadata.truncated {
            response.push_str(&format!("Results truncated to {} items\n", matches.len()));
        }
        
        if !matches.is_empty() {
            response.push_str("\nMatches (sorted by modification time, newest first):\n");
            for (i, file_match) in matches.iter().enumerate() {
                response.push_str(&format!("{}. {} ({})", 
                    i + 1, file_match.path, file_match.file_type));
                
                if let Some(size) = file_match.size {
                    response.push_str(&format!(", {} bytes", size));
                }
                
                if let Some(modified) = file_match.modified {
                    let datetime = chrono::DateTime::from_timestamp(modified as i64, 0)
                        .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
                        .unwrap_or_else(|| "unknown".to_string());
                    response.push_str(&format!(", modified: {}", datetime));
                }
                
                response.push('\n');
            }
        } else {
            response.push_str("\nNo matches found.\n");
        }
        
        // Add pattern syntax help if no matches
        if matches.is_empty() {
            response.push_str("\nGlob pattern syntax:\n");
            response.push_str("  * - matches any sequence of characters\n");
            response.push_str("  ? - matches any single character\n");
            response.push_str("  [abc] - matches any character in brackets\n");
            response.push_str("  **/ - matches directories recursively\n");
            response.push_str("  Examples: *.rs, **/*.py, src/**/test_*.rs\n");
        }
        
        response
    }
}

impl Default for GlobTool {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Tool for GlobTool {
    async fn execute(
        &self,
        parameters: serde_json::Value,
        _host: &dyn HostIntegration,
    ) -> Result<ToolResponse, ToolError> {
        let params: GlobParams = serde_json::from_value(parameters)
            .map_err(|e| ToolError::InvalidParameters(format!("Invalid parameters: {}", e)))?;

        // Find matches
        let (matches, metadata) = self.find_matches(&params).await?;

        let response_content = self.format_response(&matches, &metadata);
        let metadata_json = serde_json::to_value(&metadata)
            .unwrap_or(serde_json::Value::Null);

        Ok(ToolResponse {
            content: response_content,
            success: true,
            metadata: metadata_json,
            affected_files: Vec::new(), // No files affected by glob search
        })
    }

    fn name(&self) -> &str {
        "glob"
    }

    fn description(&self) -> &str {
        "Fast file pattern matching tool that finds files by name and pattern, returning matching paths sorted by modification time (newest first)."
    }

    fn requires_permission(&self) -> Permission {
        Permission::ReadFile(PathBuf::from(".")) // Requires read access to search directories
    }

    fn parameter_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "pattern": {
                    "type": "string",
                    "description": "Glob pattern to match against file paths (e.g., '*.rs', '**/*.py', 'src/**/test_*.rs')"
                },
                "path": {
                    "type": "string",
                    "description": "Starting directory for search (default: current working directory)"
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum number of results to return (default: 100)",
                    "default": 100,
                    "minimum": 1,
                    "maximum": 1000
                },
                "include_hidden": {
                    "type": "boolean",
                    "description": "Whether to include hidden files (starting with '.') (default: false)",
                    "default": false
                },
                "follow_symlinks": {
                    "type": "boolean",
                    "description": "Whether to follow symbolic links (default: false)",
                    "default": false
                },
                "file_type": {
                    "type": "string",
                    "description": "File type filter: 'file', 'dir', or 'any' (default: 'any')",
                    "enum": ["file", "dir", "any"],
                    "default": "any"
                }
            },
            "required": ["pattern"]
        })
    }

    fn clone_box(&self) -> Box<dyn Tool> {
        Box::new(Self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;
    use tokio::fs;

    #[tokio::test]
    async fn test_glob_tool_creation() {
        let tool = GlobTool::new();
        assert_eq!(tool.name(), "glob");
        assert!(!tool.description().is_empty());
    }

    #[tokio::test]
    async fn test_glob_pattern_matching() {
        let temp_dir = TempDir::new().unwrap();
        let base_path = temp_dir.path();

        // Create test files
        fs::write(base_path.join("test.rs"), "// Rust file").await.unwrap();
        fs::write(base_path.join("test.py"), "# Python file").await.unwrap();
        fs::write(base_path.join("README.md"), "# Readme").await.unwrap();

        let tool = GlobTool::new();
        let params = serde_json::json!({
            "pattern": "*.rs",
            "path": base_path
        });

        let result = tool.execute(params, &crate::integration::MockHost).await.unwrap();
        assert!(result.success);
        assert!(result.content.contains("test.rs"));
        assert!(!result.content.contains("test.py"));
    }

    #[tokio::test]
    async fn test_glob_recursive_pattern() {
        let temp_dir = TempDir::new().unwrap();
        let base_path = temp_dir.path();

        // Create nested directory structure
        let src_dir = base_path.join("src");
        fs::create_dir(&src_dir).await.unwrap();
        fs::write(src_dir.join("main.rs"), "fn main() {}").await.unwrap();

        let tests_dir = base_path.join("tests");
        fs::create_dir(&tests_dir).await.unwrap();
        fs::write(tests_dir.join("test_main.rs"), "#[test] fn test() {}").await.unwrap();

        let tool = GlobTool::new();
        let params = serde_json::json!({
            "pattern": "**/*.rs",
            "path": base_path
        });

        let result = tool.execute(params, &crate::integration::MockHost).await.unwrap();
        assert!(result.success);

        // Check for main.rs and test_main.rs files (path separators may vary by OS)
        assert!(result.content.contains("main.rs"), "Expected to find main.rs in: {}", result.content);
        assert!(result.content.contains("test_main.rs"), "Expected to find test_main.rs in: {}", result.content);
    }

    #[tokio::test]
    async fn test_glob_file_type_filter() {
        let temp_dir = TempDir::new().unwrap();
        let base_path = temp_dir.path();

        // Create files and directories
        fs::write(base_path.join("file.txt"), "content").await.unwrap();
        fs::create_dir(base_path.join("subdir")).await.unwrap();

        let tool = GlobTool::new();

        // Test file filter
        let params = serde_json::json!({
            "pattern": "*",
            "path": base_path,
            "file_type": "file"
        });

        let result = tool.execute(params, &crate::integration::MockHost).await.unwrap();
        assert!(result.success);
        assert!(result.content.contains("file.txt"));
        assert!(!result.content.contains("subdir"));

        // Test directory filter
        let params = serde_json::json!({
            "pattern": "*",
            "path": base_path,
            "file_type": "dir"
        });

        let result = tool.execute(params, &crate::integration::MockHost).await.unwrap();
        assert!(result.success);
        assert!(!result.content.contains("file.txt"));
        assert!(result.content.contains("subdir"));
    }
}