1use async_trait::async_trait;
2use serde_json::json;
3use std::path::PathBuf;
4use tracing::info;
5
6use crate::config::WorkingDirIsolation;
7use microclaw_core::llm_types::ToolDefinition;
8
9use super::{schema_object, Tool, ToolResult};
10
11pub struct EditFileTool {
12 working_dir: PathBuf,
13 working_dir_isolation: WorkingDirIsolation,
14 diff_max_lines: usize,
15 governance_guard: crate::internal::tool_runtime::path_guard::GovernanceGuard,
16 file_state: std::sync::Arc<super::file_state::FileStateTable>,
17}
18
19impl EditFileTool {
20 pub fn new(working_dir: &str) -> Self {
21 Self::new_with_isolation(working_dir, WorkingDirIsolation::Shared)
22 }
23
24 pub fn new_with_isolation(
25 working_dir: &str,
26 working_dir_isolation: WorkingDirIsolation,
27 ) -> Self {
28 Self {
29 working_dir: PathBuf::from(working_dir),
30 working_dir_isolation,
31 diff_max_lines: microclaw_core::diff::DEFAULT_DIFF_MAX_LINES,
32 governance_guard: Default::default(),
33 file_state: Default::default(),
34 }
35 }
36
37 pub fn with_file_state(
39 mut self,
40 file_state: std::sync::Arc<super::file_state::FileStateTable>,
41 ) -> Self {
42 self.file_state = file_state;
43 self
44 }
45
46 pub fn with_diff_max_lines(mut self, max_lines: usize) -> Self {
47 self.diff_max_lines = max_lines;
48 self
49 }
50
51 pub fn with_governance_guard(
52 mut self,
53 guard: crate::internal::tool_runtime::path_guard::GovernanceGuard,
54 ) -> Self {
55 self.governance_guard = guard;
56 self
57 }
58}
59
60#[async_trait]
61impl Tool for EditFileTool {
62 fn name(&self) -> &str {
63 "edit_file"
64 }
65
66 fn definition(&self) -> ToolDefinition {
67 ToolDefinition {
68 name: "edit_file".into(),
69 description: "Edit a file by replacing a string match with new content. The match must be unique unless replace_all is set. The tool first tries an exact match; if that fails it falls back to whitespace/indentation-flexible, escape-normalized, smart-quote-aware, and block-anchor matching, and tells you which strategy succeeded. To make several changes to one file in a single call, pass `edits` (applied in order, all or nothing) instead of old_string/new_string. Edits are refused when the file changed on disk after you last read it; re-read it first. Prefer paths relative to the current chat working directory; do not invent machine-specific absolute paths unless the user or a tool already provided them.".into(),
70 input_schema: schema_object(
71 json!({
72 "path": {
73 "type": "string",
74 "description": "The file path to edit, usually relative to the current chat working directory"
75 },
76 "old_string": {
77 "type": "string",
78 "description": "The exact string to find and replace (must be unique in the file unless replace_all is true)"
79 },
80 "new_string": {
81 "type": "string",
82 "description": "The string to replace with"
83 },
84 "replace_all": {
85 "type": "boolean",
86 "description": "Replace every exact occurrence of old_string instead of requiring a unique match (default: false)"
87 },
88 "edits": {
89 "type": "array",
90 "description": "Several replacements applied in order to the same file; all must succeed or the file is left unchanged",
91 "items": {
92 "type": "object",
93 "properties": {
94 "old_string": {"type": "string"},
95 "new_string": {"type": "string"},
96 "replace_all": {"type": "boolean"}
97 },
98 "required": ["old_string", "new_string"]
99 }
100 }
101 }),
102 &["path"],
103 ),
104 }
105 }
106
107 async fn execute(&self, input: serde_json::Value) -> ToolResult {
108 let path = match input.get("path").and_then(|v| v.as_str()) {
109 Some(p) => p,
110 None => return ToolResult::error("Missing 'path' parameter".into()),
111 };
112 let working_dir =
113 super::resolve_tool_working_dir(&self.working_dir, self.working_dir_isolation, &input);
114 let resolved_path = super::resolve_tool_path(&working_dir, path);
115 let resolved_path_str = resolved_path.to_string_lossy().to_string();
116
117 if let Err(msg) = crate::internal::tool_runtime::path_guard::check_path(&resolved_path_str)
118 {
119 return ToolResult::error(msg);
120 }
121 if let Err(msg) = self.governance_guard.check_write(&resolved_path) {
122 return ToolResult::error(msg);
123 }
124
125 let edits = match parse_edits(&input) {
126 Ok(edits) => edits,
127 Err(msg) => return ToolResult::error(msg),
128 };
129
130 info!("Editing file: {}", resolved_path.display());
131
132 let content = match tokio::fs::read_to_string(&resolved_path).await {
133 Ok(c) => c,
134 Err(e) => return ToolResult::error(format!("Failed to read file: {e}")),
135 };
136 if let Err(msg) = self
137 .file_state
138 .check_fresh(&resolved_path, content.as_bytes())
139 {
140 return ToolResult::error(msg).with_error_type("stale_read");
141 }
142
143 let multi = edits.len() > 1;
144 let mut new_content = content.clone();
145 let mut notes = Vec::new();
146 for (index, edit) in edits.iter().enumerate() {
147 let label = if multi {
148 format!("edit {}: ", index + 1)
149 } else {
150 String::new()
151 };
152 match apply_edit(&new_content, edit) {
153 Ok((updated, note)) => {
154 new_content = updated;
155 if let Some(note) = note {
156 notes.push(format!("{label}{note}"));
157 }
158 }
159 Err(msg) => {
160 let unchanged = if multi { " No edits were applied." } else { "" };
161 return ToolResult::error(format!("{label}{msg}{unchanged}"));
162 }
163 }
164 }
165
166 match tokio::fs::write(&resolved_path, &new_content).await {
167 Ok(()) => {
168 self.file_state
169 .record(&resolved_path, new_content.as_bytes());
170 let suffix = if notes.is_empty() {
171 String::new()
172 } else {
173 format!(" ({})", notes.join("; "))
174 };
175 let count = if multi {
176 format!(" with {} edits", edits.len())
177 } else {
178 String::new()
179 };
180 let diff =
181 microclaw_core::diff::unified_diff(&content, &new_content, self.diff_max_lines);
182 let mut result = ToolResult::success(match &diff {
183 Some(d) => format!(
184 "Successfully edited {}{} ({}){}",
185 resolved_path.display(),
186 count,
187 d.stats(),
188 suffix
189 ),
190 None => format!(
191 "Successfully edited {}{}{}",
192 resolved_path.display(),
193 count,
194 suffix
195 ),
196 });
197 if let Some(d) = diff {
198 result =
199 result.with_metadata(microclaw_core::diff::file_diff_metadata(path, &d));
200 }
201 result
202 }
203 Err(e) => ToolResult::error(format!("Failed to write file: {e}")),
204 }
205 }
206}
207
208struct Edit {
209 old_string: String,
210 new_string: String,
211 replace_all: bool,
212}
213
214fn parse_edit(value: &serde_json::Value, context: &str) -> Result<Edit, String> {
215 let old_string = value
216 .get("old_string")
217 .and_then(|v| v.as_str())
218 .ok_or_else(|| format!("Missing 'old_string' parameter{context}"))?;
219 let new_string = value
220 .get("new_string")
221 .and_then(|v| v.as_str())
222 .ok_or_else(|| format!("Missing 'new_string' parameter{context}"))?;
223 Ok(Edit {
224 old_string: old_string.to_string(),
225 new_string: new_string.to_string(),
226 replace_all: value
227 .get("replace_all")
228 .and_then(|v| v.as_bool())
229 .unwrap_or(false),
230 })
231}
232
233fn parse_edits(input: &serde_json::Value) -> Result<Vec<Edit>, String> {
234 match input.get("edits") {
235 Some(serde_json::Value::Array(items)) => {
236 if input.get("old_string").is_some() {
237 return Err("Pass either 'edits' or 'old_string'/'new_string', not both".into());
238 }
239 if items.is_empty() {
240 return Err("'edits' must contain at least one edit".into());
241 }
242 items
243 .iter()
244 .enumerate()
245 .map(|(i, item)| parse_edit(item, &format!(" in edits[{i}]")))
246 .collect()
247 }
248 Some(_) => Err("'edits' must be an array of {old_string, new_string} objects".into()),
249 None => parse_edit(input, " (or provide 'edits')").map(|edit| vec![edit]),
250 }
251}
252
253fn apply_edit(content: &str, edit: &Edit) -> Result<(String, Option<String>), String> {
256 if edit.replace_all {
257 if edit.old_string.is_empty() {
258 return Err("old_string cannot be empty".into());
259 }
260 if edit.old_string == edit.new_string {
261 return Err("old_string and new_string are identical".into());
262 }
263 let count = content.matches(edit.old_string.as_str()).count();
264 if count == 0 {
265 return Err(
266 "Could not find a match for old_string (replace_all requires an exact match)"
267 .into(),
268 );
269 }
270 let note = format!(
271 "replaced {count} occurrence{}",
272 if count == 1 { "" } else { "s" }
273 );
274 return Ok((
275 content.replace(edit.old_string.as_str(), &edit.new_string),
276 Some(note),
277 ));
278 }
279 let fm =
280 super::fuzzy_match::fuzzy_find_and_replace(content, &edit.old_string, &edit.new_string)?;
281 let note = (fm.strategy != "exact").then(|| {
282 format!(
283 "matched via `{}` strategy — re-read the file if you want to confirm the byte-exact form",
284 fm.strategy
285 )
286 });
287 Ok((fm.new_content, note))
288}
289
290#[cfg(test)]
291mod tests {
292 use super::*;
293 use serde_json::json;
294
295 #[test]
296 fn test_edit_file_definition_prefers_relative_paths() {
297 let tool = EditFileTool::new(".");
298 let def = tool.definition();
299 assert!(def
300 .description
301 .contains("Prefer paths relative to the current chat working directory"));
302 assert_eq!(
303 def.input_schema["properties"]["path"]["description"].as_str(),
304 Some("The file path to edit, usually relative to the current chat working directory")
305 );
306 }
307
308 fn setup_file(content: &str) -> (std::path::PathBuf, std::path::PathBuf) {
309 let dir = std::env::temp_dir().join(format!("microclaw_ef_{}", uuid::Uuid::new_v4()));
310 std::fs::create_dir_all(&dir).unwrap();
311 let file = dir.join("edit_me.txt");
312 std::fs::write(&file, content).unwrap();
313 (dir, file)
314 }
315
316 #[tokio::test]
317 async fn test_edit_file_success() {
318 let (dir, file) = setup_file("hello world");
319 let tool = EditFileTool::new(".");
320 let result = tool
321 .execute(json!({
322 "path": file.to_str().unwrap(),
323 "old_string": "world",
324 "new_string": "rust"
325 }))
326 .await;
327 assert!(!result.is_error);
328 assert_eq!(std::fs::read_to_string(&file).unwrap(), "hello rust");
329 let _ = std::fs::remove_dir_all(&dir);
330 }
331
332 #[tokio::test]
333 async fn test_edit_file_not_found() {
334 let tool = EditFileTool::new(".");
335 let result = tool
336 .execute(json!({
337 "path": "/nonexistent/file.txt",
338 "old_string": "a",
339 "new_string": "b"
340 }))
341 .await;
342 assert!(result.is_error);
343 assert!(result.content.contains("Failed to read file"));
344 }
345
346 #[tokio::test]
347 async fn test_edit_file_old_string_not_found() {
348 let (dir, file) = setup_file("hello world");
349 let tool = EditFileTool::new(".");
350 let result = tool
351 .execute(json!({
352 "path": file.to_str().unwrap(),
353 "old_string": "completely different content xyz",
354 "new_string": "abc"
355 }))
356 .await;
357 assert!(result.is_error);
358 assert!(result.content.contains("Could not find a match"));
359 let _ = std::fs::remove_dir_all(&dir);
360 }
361
362 #[tokio::test]
363 async fn test_edit_file_multiple_matches() {
364 let (dir, file) = setup_file("aaa bbb aaa");
365 let tool = EditFileTool::new(".");
366 let result = tool
367 .execute(json!({
368 "path": file.to_str().unwrap(),
369 "old_string": "aaa",
370 "new_string": "ccc"
371 }))
372 .await;
373 assert!(result.is_error);
374 assert!(result.content.contains("2 matches"));
375 let _ = std::fs::remove_dir_all(&dir);
376 }
377
378 #[tokio::test]
379 async fn test_edit_file_fuzzy_indentation() {
380 let (dir, file) = setup_file(" let x = 1;\n let y = 2;\n");
382 let tool = EditFileTool::new(".");
383 let result = tool
384 .execute(json!({
385 "path": file.to_str().unwrap(),
386 "old_string": "let x = 1;\nlet y = 2;",
387 "new_string": "let x = 1;\nlet y = 99;"
388 }))
389 .await;
390 assert!(!result.is_error, "got error: {}", result.content);
391 assert!(
393 result.content.contains("line_trimmed")
394 || result.content.contains("indentation_flexible"),
395 "expected fuzzy strategy hint, got: {}",
396 result.content
397 );
398 let after = std::fs::read_to_string(&file).unwrap();
399 assert!(after.contains("let y = 99"));
400 let _ = std::fs::remove_dir_all(&dir);
401 }
402
403 #[tokio::test]
404 async fn test_edit_file_missing_params() {
405 let tool = EditFileTool::new(".");
406 let result = tool.execute(json!({})).await;
407 assert!(result.is_error);
408 assert!(result.content.contains("Missing 'path'"));
409
410 let result = tool.execute(json!({"path": "/tmp/x"})).await;
411 assert!(result.is_error);
412 assert!(result.content.contains("Missing 'old_string'"));
413 }
414
415 #[tokio::test]
416 async fn test_edit_file_resolves_relative_to_working_dir() {
417 let root = std::env::temp_dir().join(format!("microclaw_ef2_{}", uuid::Uuid::new_v4()));
418 let work = root.join("workspace");
419 let shared = work.join("shared");
420 std::fs::create_dir_all(&shared).unwrap();
421 let file = shared.join("edit_me.txt");
422 std::fs::write(&file, "aaa bbb").unwrap();
423
424 let tool = EditFileTool::new(work.to_str().unwrap());
425 let result = tool
426 .execute(json!({
427 "path": "edit_me.txt",
428 "old_string": "bbb",
429 "new_string": "ccc"
430 }))
431 .await;
432 assert!(!result.is_error);
433 assert_eq!(std::fs::read_to_string(&file).unwrap(), "aaa ccc");
434
435 let _ = std::fs::remove_dir_all(&root);
436 }
437
438 #[tokio::test]
439 async fn test_edit_file_replace_all() {
440 let (dir, file) = setup_file("aaa bbb aaa");
441 let tool = EditFileTool::new(".");
442 let result = tool
443 .execute(json!({
444 "path": file.to_str().unwrap(),
445 "old_string": "aaa",
446 "new_string": "ccc",
447 "replace_all": true
448 }))
449 .await;
450 assert!(!result.is_error, "{}", result.content);
451 assert!(result.content.contains("replaced 2 occurrences"));
452 assert_eq!(std::fs::read_to_string(&file).unwrap(), "ccc bbb ccc");
453 let _ = std::fs::remove_dir_all(&dir);
454 }
455
456 #[tokio::test]
457 async fn test_edit_file_multi_edit_is_all_or_nothing() {
458 let (dir, file) = setup_file("one two three");
459 let tool = EditFileTool::new(".");
460 let failed = tool
461 .execute(json!({
462 "path": file.to_str().unwrap(),
463 "edits": [
464 {"old_string": "one", "new_string": "1"},
465 {"old_string": "missing words here", "new_string": "x"}
466 ]
467 }))
468 .await;
469 assert!(failed.is_error);
470 assert!(failed.content.contains("edit 2"));
471 assert!(failed.content.contains("No edits were applied"));
472 assert_eq!(std::fs::read_to_string(&file).unwrap(), "one two three");
473
474 let ok = tool
475 .execute(json!({
476 "path": file.to_str().unwrap(),
477 "edits": [
478 {"old_string": "one", "new_string": "1"},
479 {"old_string": "three", "new_string": "3"}
480 ]
481 }))
482 .await;
483 assert!(!ok.is_error, "{}", ok.content);
484 assert!(ok.content.contains("with 2 edits"));
485 assert_eq!(std::fs::read_to_string(&file).unwrap(), "1 two 3");
486 let _ = std::fs::remove_dir_all(&dir);
487 }
488
489 #[tokio::test]
490 async fn test_edit_file_refuses_stale_read() {
491 let (dir, file) = setup_file("original");
492 let table = std::sync::Arc::new(super::super::file_state::FileStateTable::default());
493 let read = super::super::read_file::ReadFileTool::new(".").with_file_state(table.clone());
494 let _ = read.execute(json!({"path": file.to_str().unwrap()})).await;
495 std::fs::write(&file, "changed by the user").unwrap();
496
497 let tool = EditFileTool::new(".").with_file_state(table);
498 let result = tool
499 .execute(json!({
500 "path": file.to_str().unwrap(),
501 "old_string": "changed",
502 "new_string": "edited"
503 }))
504 .await;
505 assert!(result.is_error);
506 assert_eq!(result.error_type.as_deref(), Some("stale_read"));
507 assert_eq!(
508 std::fs::read_to_string(&file).unwrap(),
509 "changed by the user"
510 );
511
512 let _ = read.execute(json!({"path": file.to_str().unwrap()})).await;
513 let retry = tool
514 .execute(json!({
515 "path": file.to_str().unwrap(),
516 "old_string": "changed",
517 "new_string": "edited"
518 }))
519 .await;
520 assert!(!retry.is_error, "{}", retry.content);
521 let _ = std::fs::remove_dir_all(&dir);
522 }
523}