Skip to main content

trusty_code/tools/fs/
write.rs

1//! `write_file` tool — create or overwrite a file, creating parent dirs as needed.
2//!
3//! Why: AI coding loops must be able to emit new source files. A structured
4//! `ToolExecutor` with explicit working-directory scoping is safer than a raw
5//! shell `echo >` or `cat >` call: path traversal is blocked at the tool boundary
6//! before anything touches the filesystem.
7//! What: `WriteFileTool` writes `content` to `path` (relative or absolute within
8//! `working_dir`), creating all missing parent directories. Existing files are
9//! overwritten atomically.
10//! Test: See `#[cfg(test)]` below — covers new file, parent dir creation,
11//! overwrite, and path traversal.
12
13use std::path::PathBuf;
14
15use async_trait::async_trait;
16use serde_json::{Value, json};
17
18use crate::tools::fs::{FsError, scoped_path};
19use crate::tools::traits::{ToolExecutor, ToolResult};
20
21/// `ToolExecutor` that creates or overwrites a file.
22///
23/// Why: Provides agents with a safe, sandboxed way to write files inside the
24/// working directory. Parent directories are created automatically so agents do
25/// not need a separate `mkdir` step.
26/// What: Implements `ToolExecutor` with `name = "write_file"`. Scopes all writes
27/// to `working_dir`; rejects traversal attempts.
28/// Test: `cargo test -p trusty-code -- tools::fs::write`.
29pub struct WriteFileTool {
30    working_dir: PathBuf,
31}
32
33impl WriteFileTool {
34    /// Construct a new `WriteFileTool` scoped to `working_dir`.
35    ///
36    /// Why: The working directory is the security boundary; it must be set at
37    /// construction time and cannot be overridden per-call by the LLM.
38    /// What: Stores `working_dir`.
39    /// Test: `write_creates_new_file`, et al.
40    pub fn new(working_dir: impl Into<PathBuf>) -> Self {
41        Self {
42            working_dir: working_dir.into(),
43        }
44    }
45
46    /// Write `content` to `path`, creating parent directories as needed.
47    ///
48    /// Why: Centralises the IO path so `execute` stays short.
49    /// What: Scopes path, creates parent dirs, writes bytes, returns unit.
50    /// Test: All `WriteFileTool` unit tests.
51    fn write_inner(&self, path: &std::path::Path, content: &str) -> Result<(), FsError> {
52        let scoped = scoped_path(&self.working_dir, path)?;
53
54        // Create any missing parent directories.
55        if let Some(parent) = scoped.parent() {
56            std::fs::create_dir_all(parent).map_err(|e| FsError::io(parent, e))?;
57        }
58
59        std::fs::write(&scoped, content).map_err(|e| FsError::io(&scoped, e))?;
60        Ok(())
61    }
62}
63
64#[async_trait]
65impl ToolExecutor for WriteFileTool {
66    fn name(&self) -> &str {
67        "write_file"
68    }
69
70    /// OpenAI function-call schema for `write_file`.
71    ///
72    /// Why: The LLM uses this schema to construct its tool call.
73    /// What: JSON object with `path` and `content` (both required).
74    /// Test: `schema_has_required_fields`.
75    fn schema(&self) -> Value {
76        json!({
77            "type": "function",
78            "function": {
79                "name": "write_file",
80                "description": "Create or overwrite a file with the provided content. Parent directories are created automatically. The path must be inside the working directory.",
81                "parameters": {
82                    "type": "object",
83                    "properties": {
84                        "path": {
85                            "type": "string",
86                            "description": "Relative or absolute path to the file (must be inside the working directory)."
87                        },
88                        "content": {
89                            "type": "string",
90                            "description": "Text content to write to the file."
91                        }
92                    },
93                    "required": ["path", "content"],
94                    "additionalProperties": false
95                }
96            }
97        })
98    }
99
100    /// Execute a `write_file` tool call.
101    ///
102    /// Why: Writes content to a file within the working directory.
103    /// What: Parses `{path, content}` from `args`, calls `write_inner`, and
104    /// converts the result into a `ToolResult`.
105    /// Test: `write_creates_new_file`, `write_creates_parent_dirs`, etc.
106    async fn execute(&self, args: Value) -> ToolResult {
107        let Some(path_str) = args.get("path").and_then(Value::as_str) else {
108            return ToolResult::err("write_file: missing required argument 'path'");
109        };
110        let Some(content) = args.get("content").and_then(Value::as_str) else {
111            return ToolResult::err("write_file: missing required argument 'content'");
112        };
113
114        match self.write_inner(std::path::Path::new(path_str), content) {
115            Ok(()) => ToolResult::ok(format!("wrote {path_str}")),
116            Err(e) => ToolResult::err(e.to_string()),
117        }
118    }
119}
120
121// ── Tests ─────────────────────────────────────────────────────────────────────
122
123#[cfg(test)]
124mod tests {
125    use std::fs;
126
127    use serde_json::json;
128
129    use super::*;
130    use crate::tools::traits::ToolExecutor;
131
132    fn make_tool(tmp: &tempfile::TempDir) -> WriteFileTool {
133        WriteFileTool::new(tmp.path())
134    }
135
136    /// `write_file` creates a new file with the provided content.
137    ///
138    /// Why: Basic contract — write then re-read must return the same bytes.
139    /// What: `execute({path:"new.py", content:"# hello"})`, then read the file.
140    /// Test: This test.
141    #[tokio::test]
142    async fn write_creates_new_file() {
143        let tmp = tempfile::tempdir().expect("tempdir");
144        let tool = make_tool(&tmp);
145        let result = tool
146            .execute(json!({"path": "new.py", "content": "# hello"}))
147            .await;
148        assert!(!result.is_error(), "unexpected error: {}", result.content());
149        let content = fs::read_to_string(tmp.path().join("new.py")).expect("read back");
150        assert_eq!(content, "# hello");
151    }
152
153    /// `write_file` creates missing parent directories.
154    ///
155    /// Why: AI agents write deeply-nested files (e.g. `src/pkg/__init__.py`).
156    /// What: Write to `a/b/c.txt`; assert all dirs created and file readable.
157    /// Test: This test.
158    #[tokio::test]
159    async fn write_creates_parent_dirs() {
160        let tmp = tempfile::tempdir().expect("tempdir");
161        let tool = make_tool(&tmp);
162        let result = tool
163            .execute(json!({"path": "a/b/c.txt", "content": "deep"}))
164            .await;
165        assert!(!result.is_error(), "{}", result.content());
166        let content = fs::read_to_string(tmp.path().join("a/b/c.txt")).expect("read back");
167        assert_eq!(content, "deep");
168    }
169
170    /// `write_file` overwrites an existing file.
171    ///
172    /// Why: Agents re-emit files during iteration; overwrite must succeed.
173    /// What: Write `v1`, then write `v2` to the same path, assert `v2` on disk.
174    /// Test: This test.
175    #[tokio::test]
176    async fn write_overwrites_existing_file() {
177        let tmp = tempfile::tempdir().expect("tempdir");
178        fs::write(tmp.path().join("f.txt"), "v1").expect("seed");
179        let tool = make_tool(&tmp);
180        let result = tool
181            .execute(json!({"path": "f.txt", "content": "v2"}))
182            .await;
183        assert!(!result.is_error(), "{}", result.content());
184        let content = fs::read_to_string(tmp.path().join("f.txt")).expect("read back");
185        assert_eq!(content, "v2");
186    }
187
188    /// `write_file` rejects a path that escapes the working directory.
189    ///
190    /// Why: Path traversal must be blocked at the tool boundary.
191    /// What: `execute({path:"../../evil.sh", content:"..."})` must return error.
192    /// Test: This test.
193    #[tokio::test]
194    async fn path_traversal_is_rejected() {
195        let tmp = tempfile::tempdir().expect("tempdir");
196        let tool = make_tool(&tmp);
197        let result = tool
198            .execute(json!({"path": "../../evil.sh", "content": "harm"}))
199            .await;
200        assert!(result.is_error());
201        assert!(
202            result.content().contains("escapes"),
203            "unexpected message: {}",
204            result.content()
205        );
206    }
207
208    /// The schema lists both `path` and `content` as required.
209    ///
210    /// Why: The LLM must always provide both arguments.
211    /// What: Parses `schema()` and checks both appear in `required`.
212    /// Test: This test.
213    #[test]
214    fn schema_has_required_fields() {
215        let tmp = tempfile::tempdir().expect("tempdir");
216        let tool = make_tool(&tmp);
217        let schema = tool.schema();
218        let required = schema["function"]["parameters"]["required"]
219            .as_array()
220            .expect("required array");
221        let names: Vec<&str> = required.iter().filter_map(Value::as_str).collect();
222        assert!(names.contains(&"path"), "must require 'path'");
223        assert!(names.contains(&"content"), "must require 'content'");
224    }
225}