microclaw_engine/tools/
write_file.rs1use 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 WriteFileTool {
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 WriteFileTool {
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 WriteFileTool {
62 fn name(&self) -> &str {
63 "write_file"
64 }
65
66 fn definition(&self) -> ToolDefinition {
67 ToolDefinition {
68 name: "write_file".into(),
69 description: "Write content to a file. Creates the file and any parent directories if they don't exist. Overwrites existing content. 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 write to, usually relative to the current chat working directory"
75 },
76 "content": {
77 "type": "string",
78 "description": "The content to write"
79 }
80 }),
81 &["path", "content"],
82 ),
83 }
84 }
85
86 async fn execute(&self, input: serde_json::Value) -> ToolResult {
87 let path = match input.get("path").and_then(|v| v.as_str()) {
88 Some(p) => p,
89 None => return ToolResult::error("Missing 'path' parameter".into()),
90 };
91 let working_dir =
92 super::resolve_tool_working_dir(&self.working_dir, self.working_dir_isolation, &input);
93 let resolved_path = super::resolve_tool_path(&working_dir, path);
94 let resolved_path_str = resolved_path.to_string_lossy().to_string();
95
96 if let Err(msg) = crate::internal::tool_runtime::path_guard::check_path(&resolved_path_str)
97 {
98 return ToolResult::error(msg);
99 }
100 if let Err(msg) = self.governance_guard.check_write(&resolved_path) {
101 return ToolResult::error(msg);
102 }
103
104 if resolved_path.file_name().and_then(|f| f.to_str()) == Some("SKILL.md") {
106 let path_str = resolved_path.to_string_lossy();
107 let normalized = path_str.replace('\\', "/");
108 let in_correct_dir = normalized.contains("/skills/");
109 let in_runtime_dir = normalized.contains("/runtime/skills/");
110 if in_runtime_dir || !in_correct_dir {
111 return ToolResult::error(format!(
112 "Wrong directory for skills! SKILL.md files MUST be written to ~/.microclaw/skills/<skill-name>/SKILL.md (or configured skills dir) — \
113 NOT runtime/skills/ or any other location. Use the `sync_skills` tool instead, which handles this automatically. \
114 Attempted path: {}",
115 resolved_path.display()
116 ));
117 }
118 }
119
120 let content = match input.get("content").and_then(|v| v.as_str()) {
121 Some(c) => c,
122 None => return ToolResult::error("Missing 'content' parameter".into()),
123 };
124
125 info!("Writing file: {}", resolved_path.display());
126
127 let previous_bytes = tokio::fs::read(&resolved_path).await.ok();
130 if let Some(bytes) = &previous_bytes {
131 if let Err(msg) = self.file_state.check_fresh(&resolved_path, bytes) {
132 return ToolResult::error(msg).with_error_type("stale_read");
133 }
134 }
135 let previous = previous_bytes
136 .and_then(|bytes| String::from_utf8(bytes).ok())
137 .unwrap_or_default();
138
139 if let Some(parent) = resolved_path.parent() {
140 if let Err(e) = tokio::fs::create_dir_all(parent).await {
141 return ToolResult::error(format!("Failed to create directories: {e}"));
142 }
143 }
144
145 match tokio::fs::write(&resolved_path, content).await {
146 Ok(()) => {
147 self.file_state.record(&resolved_path, content.as_bytes());
148 let diff =
149 microclaw_core::diff::unified_diff(&previous, content, self.diff_max_lines);
150 let mut result = ToolResult::success(match &diff {
151 Some(d) => format!(
152 "Successfully wrote to {} ({})",
153 resolved_path.display(),
154 d.stats()
155 ),
156 None => format!("Successfully wrote to {}", resolved_path.display()),
157 });
158 if let Some(d) = diff {
159 result =
160 result.with_metadata(microclaw_core::diff::file_diff_metadata(path, &d));
161 }
162 result
163 }
164 Err(e) => ToolResult::error(format!("Failed to write file: {e}")),
165 }
166 }
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172 use serde_json::json;
173
174 #[tokio::test]
175 async fn test_write_file_refuses_governance_files() {
176 let dir = std::env::temp_dir().join(format!("microclaw_wf_gov_{}", uuid::Uuid::new_v4()));
177 let memory = dir.join("runtime/groups/AGENTS.md");
178 let guard = crate::internal::tool_runtime::path_guard::GovernanceGuard::default()
179 .protect_data_root(&dir)
180 .exempt(dir.join("working_dir"));
181 let tool = WriteFileTool::new(dir.join("working_dir").to_str().unwrap())
182 .with_governance_guard(guard);
183 let result = tool
184 .execute(json!({"path": memory.to_str().unwrap(), "content": "injected"}))
185 .await;
186 assert!(result.is_error);
187 assert!(result.content.contains("governance file"));
188 assert!(!memory.exists());
189
190 let result = tool
191 .execute(json!({"path": "notes.md", "content": "ok"}))
192 .await;
193 assert!(!result.is_error, "{}", result.content);
194 let _ = std::fs::remove_dir_all(&dir);
195 }
196
197 #[test]
198 fn test_write_file_definition_prefers_relative_paths() {
199 let tool = WriteFileTool::new(".");
200 let def = tool.definition();
201 assert!(def
202 .description
203 .contains("Prefer paths relative to the current chat working directory"));
204 assert_eq!(
205 def.input_schema["properties"]["path"]["description"].as_str(),
206 Some(
207 "The file path to write to, usually relative to the current chat working directory"
208 )
209 );
210 }
211
212 #[tokio::test]
213 async fn test_write_file_success() {
214 let dir = std::env::temp_dir().join(format!("microclaw_wf_{}", uuid::Uuid::new_v4()));
215 std::fs::create_dir_all(&dir).unwrap();
216 let file = dir.join("out.txt");
217
218 let tool = WriteFileTool::new(".");
219 let result = tool
220 .execute(json!({"path": file.to_str().unwrap(), "content": "hello world"}))
221 .await;
222 assert!(!result.is_error);
223 assert!(result.content.contains("Successfully wrote"));
224
225 let content = std::fs::read_to_string(&file).unwrap();
226 assert_eq!(content, "hello world");
227
228 let _ = std::fs::remove_dir_all(&dir);
229 }
230
231 #[tokio::test]
232 async fn test_write_file_creates_parent_dirs() {
233 let dir = std::env::temp_dir().join(format!("microclaw_wf2_{}", uuid::Uuid::new_v4()));
234 let file = dir.join("sub").join("dir").join("file.txt");
235
236 let tool = WriteFileTool::new(".");
237 let result = tool
238 .execute(json!({"path": file.to_str().unwrap(), "content": "nested"}))
239 .await;
240 assert!(!result.is_error);
241 assert_eq!(std::fs::read_to_string(&file).unwrap(), "nested");
242
243 let _ = std::fs::remove_dir_all(&dir);
244 }
245
246 #[tokio::test]
247 async fn test_write_file_missing_params() {
248 let tool = WriteFileTool::new(".");
249
250 let result = tool.execute(json!({"content": "hello"})).await;
251 assert!(result.is_error);
252 assert!(result.content.contains("Missing 'path'"));
253
254 let result = tool.execute(json!({"path": "/tmp/x"})).await;
255 assert!(result.is_error);
256 assert!(result.content.contains("Missing 'content'"));
257 }
258
259 #[tokio::test]
260 async fn test_write_file_resolves_relative_to_working_dir() {
261 let root = std::env::temp_dir().join(format!("microclaw_wf3_{}", uuid::Uuid::new_v4()));
262 let work = root.join("workspace");
263 std::fs::create_dir_all(&work).unwrap();
264
265 let tool = WriteFileTool::new(work.to_str().unwrap());
266 let result = tool
267 .execute(json!({"path": "nested/out.txt", "content": "ok"}))
268 .await;
269 assert!(!result.is_error);
270 assert_eq!(
271 std::fs::read_to_string(work.join("shared/nested/out.txt")).unwrap(),
272 "ok"
273 );
274
275 let _ = std::fs::remove_dir_all(&root);
276 }
277}