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
//! Advanced file editing tool with LSP integration

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
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};

/// Advanced edit tool with LSP integration and change tracking
pub struct EditTool {
    lsp_service: Option<Arc<dyn LspService>>,
}

/// Parameters for the edit tool
#[derive(Debug, Deserialize)]
struct EditParams {
    /// File path to edit
    file_path: PathBuf,
    /// Old string to replace (empty for new file creation)
    old_string: Option<String>,
    /// New string to insert (empty for deletion)
    new_string: Option<String>,
    /// Whether to validate with LSP after edit
    validate_with_lsp: Option<bool>,
    /// Whether to create parent directories if they don't exist
    create_dirs: Option<bool>,
}

/// Edit operation metadata
#[derive(Debug, Serialize)]
struct EditMetadata {
    /// Generated diff
    diff: String,
    /// Number of lines added
    additions: usize,
    /// Number of lines removed
    removals: usize,
    /// LSP diagnostics after edit (if available)
    diagnostics: Vec<LspDiagnostic>,
    /// File size before edit
    old_size: usize,
    /// File size after edit
    new_size: usize,
}

impl EditTool {
    /// Create a new edit 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);
    }
    
    /// Create a new file
    async fn create_file(&self, file_path: &Path, content: &str, create_dirs: bool) -> Result<EditMetadata, ToolError> {
        // Check if file already exists
        if file_path.exists() {
            return Err(ToolError::ExecutionFailed(format!(
                "File already exists: {}. Use old_string parameter to edit existing files.",
                file_path.display()
            )));
        }
        
        // Create parent directories if requested
        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)))?;
            }
        }
        
        // Write the new file
        fs::write(file_path, content).await
            .map_err(|e| ToolError::ExecutionFailed(format!("Failed to create file: {}", e)))?;
        
        // Generate diff
        let diff = self.generate_diff("", content, file_path);
        let lines: Vec<&str> = content.lines().collect();
        
        Ok(EditMetadata {
            diff,
            additions: lines.len(),
            removals: 0,
            diagnostics: Vec::new(),
            old_size: 0,
            new_size: content.len(),
        })
    }
    
    /// Delete content from file
    async fn delete_content(&self, file_path: &Path, old_string: &str) -> Result<EditMetadata, ToolError> {
        let old_content = fs::read_to_string(file_path).await
            .map_err(|e| ToolError::ExecutionFailed(format!("Failed to read file: {}", e)))?;
        
        // Find the string to delete
        let index = old_content.find(old_string)
            .ok_or_else(|| ToolError::ExecutionFailed("old_string not found in file".to_string()))?;
        
        // Check for multiple occurrences
        if old_content.rfind(old_string) != Some(index) {
            return Err(ToolError::ExecutionFailed(
                "old_string appears multiple times in the file. Please provide more context to ensure a unique match".to_string()
            ));
        }
        
        // Create new content without the old string
        let new_content = format!("{}{}", &old_content[..index], &old_content[index + old_string.len()..]);
        
        // Write the updated file
        fs::write(file_path, &new_content).await
            .map_err(|e| ToolError::ExecutionFailed(format!("Failed to write file: {}", e)))?;
        
        // Generate diff and metadata
        let diff = self.generate_diff(&old_content, &new_content, file_path);
        let old_lines: Vec<&str> = old_content.lines().collect();
        let new_lines: Vec<&str> = new_content.lines().collect();
        
        Ok(EditMetadata {
            diff,
            additions: 0,
            removals: old_lines.len().saturating_sub(new_lines.len()),
            diagnostics: Vec::new(),
            old_size: old_content.len(),
            new_size: new_content.len(),
        })
    }
    
    /// Replace content in file
    async fn replace_content(&self, file_path: &Path, old_string: &str, new_string: &str) -> Result<EditMetadata, ToolError> {
        let old_content = fs::read_to_string(file_path).await
            .map_err(|e| ToolError::ExecutionFailed(format!("Failed to read file: {}", e)))?;
        
        // Find the string to replace
        let index = old_content.find(old_string)
            .ok_or_else(|| ToolError::ExecutionFailed("old_string not found in file".to_string()))?;
        
        // Check for multiple occurrences
        if old_content.rfind(old_string) != Some(index) {
            return Err(ToolError::ExecutionFailed(
                "old_string appears multiple times in the file. Please provide more context to ensure a unique match".to_string()
            ));
        }
        
        // Create new content with replacement
        let new_content = format!("{}{}{}", 
            &old_content[..index], 
            new_string, 
            &old_content[index + old_string.len()..]
        );
        
        // Write the updated file
        fs::write(file_path, &new_content).await
            .map_err(|e| ToolError::ExecutionFailed(format!("Failed to write file: {}", e)))?;
        
        // Generate diff and metadata
        let diff = self.generate_diff(&old_content, &new_content, file_path);
        let old_lines: Vec<&str> = old_content.lines().collect();
        let new_lines: Vec<&str> = new_content.lines().collect();
        
        let additions = new_lines.len().saturating_sub(old_lines.len());
        let removals = old_lines.len().saturating_sub(new_lines.len());
        
        Ok(EditMetadata {
            diff,
            additions,
            removals,
            diagnostics: Vec::new(),
            old_size: old_content.len(),
            new_size: new_content.len(),
        })
    }
    
    /// Generate a unified diff
    fn generate_diff(&self, old_content: &str, new_content: &str, file_path: &Path) -> String {
        let old_lines: Vec<&str> = old_content.lines().collect();
        let new_lines: Vec<&str> = new_content.lines().collect();
        
        let mut diff = String::new();
        diff.push_str(&format!("--- {}\n", file_path.display()));
        diff.push_str(&format!("+++ {}\n", file_path.display()));
        diff.push_str(&format!("@@ -{},{} +{},{} @@\n", 
            1, old_lines.len(), 1, new_lines.len()));
        
        // Simple line-by-line diff
        let max_lines = old_lines.len().max(new_lines.len());
        for i in 0..max_lines {
            match (old_lines.get(i), new_lines.get(i)) {
                (Some(old_line), Some(new_line)) => {
                    if old_line != new_line {
                        diff.push_str(&format!("-{}\n", old_line));
                        diff.push_str(&format!("+{}\n", new_line));
                    } else {
                        diff.push_str(&format!(" {}\n", old_line));
                    }
                }
                (Some(old_line), None) => {
                    diff.push_str(&format!("-{}\n", old_line));
                }
                (None, Some(new_line)) => {
                    diff.push_str(&format!("+{}\n", new_line));
                }
                (None, None) => break,
            }
        }
        
        diff
    }
    
    /// Get LSP diagnostics for a file
    async fn get_diagnostics(&self, file_path: &Path) -> Vec<LspDiagnostic> {
        if let Some(lsp) = &self.lsp_service {
            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(diagnostics) => diagnostics,
                    Err(_) => Vec::new(),
                }
            } else {
                Vec::new()
            }
        } else {
            Vec::new()
        }
    }
    
    /// Format the edit response
    fn format_response(&self, metadata: &EditMetadata, file_path: &Path) -> String {
        let mut response = String::new();
        
        response.push_str(&format!("Successfully edited {}\n\n", file_path.display()));
        response.push_str(&format!("Changes: +{} lines, -{} lines\n", metadata.additions, metadata.removals));
        response.push_str(&format!("File size: {} → {} bytes\n\n", metadata.old_size, metadata.new_size));
        
        // Add diff
        response.push_str("Diff:\n");
        response.push_str(&metadata.diff);
        
        // Add diagnostics if available
        if !metadata.diagnostics.is_empty() {
            response.push_str("\n\nLSP Diagnostics:\n");
            for diagnostic in &metadata.diagnostics {
                response.push_str(&format!("  {}: {} (line {})\n",
                    diagnostic.severity, diagnostic.message, diagnostic.line + 1));
            }
        }
        
        response
    }
}

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

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

        // Validate file path
        if params.file_path.as_os_str().is_empty() {
            return Err(ToolError::InvalidParameters("file_path is required".to_string()));
        }

        let file_path = &params.file_path;
        let validate_with_lsp = params.validate_with_lsp.unwrap_or(true);
        let create_dirs = params.create_dirs.unwrap_or(false);

        // Determine operation type
        let mut metadata = match (&params.old_string, &params.new_string) {
            // Create new file
            (None, Some(new_string)) => {
                self.create_file(file_path, new_string, create_dirs).await?
            }
            (Some(old_string), Some(new_string)) if old_string.is_empty() => {
                self.create_file(file_path, new_string, create_dirs).await?
            }
            // Delete content
            (Some(old_string), None) => {
                self.delete_content(file_path, old_string).await?
            }
            (Some(old_string), Some(new_string)) if new_string.is_empty() => {
                self.delete_content(file_path, old_string).await?
            }
            // Replace content
            (Some(old_string), Some(new_string)) => {
                self.replace_content(file_path, old_string, new_string).await?
            }
            // Invalid parameters
            _ => {
                return Err(ToolError::InvalidParameters(
                    "Either old_string or new_string (or both) must be provided".to_string()
                ));
            }
        };

        // Get LSP diagnostics if requested and available
        if validate_with_lsp {
            metadata.diagnostics = self.get_diagnostics(file_path).await;

            // Notify LSP of file change
            if let Some(lsp) = &self.lsp_service {
                if lsp.supports_file(file_path) {
                    if let Ok(content) = fs::read_to_string(file_path).await {
                        let _ = lsp.did_change_file(file_path, &content).await;
                    }
                }
            }
        }

        let response_content = self.format_response(&metadata, file_path);
        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![file_path.clone()],
        })
    }

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

    fn description(&self) -> &str {
        "Advanced file editing tool with LSP integration. Supports creating new files, replacing content, and deleting content with change tracking and validation."
    }

    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": {
                "file_path": {
                    "type": "string",
                    "description": "Path to the file to edit (relative or absolute)"
                },
                "old_string": {
                    "type": "string",
                    "description": "String to replace or delete (omit for new file creation)"
                },
                "new_string": {
                    "type": "string",
                    "description": "String to insert or replace with (omit for deletion)"
                },
                "validate_with_lsp": {
                    "type": "boolean",
                    "description": "Whether to validate the edit with LSP and get diagnostics (default: true)",
                    "default": true
                },
                "create_dirs": {
                    "type": "boolean",
                    "description": "Whether to create parent directories if they don't exist (default: false)",
                    "default": false
                }
            },
            "required": ["file_path"],
            "oneOf": [
                {
                    "description": "Create new file",
                    "required": ["new_string"],
                    "not": {"required": ["old_string"]}
                },
                {
                    "description": "Replace content",
                    "required": ["old_string", "new_string"]
                },
                {
                    "description": "Delete content",
                    "required": ["old_string"],
                    "not": {"required": ["new_string"]}
                }
            ]
        })
    }

    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() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.txt");

        let tool = EditTool::new();
        let params = serde_json::json!({
            "file_path": file_path,
            "new_string": "Hello, World!"
        });

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

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

    #[tokio::test]
    async fn test_replace_content() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.txt");
        fs::write(&file_path, "Hello, World!").await.unwrap();

        let tool = EditTool::new();
        let params = serde_json::json!({
            "file_path": file_path,
            "old_string": "World",
            "new_string": "Rust"
        });

        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, Rust!");
    }

    #[tokio::test]
    async fn test_delete_content() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.txt");
        fs::write(&file_path, "Hello, World!\nGoodbye!").await.unwrap();

        let tool = EditTool::new();
        let params = serde_json::json!({
            "file_path": file_path,
            "old_string": ", World!"
        });

        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\nGoodbye!");
    }

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

        let tool = EditTool::new();
        let params = serde_json::json!({
            "file_path": file_path,
            "old_string": "test",
            "new_string": "replaced"
        });

        let result = tool.execute(params, &crate::integration::MockHost).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("multiple times"));
    }
}