Skip to main content

trusty_code/tools/fs/
write_files.rs

1//! `write_files` tool — create or overwrite MANY files in a single call.
2//!
3//! Why: `write_file` is one-file-per-call, and on every bake-off run the file
4//! count equalled the write-turn count 1:1 — an 8-file scaffold cost 8 turns,
5//! the single biggest driver of tcode's high agent-turn count. PR #2666 lets the
6//! loop execute several tool calls per turn, but the model does not always batch;
7//! a dedicated `write_files` tool decouples turn-count from file-count
8//! STRUCTURALLY — one call writes N files regardless of whether the model
9//! batches. (#2681.)
10//! What: `WriteFilesTool` takes a `files` array of `{path, content}` objects,
11//! writes each (creating parent dirs) scoped to `working_dir`, and reports a
12//! per-file result. A failure on one file does not abort the others — every
13//! file's outcome is reported so the model can retry only what failed. Every
14//! successfully written path is batched into ONE best-effort mid-task
15//! incremental trusty-search index update (issue: mid-task incremental
16//! re-indexing) so `search_code` sees the whole batch within the same task.
17//! Test: See `#[cfg(test)]` below — covers a multi-file write, partial failure,
18//! empty array, and path traversal.
19
20use std::path::PathBuf;
21
22use async_trait::async_trait;
23use serde_json::{Value, json};
24
25use crate::tools::fs::{FsError, scoped_path};
26use crate::tools::traits::{ToolExecutor, ToolResult};
27
28/// Canonical name of the batch-write tool.
29///
30/// Why: Referenced by the registry wiring and by tests that assert the tool is
31/// registered; a shared constant avoids stringly-typed drift.
32/// What: The function name exposed to the LLM.
33/// Test: `crate::tools::fs_registry_tests` (batch-write registration).
34pub const WRITE_FILES_TOOL_NAME: &str = "write_files";
35
36/// `ToolExecutor` that creates or overwrites a batch of files in one call.
37///
38/// Why: Structurally decouples turn-count from file-count so an N-file scaffold
39/// is one turn, not N (the dominant bake-off turn sink).
40/// What: Implements `ToolExecutor` with `name = "write_files"`; scopes every
41/// write to `working_dir`; rejects traversal per-file without aborting siblings.
42/// Test: `cargo test -p trusty-code -- tools::fs::write_files`.
43pub struct WriteFilesTool {
44    working_dir: PathBuf,
45}
46
47impl WriteFilesTool {
48    /// Construct a new `WriteFilesTool` scoped to `working_dir`.
49    ///
50    /// Why: The working directory is the security boundary; set once at
51    /// construction so the LLM cannot widen it per-call.
52    /// What: Stores `working_dir`.
53    /// Test: `write_files_writes_all`, et al.
54    pub fn new(working_dir: impl Into<PathBuf>) -> Self {
55        Self {
56            working_dir: working_dir.into(),
57        }
58    }
59
60    /// Write a single `{path, content}` entry, creating parent dirs as needed.
61    ///
62    /// Why: Reuses the same scoped-write contract as `WriteFileTool` so batch and
63    /// single writes behave identically per-file.
64    /// What: Scopes path, creates parent dirs, writes bytes.
65    /// Test: Exercised by all `WriteFilesTool` unit tests.
66    fn write_one(&self, path: &str, content: &str) -> Result<(), FsError> {
67        let scoped = scoped_path(&self.working_dir, std::path::Path::new(path))?;
68        if let Some(parent) = scoped.parent() {
69            std::fs::create_dir_all(parent).map_err(|e| FsError::io(parent, e))?;
70        }
71        std::fs::write(&scoped, content).map_err(|e| FsError::io(&scoped, e))?;
72        Ok(())
73    }
74}
75
76#[async_trait]
77impl ToolExecutor for WriteFilesTool {
78    fn name(&self) -> &str {
79        WRITE_FILES_TOOL_NAME
80    }
81
82    /// OpenAI function-call schema for `write_files`.
83    ///
84    /// Why: The LLM constructs its call from this schema; the `files` array
85    /// mirrors the `execute` contract exactly.
86    /// What: JSON object with a required `files` array of `{path, content}`.
87    /// Test: `schema_requires_files_array`.
88    fn schema(&self) -> Value {
89        json!({
90            "type": "function",
91            "function": {
92                "name": WRITE_FILES_TOOL_NAME,
93                "description": "Create or overwrite MULTIPLE files in a single call. Prefer this over several separate write_file calls when scaffolding independent files — it writes them all in one turn. Parent directories are created automatically. Each path must be inside the working directory.",
94                "parameters": {
95                    "type": "object",
96                    "properties": {
97                        "files": {
98                            "type": "array",
99                            "description": "The files to write. Each element is an object with a path and its full content.",
100                            "items": {
101                                "type": "object",
102                                "properties": {
103                                    "path": {
104                                        "type": "string",
105                                        "description": "Relative or absolute path (must be inside the working directory)."
106                                    },
107                                    "content": {
108                                        "type": "string",
109                                        "description": "Full text content to write to the file."
110                                    }
111                                },
112                                "required": ["path", "content"],
113                                "additionalProperties": false
114                            }
115                        }
116                    },
117                    "required": ["files"],
118                    "additionalProperties": false
119                }
120            }
121        })
122    }
123
124    /// Execute a `write_files` tool call.
125    ///
126    /// Why: Writes every file in the batch, reporting each outcome so a single
127    /// bad entry does not lose the successful writes.
128    /// What: Parses `{files:[{path, content}, …]}`, writes each, and returns a
129    /// per-file summary. Returns an error only when `files` is missing/not an
130    /// array, or when EVERY write failed. Batches every SUCCESSFULLY written
131    /// path into ONE best-effort mid-task incremental trusty-search index
132    /// update (issue: mid-task incremental re-indexing) so `search_code` can
133    /// see the whole batch within the same task — this never affects the
134    /// returned `ToolResult`; see
135    /// [`trusty_common::search_index::index_files_best_effort`]'s fail-open
136    /// contract.
137    /// Test: `write_files_writes_all`, `write_files_partial_failure`.
138    async fn execute(&self, args: Value) -> ToolResult {
139        let Some(files) = args.get("files").and_then(Value::as_array) else {
140            return ToolResult::err("write_files: missing required argument 'files' (an array)");
141        };
142        if files.is_empty() {
143            return ToolResult::err("write_files: 'files' array is empty — nothing to write");
144        }
145
146        let mut lines = Vec::with_capacity(files.len());
147        let mut ok_count = 0usize;
148        let mut written_paths = Vec::with_capacity(files.len());
149        for (i, entry) in files.iter().enumerate() {
150            let path = entry.get("path").and_then(Value::as_str);
151            let content = entry.get("content").and_then(Value::as_str);
152            match (path, content) {
153                (Some(p), Some(c)) => match self.write_one(p, c) {
154                    Ok(()) => {
155                        ok_count += 1;
156                        lines.push(format!("wrote {p}"));
157                        written_paths.push(PathBuf::from(p));
158                    }
159                    Err(e) => lines.push(format!("FAILED {p}: {e}")),
160                },
161                _ => lines.push(format!(
162                    "FAILED entry {i}: each element needs both 'path' and 'content'"
163                )),
164            }
165        }
166
167        if !written_paths.is_empty() {
168            trusty_common::search_index::index_files_best_effort(&self.working_dir, &written_paths);
169        }
170
171        let summary = lines.join("\n");
172        if ok_count == 0 {
173            // Every write failed — surface as a recoverable error so the model
174            // retries rather than treating the batch as done.
175            ToolResult::err(summary)
176        } else {
177            ToolResult::ok(format!(
178                "{summary}\n({ok_count}/{} files written)",
179                files.len()
180            ))
181        }
182    }
183}
184
185// ── Tests ─────────────────────────────────────────────────────────────────────
186
187#[cfg(test)]
188mod tests {
189    use std::fs;
190
191    use serde_json::json;
192
193    use super::*;
194    use crate::tools::traits::ToolExecutor;
195
196    /// `write_files` writes every file in the batch in a single call.
197    ///
198    /// Why: This is the structural turn-count/file-count decoupling — one call,
199    /// N files (#2681).
200    /// What: Writes three files (one nested), asserts all three land on disk with
201    /// the right content and the summary reports 3/3.
202    /// Test: This test.
203    #[tokio::test]
204    async fn write_files_writes_all() {
205        let tmp = tempfile::tempdir().expect("tempdir");
206        let tool = WriteFilesTool::new(tmp.path());
207        let result = tool
208            .execute(json!({
209                "files": [
210                    {"path": "a.py", "content": "# a"},
211                    {"path": "pkg/b.py", "content": "# b"},
212                    {"path": "src/main.rs", "content": "fn main() {}"}
213                ]
214            }))
215            .await;
216        assert!(!result.is_error(), "unexpected error: {}", result.content());
217        assert_eq!(fs::read_to_string(tmp.path().join("a.py")).unwrap(), "# a");
218        assert_eq!(
219            fs::read_to_string(tmp.path().join("pkg/b.py")).unwrap(),
220            "# b"
221        );
222        assert_eq!(
223            fs::read_to_string(tmp.path().join("src/main.rs")).unwrap(),
224            "fn main() {}"
225        );
226        assert!(result.content().contains("3/3"), "{}", result.content());
227    }
228
229    /// A single bad entry does not abort the successful writes.
230    ///
231    /// Why: Partial failure must preserve the good writes and report the bad one,
232    /// mirroring the batched-tool-dispatch contract.
233    /// What: Batches a valid file and a traversal-escaping file; asserts the valid
234    /// one is written and the summary flags the failure.
235    /// Test: This test.
236    #[tokio::test]
237    async fn write_files_partial_failure() {
238        let tmp = tempfile::tempdir().expect("tempdir");
239        let tool = WriteFilesTool::new(tmp.path());
240        let result = tool
241            .execute(json!({
242                "files": [
243                    {"path": "good.py", "content": "ok"},
244                    {"path": "../../evil.sh", "content": "harm"}
245                ]
246            }))
247            .await;
248        // At least one succeeded → overall success with a per-file summary.
249        assert!(!result.is_error(), "{}", result.content());
250        assert_eq!(
251            fs::read_to_string(tmp.path().join("good.py")).unwrap(),
252            "ok"
253        );
254        assert!(result.content().contains("wrote good.py"));
255        assert!(
256            result.content().contains("FAILED"),
257            "must flag the failed entry: {}",
258            result.content()
259        );
260    }
261
262    /// An entirely-failing batch surfaces as an error.
263    ///
264    /// Why: If nothing was written, the model must retry, not treat it as done.
265    /// What: Batches a single traversal-escaping file; asserts an error result.
266    /// Test: This test.
267    #[tokio::test]
268    async fn write_files_all_fail_is_error() {
269        let tmp = tempfile::tempdir().expect("tempdir");
270        let tool = WriteFilesTool::new(tmp.path());
271        let result = tool
272            .execute(json!({"files": [{"path": "../../evil.sh", "content": "x"}]}))
273            .await;
274        assert!(result.is_error());
275        assert!(result.content().contains("FAILED"));
276    }
277
278    /// An empty `files` array is a recoverable error.
279    ///
280    /// Why: Nothing to write is a caller mistake worth surfacing.
281    /// What: `execute({files: []})` returns an error.
282    /// Test: This test.
283    #[tokio::test]
284    async fn write_files_empty_array_errors() {
285        let tmp = tempfile::tempdir().expect("tempdir");
286        let tool = WriteFilesTool::new(tmp.path());
287        let result = tool.execute(json!({"files": []})).await;
288        assert!(result.is_error());
289        assert!(result.content().contains("empty"));
290    }
291
292    /// The schema requires the `files` array.
293    ///
294    /// Why: The LLM must always provide the batch.
295    /// What: Parses `schema()` and checks `required` contains "files".
296    /// Test: This test.
297    #[test]
298    fn schema_requires_files_array() {
299        let tmp = tempfile::tempdir().expect("tempdir");
300        let tool = WriteFilesTool::new(tmp.path());
301        let schema = tool.schema();
302        let required = schema["function"]["parameters"]["required"]
303            .as_array()
304            .expect("required array");
305        assert!(
306            required.iter().any(|v| v.as_str() == Some("files")),
307            "schema must list 'files' as required"
308        );
309    }
310}