codive-tools 0.1.0

Tool implementations for Codive
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
//! EditFile tool for making targeted edits to files
//!
//! This tool performs surgical string replacements in files without
//! rewriting the entire content. It's designed for making precise edits
//! like fixing bugs, updating function names, or modifying specific lines.
//!
//! # Safety
//!
//! The tool validates that `old_string` exists and is unique (unless
//! `replace_all` is true) to prevent accidental modifications.

use codive_core::tool::{Tool, ToolOutput};
use async_trait::async_trait;
use serde::Deserialize;
use std::path::Path;
use tokio::fs;
use tracing::debug;

/// Maximum file size to edit (10MB)
const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024;

/// Tool for editing files with string replacement
pub struct EditFileTool {
    /// Maximum file size to edit
    max_file_size: u64,
}

impl EditFileTool {
    /// Create a new EditFileTool with default settings
    pub fn new() -> Self {
        Self {
            max_file_size: MAX_FILE_SIZE,
        }
    }

    /// Set the maximum file size
    pub fn with_max_file_size(mut self, size: u64) -> Self {
        self.max_file_size = size;
        self
    }
}

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

/// Parameters for the edit_file tool
#[derive(Debug, Deserialize)]
struct EditFileParams {
    /// Path to the file to edit
    path: String,
    /// The text to find and replace
    old_string: String,
    /// The replacement text
    new_string: String,
    /// Whether to replace all occurrences (default: false)
    /// If false, old_string must be unique in the file
    #[serde(default)]
    replace_all: bool,
}

#[async_trait]
impl Tool for EditFileTool {
    fn name(&self) -> &str {
        "edit_file"
    }

    fn description(&self) -> &str {
        "Edit a file by replacing a specific string with new content. \
         By default, the old_string must be unique in the file to prevent \
         unintended changes. Use replace_all=true to replace all occurrences."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "The path to the file to edit"
                },
                "old_string": {
                    "type": "string",
                    "description": "The exact text to find and replace"
                },
                "new_string": {
                    "type": "string",
                    "description": "The text to replace old_string with"
                },
                "replace_all": {
                    "type": "boolean",
                    "description": "If true, replace all occurrences. If false (default), old_string must be unique"
                }
            },
            "required": ["path", "old_string", "new_string"]
        })
    }

    async fn execute(&self, params: serde_json::Value) -> ToolOutput {
        // Parse parameters
        let params: EditFileParams = match serde_json::from_value(params) {
            Ok(p) => p,
            Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
        };

        let path = Path::new(&params.path);
        debug!(path = %path.display(), replace_all = params.replace_all, "Editing file");

        // Validate old_string is not empty
        if params.old_string.is_empty() {
            return ToolOutput::error("old_string cannot be empty");
        }

        // Check if old_string and new_string are different
        if params.old_string == params.new_string {
            return ToolOutput::error("old_string and new_string must be different");
        }

        // Check if file exists
        if !path.exists() {
            return ToolOutput::error(format!("File does not exist: {}", params.path));
        }

        // Check if it's a file (not a directory)
        if !path.is_file() {
            return ToolOutput::error(format!("Path is not a file: {}", params.path));
        }

        // Check file size
        let metadata = match fs::metadata(path).await {
            Ok(m) => m,
            Err(e) => return ToolOutput::error(format!("Failed to read file metadata: {}", e)),
        };

        if metadata.len() > self.max_file_size {
            return ToolOutput::error(format!(
                "File too large: {} bytes (max: {} bytes)",
                metadata.len(),
                self.max_file_size
            ));
        }

        // Read the file
        let content = match fs::read_to_string(path).await {
            Ok(c) => c,
            Err(e) => return ToolOutput::error(format!("Failed to read file: {}", e)),
        };

        // Count occurrences
        let occurrences = content.matches(&params.old_string).count();

        if occurrences == 0 {
            return ToolOutput::error(
                "old_string not found in file. Make sure the text matches exactly, \
                 including whitespace and line endings."
            );
        }

        // If not replace_all, check uniqueness
        if !params.replace_all && occurrences > 1 {
            return ToolOutput::error(format!(
                "old_string appears {} times in the file. Use replace_all=true to replace \
                 all occurrences, or provide a more specific old_string that is unique.",
                occurrences
            ));
        }

        // Store old content for diff metadata
        let old_content = content.clone();

        // Perform the replacement
        let new_content = if params.replace_all {
            content.replace(&params.old_string, &params.new_string)
        } else {
            content.replacen(&params.old_string, &params.new_string, 1)
        };

        // Write the file
        if let Err(e) = fs::write(path, &new_content).await {
            return ToolOutput::error(format!("Failed to write file: {}", e));
        }

        // Build success message
        let action = if params.replace_all && occurrences > 1 {
            format!("Replaced {} occurrences", occurrences)
        } else {
            "Replaced 1 occurrence".to_string()
        };

        ToolOutput::success(format!("{} in {}", action, path.display()))
            .with_file_change(params.path, Some(old_content), new_content)
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_edit_file_tool_name() {
        let tool = EditFileTool::new();
        assert_eq!(tool.name(), "edit_file");
    }

    #[test]
    fn test_edit_file_schema() {
        let tool = EditFileTool::new();
        let schema = tool.parameters_schema();
        assert_eq!(schema["type"], "object");
        assert!(schema["properties"]["path"].is_object());
        assert!(schema["properties"]["old_string"].is_object());
        assert!(schema["properties"]["new_string"].is_object());
        assert_eq!(schema["required"][0], "path");
        assert_eq!(schema["required"][1], "old_string");
        assert_eq!(schema["required"][2], "new_string");
    }

    #[tokio::test]
    async fn test_edit_simple_replacement() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.txt");
        fs::write(&file_path, "Hello World").unwrap();

        let tool = EditFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file_path.to_str().unwrap(),
                "old_string": "World",
                "new_string": "Rust"
            }))
            .await;

        assert!(output.is_success(), "Output: {}", output.content);
        assert!(output.content.contains("Replaced 1 occurrence"));

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

    #[tokio::test]
    async fn test_edit_multiline() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.txt");
        fs::write(
            &file_path,
            "fn main() {\n    println!(\"Hello\");\n}\n",
        )
        .unwrap();

        let tool = EditFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file_path.to_str().unwrap(),
                "old_string": "    println!(\"Hello\");",
                "new_string": "    println!(\"Hello, World!\");"
            }))
            .await;

        assert!(output.is_success(), "Output: {}", output.content);

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

    #[tokio::test]
    async fn test_edit_not_unique_fails() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.txt");
        fs::write(&file_path, "foo bar foo baz foo").unwrap();

        let tool = EditFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file_path.to_str().unwrap(),
                "old_string": "foo",
                "new_string": "qux"
            }))
            .await;

        assert!(output.is_error);
        assert!(output.content.contains("3 times"));
        assert!(output.content.contains("replace_all=true"));

        // File should be unchanged
        let content = fs::read_to_string(&file_path).unwrap();
        assert_eq!(content, "foo bar foo baz foo");
    }

    #[tokio::test]
    async fn test_edit_replace_all() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.txt");
        fs::write(&file_path, "foo bar foo baz foo").unwrap();

        let tool = EditFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file_path.to_str().unwrap(),
                "old_string": "foo",
                "new_string": "qux",
                "replace_all": true
            }))
            .await;

        assert!(output.is_success(), "Output: {}", output.content);
        assert!(output.content.contains("Replaced 3 occurrences"));

        let content = fs::read_to_string(&file_path).unwrap();
        assert_eq!(content, "qux bar qux baz qux");
    }

    #[tokio::test]
    async fn test_edit_old_string_not_found() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.txt");
        fs::write(&file_path, "Hello World").unwrap();

        let tool = EditFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file_path.to_str().unwrap(),
                "old_string": "Goodbye",
                "new_string": "Hi"
            }))
            .await;

        assert!(output.is_error);
        assert!(output.content.contains("not found"));
    }

    #[tokio::test]
    async fn test_edit_empty_old_string() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.txt");
        fs::write(&file_path, "Hello World").unwrap();

        let tool = EditFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file_path.to_str().unwrap(),
                "old_string": "",
                "new_string": "Hi"
            }))
            .await;

        assert!(output.is_error);
        assert!(output.content.contains("cannot be empty"));
    }

    #[tokio::test]
    async fn test_edit_same_strings() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.txt");
        fs::write(&file_path, "Hello World").unwrap();

        let tool = EditFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file_path.to_str().unwrap(),
                "old_string": "Hello",
                "new_string": "Hello"
            }))
            .await;

        assert!(output.is_error);
        assert!(output.content.contains("must be different"));
    }

    #[tokio::test]
    async fn test_edit_nonexistent_file() {
        let tool = EditFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": "/nonexistent/path/file.txt",
                "old_string": "foo",
                "new_string": "bar"
            }))
            .await;

        assert!(output.is_error);
        assert!(output.content.contains("does not exist"));
    }

    #[tokio::test]
    async fn test_edit_directory_fails() {
        let dir = tempdir().unwrap();

        let tool = EditFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": dir.path().to_str().unwrap(),
                "old_string": "foo",
                "new_string": "bar"
            }))
            .await;

        assert!(output.is_error);
        assert!(output.content.contains("not a file"));
    }

    #[tokio::test]
    async fn test_edit_file_too_large() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.txt");
        fs::write(&file_path, "Hello World").unwrap();

        let tool = EditFileTool::new().with_max_file_size(5);
        let output = tool
            .execute(serde_json::json!({
                "path": file_path.to_str().unwrap(),
                "old_string": "World",
                "new_string": "Rust"
            }))
            .await;

        assert!(output.is_error);
        assert!(output.content.contains("too large"));
    }

    #[tokio::test]
    async fn test_edit_invalid_params() {
        let tool = EditFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": "/tmp/test.txt"
            }))
            .await;

        assert!(output.is_error);
        assert!(output.content.contains("Invalid parameters"));
    }

    #[tokio::test]
    async fn test_edit_preserves_other_content() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.rs");
        let original = r#"fn main() {
    let x = 1;
    let y = 2;
    println!("{}", x + y);
}
"#;
        fs::write(&file_path, original).unwrap();

        let tool = EditFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file_path.to_str().unwrap(),
                "old_string": "let y = 2;",
                "new_string": "let y = 42;"
            }))
            .await;

        assert!(output.is_success(), "Output: {}", output.content);

        let content = fs::read_to_string(&file_path).unwrap();
        assert!(content.contains("let x = 1;"));
        assert!(content.contains("let y = 42;"));
        assert!(content.contains("println!"));
    }

    #[tokio::test]
    async fn test_edit_with_special_chars() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.txt");
        fs::write(&file_path, "Price: $100.00").unwrap();

        let tool = EditFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file_path.to_str().unwrap(),
                "old_string": "$100.00",
                "new_string": "$200.00"
            }))
            .await;

        assert!(output.is_success(), "Output: {}", output.content);

        let content = fs::read_to_string(&file_path).unwrap();
        assert_eq!(content, "Price: $200.00");
    }
}