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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! Git-style patch application tool

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

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

/// Patch application tool
pub struct PatchTool {
    lsp_service: Option<Arc<dyn LspService>>,
}

/// Parameters for the patch tool
#[derive(Debug, Deserialize)]
struct PatchParams {
    /// Patch content in unified diff format
    patch_text: String,
    /// Whether to validate with LSP after applying patch
    validate_with_lsp: Option<bool>,
    /// Maximum fuzz level to allow (default: 3)
    max_fuzz: Option<u32>,
    /// Whether to create parent directories if they don't exist
    create_dirs: Option<bool>,
}

/// Patch operation metadata
#[derive(Debug, Serialize)]
struct PatchMetadata {
    /// Files that were modified
    modified_files: Vec<String>,
    /// Files that were created
    created_files: Vec<String>,
    /// Files that were deleted
    deleted_files: Vec<String>,
    /// Total lines added
    total_additions: usize,
    /// Total lines removed
    total_removals: usize,
    /// Fuzz level used
    fuzz_level: u32,
    /// LSP diagnostics for modified files
    diagnostics: HashMap<String, Vec<LspDiagnostic>>,
}

/// Represents a single file change in a patch
#[derive(Debug)]
struct FileChange {
    /// Type of change
    change_type: ChangeType,
    /// Original file content (for updates and deletions)
    old_content: Option<String>,
    /// New file content (for updates and creations)
    new_content: Option<String>,
}

/// Type of file change
#[derive(Debug)]
enum ChangeType {
    Create,
    Update,
    Delete,
}

/// Parsed patch information
#[derive(Debug)]
struct ParsedPatch {
    /// Map of file paths to their changes
    changes: HashMap<PathBuf, FileChange>,
    /// Fuzz level required for this patch
    fuzz_level: u32,
}

impl PatchTool {
    /// Create a new patch tool
    pub fn new() -> Self {
        Self {
            lsp_service: None,
        }
    }
    
    /// Set the LSP service for this tool
    pub fn set_lsp_service(&mut self, lsp_service: Arc<dyn LspService>) {
        self.lsp_service = Some(lsp_service);
    }
    
    /// Parse a unified diff patch
    fn parse_patch(&self, patch_text: &str) -> Result<ParsedPatch, ToolError> {
        let mut changes = HashMap::new();
        let mut current_file: Option<PathBuf> = None;
        let mut old_content = String::new();
        let mut new_content = String::new();
        let mut in_hunk = false;
        let fuzz_level = 0;
        
        for line in patch_text.lines() {
            if line.starts_with("--- ") {
                // Save previous file if any
                if let Some(file_path) = current_file.take() {
                    self.finalize_file_change(&mut changes, file_path, &old_content, &new_content)?;
                }
                
                // Start new file
                let file_path = line.strip_prefix("--- ").unwrap_or("");
                if file_path != "/dev/null" {
                    current_file = Some(PathBuf::from(file_path));
                    old_content.clear();
                    new_content.clear();
                }
                in_hunk = false;
            } else if line.starts_with("+++ ") {
                let file_path = line.strip_prefix("+++ ").unwrap_or("");
                if file_path != "/dev/null" && current_file.is_none() {
                    current_file = Some(PathBuf::from(file_path));
                }
            } else if line.starts_with("@@") {
                in_hunk = true;
            } else if in_hunk {
                if line.starts_with('-') {
                    old_content.push_str(&line[1..]);
                    old_content.push('\n');
                } else if line.starts_with('+') {
                    new_content.push_str(&line[1..]);
                    new_content.push('\n');
                } else if line.starts_with(' ') {
                    // Context line
                    old_content.push_str(&line[1..]);
                    old_content.push('\n');
                    new_content.push_str(&line[1..]);
                    new_content.push('\n');
                }
            }
        }
        
        // Finalize last file
        if let Some(file_path) = current_file {
            self.finalize_file_change(&mut changes, file_path, &old_content, &new_content)?;
        }
        
        Ok(ParsedPatch {
            changes,
            fuzz_level,
        })
    }
    
    /// Finalize a file change and add it to the changes map
    fn finalize_file_change(
        &self,
        changes: &mut HashMap<PathBuf, FileChange>,
        file_path: PathBuf,
        old_content: &str,
        new_content: &str,
    ) -> Result<(), ToolError> {
        let change_type = if old_content.is_empty() {
            ChangeType::Create
        } else if new_content.is_empty() {
            ChangeType::Delete
        } else {
            ChangeType::Update
        };
        
        let change = FileChange {
            change_type,
            old_content: if old_content.is_empty() { None } else { Some(old_content.to_string()) },
            new_content: if new_content.is_empty() { None } else { Some(new_content.to_string()) },
        };
        
        changes.insert(file_path, change);
        Ok(())
    }
    
    /// Apply a parsed patch to the filesystem
    async fn apply_patch(&self, patch: ParsedPatch, create_dirs: bool) -> Result<PatchMetadata, ToolError> {
        let mut metadata = PatchMetadata {
            modified_files: Vec::new(),
            created_files: Vec::new(),
            deleted_files: Vec::new(),
            total_additions: 0,
            total_removals: 0,
            fuzz_level: patch.fuzz_level,
            diagnostics: HashMap::new(),
        };
        
        // Apply all changes
        for (file_path, change) in patch.changes {
            match change.change_type {
                ChangeType::Create => {
                    if let Some(content) = &change.new_content {
                        // Create parent directories if needed
                        if create_dirs {
                            if let Some(parent) = file_path.parent() {
                                fs::create_dir_all(parent).await
                                    .map_err(|e| ToolError::ExecutionFailed(format!("Failed to create directories: {}", e)))?;
                            }
                        }
                        
                        fs::write(&file_path, content).await
                            .map_err(|e| ToolError::ExecutionFailed(format!("Failed to create file {}: {}", file_path.display(), e)))?;
                        
                        metadata.created_files.push(file_path.display().to_string());
                        metadata.total_additions += content.lines().count();
                    }
                }
                ChangeType::Update => {
                    if let Some(content) = &change.new_content {
                        let old_content = fs::read_to_string(&file_path).await
                            .map_err(|e| ToolError::ExecutionFailed(format!("Failed to read file {}: {}", file_path.display(), e)))?;
                        
                        fs::write(&file_path, content).await
                            .map_err(|e| ToolError::ExecutionFailed(format!("Failed to update file {}: {}", file_path.display(), e)))?;
                        
                        metadata.modified_files.push(file_path.display().to_string());
                        metadata.total_additions += content.lines().count();
                        metadata.total_removals += old_content.lines().count();
                    }
                }
                ChangeType::Delete => {
                    fs::remove_file(&file_path).await
                        .map_err(|e| ToolError::ExecutionFailed(format!("Failed to delete file {}: {}", file_path.display(), e)))?;
                    
                    metadata.deleted_files.push(file_path.display().to_string());
                    if let Some(old_content) = &change.old_content {
                        metadata.total_removals += old_content.lines().count();
                    }
                }
            }
        }
        
        Ok(metadata)
    }
    
    /// Get LSP diagnostics for modified files
    async fn get_diagnostics(&self, file_paths: &[String]) -> HashMap<String, Vec<LspDiagnostic>> {
        let mut diagnostics = HashMap::new();
        
        if let Some(lsp) = &self.lsp_service {
            for file_path_str in file_paths {
                let file_path = Path::new(file_path_str);
                if lsp.supports_file(file_path) {
                    // Wait a bit for LSP to process the file
                    tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
                    
                    match lsp.get_diagnostics(file_path).await {
                        Ok(file_diagnostics) => {
                            if !file_diagnostics.is_empty() {
                                diagnostics.insert(file_path_str.clone(), file_diagnostics);
                            }
                        }
                        Err(_) => {} // Ignore LSP errors
                    }
                    
                    // Notify LSP of file change
                    if let Ok(content) = fs::read_to_string(file_path).await {
                        let _ = lsp.did_change_file(file_path, &content).await;
                    }
                }
            }
        }
        
        diagnostics
    }
    
    /// Format the patch response
    fn format_response(&self, metadata: &PatchMetadata) -> String {
        let mut response = String::new();
        
        response.push_str("Patch applied successfully!\n\n");
        
        // Summary
        let total_files = metadata.created_files.len() + metadata.modified_files.len() + metadata.deleted_files.len();
        response.push_str(&format!("Files affected: {}\n", total_files));
        response.push_str(&format!("Changes: +{} lines, -{} lines\n", metadata.total_additions, metadata.total_removals));
        
        if metadata.fuzz_level > 0 {
            response.push_str(&format!("Fuzz level: {}\n", metadata.fuzz_level));
        }
        
        // File details
        if !metadata.created_files.is_empty() {
            response.push_str(&format!("\nCreated files ({}):\n", metadata.created_files.len()));
            for file in &metadata.created_files {
                response.push_str(&format!("  + {}\n", file));
            }
        }
        
        if !metadata.modified_files.is_empty() {
            response.push_str(&format!("\nModified files ({}):\n", metadata.modified_files.len()));
            for file in &metadata.modified_files {
                response.push_str(&format!("  ~ {}\n", file));
            }
        }
        
        if !metadata.deleted_files.is_empty() {
            response.push_str(&format!("\nDeleted files ({}):\n", metadata.deleted_files.len()));
            for file in &metadata.deleted_files {
                response.push_str(&format!("  - {}\n", file));
            }
        }
        
        // LSP diagnostics
        if !metadata.diagnostics.is_empty() {
            response.push_str("\nLSP Diagnostics:\n");
            for (file, diagnostics) in &metadata.diagnostics {
                response.push_str(&format!("  {}:\n", file));
                for diagnostic in diagnostics {
                    response.push_str(&format!("    {}: {} (line {})\n",
                        diagnostic.severity, diagnostic.message, diagnostic.line + 1));
                }
            }
        }
        
        response
    }
}

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

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

        // Validate patch text
        if params.patch_text.trim().is_empty() {
            return Err(ToolError::InvalidParameters("patch_text is required".to_string()));
        }

        let validate_with_lsp = params.validate_with_lsp.unwrap_or(true);
        let max_fuzz = params.max_fuzz.unwrap_or(3);
        let create_dirs = params.create_dirs.unwrap_or(false);

        // Parse the patch
        let patch = self.parse_patch(&params.patch_text)?;

        // Check fuzz level
        if patch.fuzz_level > max_fuzz {
            return Err(ToolError::ExecutionFailed(format!(
                "Patch contains fuzzy matches (fuzz level: {}). Maximum allowed: {}. Please make your context lines more precise.",
                patch.fuzz_level, max_fuzz
            )));
        }

        // Apply the patch
        let mut metadata = self.apply_patch(patch, create_dirs).await?;

        // Get LSP diagnostics if requested
        if validate_with_lsp {
            let all_files: Vec<String> = metadata.created_files.iter()
                .chain(metadata.modified_files.iter())
                .cloned()
                .collect();

            metadata.diagnostics = self.get_diagnostics(&all_files).await;
        }

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

        // Collect all affected files
        let affected_files: Vec<PathBuf> = metadata.created_files.iter()
            .chain(metadata.modified_files.iter())
            .chain(metadata.deleted_files.iter())
            .map(|s| PathBuf::from(s))
            .collect();

        Ok(ToolResponse {
            content: response_content,
            success: true,
            metadata: metadata_json,
            affected_files,
        })
    }

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

    fn description(&self) -> &str {
        "Apply Git-style patches to files. Supports creating, updating, and deleting files with unified diff format patches."
    }

    fn requires_permission(&self) -> Permission {
        Permission::WriteFile(PathBuf::from(".")) // Requires write access to working directory
    }

    fn parameter_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "patch_text": {
                    "type": "string",
                    "description": "Patch content in unified diff format (must start with '--- ' and '+++ ' lines)"
                },
                "validate_with_lsp": {
                    "type": "boolean",
                    "description": "Whether to validate patched files with LSP and get diagnostics (default: true)",
                    "default": true
                },
                "max_fuzz": {
                    "type": "integer",
                    "description": "Maximum fuzz level to allow for patch application (default: 3)",
                    "default": 3,
                    "minimum": 0,
                    "maximum": 10
                },
                "create_dirs": {
                    "type": "boolean",
                    "description": "Whether to create parent directories if they don't exist (default: false)",
                    "default": false
                }
            },
            "required": ["patch_text"]
        })
    }

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

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

    #[tokio::test]
    async fn test_create_file_patch() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("new_file.txt");

        let patch_text = format!(
            "--- /dev/null\n+++ {}\n@@ -0,0 +1,2 @@\n+Hello\n+World\n",
            file_path.display()
        );

        let tool = PatchTool::new();
        let params = serde_json::json!({
            "patch_text": patch_text,
            "validate_with_lsp": false
        });

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

        let content = fs::read_to_string(&file_path).await.unwrap();
        assert_eq!(content, "Hello\nWorld\n");
    }

    #[tokio::test]
    async fn test_update_file_patch() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("existing_file.txt");
        fs::write(&file_path, "Hello\nWorld\n").await.unwrap();

        let patch_text = format!(
            "--- {}\n+++ {}\n@@ -1,2 +1,2 @@\n Hello\n-World\n+Rust\n",
            file_path.display(),
            file_path.display()
        );

        let tool = PatchTool::new();
        let params = serde_json::json!({
            "patch_text": patch_text,
            "validate_with_lsp": false
        });

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

        let content = fs::read_to_string(&file_path).await.unwrap();
        assert_eq!(content, "Hello\nRust\n");
    }

    #[tokio::test]
    async fn test_delete_file_patch() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("to_delete.txt");
        fs::write(&file_path, "Delete me").await.unwrap();

        let patch_text = format!(
            "--- {}\n+++ /dev/null\n@@ -1,1 +0,0 @@\n-Delete me\n",
            file_path.display()
        );

        let tool = PatchTool::new();
        let params = serde_json::json!({
            "patch_text": patch_text,
            "validate_with_lsp": false
        });

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

        assert!(!file_path.exists());
    }
}