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. On success it also best-effort fires a mid-task
10//! incremental trusty-search index update for the written path (issue:
11//! mid-task incremental re-indexing) so `search_code` sees code written
12//! during the task, not just what existed at task start.
13//! Test: See `#[cfg(test)]` below — covers new file, parent dir creation,
14//! overwrite, and path traversal.
15
16use std::path::PathBuf;
17use std::sync::Arc;
18
19use async_trait::async_trait;
20use serde_json::{Value, json};
21
22use crate::tools::fs::{FsError, scoped_path};
23use crate::tools::traits::{ToolExecutor, ToolResult};
24
25/// Signature for the mid-task incremental index hook fired after a successful
26/// write (issue: mid-task incremental re-indexing).
27///
28/// Why: boxed as a trait object (not called inline) so tests can inject a
29/// closure that records its arguments and observe that `execute` actually
30/// invokes it, WITHOUT depending on trusty-search's real, process-global
31/// daemon-discovery mechanism (`TRUSTY_DATA_DIR_OVERRIDE` + the on-disk
32/// `http_addr` file). That mechanism is unsafe to mutate from a single test in
33/// this crate's parallel suite: once this hook is wired into `execute`, EVERY
34/// concurrently-running write-tool test would also attempt to resolve and
35/// notify whatever daemon address a test-under-observation happened to have
36/// configured at that instant, causing nondeterministic cross-talk between
37/// unrelated tests (observed directly while developing this hook — a
38/// TCP-mock-daemon-based first draft of this test intermittently captured
39/// ANOTHER test's write instead of its own). Mirrors `RecallSessionTool`'s
40/// existing `rpc_url` constructor-injection precedent in this same crate,
41/// generalised to a full callback since `trusty_common::search_index` has no
42/// injectable base-URL parameter.
43/// What: `(working_dir, paths)` — the exact arguments
44/// [`trusty_common::search_index::index_files_best_effort`] expects; the
45/// default (production) notifier is that function itself.
46type IndexNotifier = Arc<dyn Fn(&std::path::Path, &[PathBuf]) + Send + Sync>;
47
48/// `ToolExecutor` that creates or overwrites a file.
49///
50/// Why: Provides agents with a safe, sandboxed way to write files inside the
51/// working directory. Parent directories are created automatically so agents do
52/// not need a separate `mkdir` step.
53/// What: Implements `ToolExecutor` with `name = "write_file"`. Scopes all writes
54/// to `working_dir`; rejects traversal attempts.
55/// Test: `cargo test -p trusty-code -- tools::fs::write`.
56pub struct WriteFileTool {
57    working_dir: PathBuf,
58    index_notifier: IndexNotifier,
59}
60
61impl WriteFileTool {
62    /// Construct a new `WriteFileTool` scoped to `working_dir`.
63    ///
64    /// Why: The working directory is the security boundary; it must be set at
65    /// construction time and cannot be overridden per-call by the LLM.
66    /// What: Stores `working_dir`; wires `index_notifier` to the real
67    /// production hook, [`trusty_common::search_index::index_files_best_effort`].
68    /// Test: `write_creates_new_file`, et al.
69    pub fn new(working_dir: impl Into<PathBuf>) -> Self {
70        Self {
71            working_dir: working_dir.into(),
72            index_notifier: Arc::new(trusty_common::search_index::index_files_best_effort),
73        }
74    }
75
76    /// Override the mid-task incremental-index hook for testing.
77    ///
78    /// Why: lets a test observe that `execute` invokes the hook (and with
79    /// what arguments) on a successful write, without touching trusty-search's
80    /// real, process-global daemon-discovery state — see [`IndexNotifier`]'s
81    /// doc comment for why that matters in this crate's parallel test suite.
82    /// What: replaces `index_notifier`. Test-only (`#[cfg(test)]`); no
83    /// production call site can reach this.
84    /// Test: `write_file_success_triggers_incremental_index_update`,
85    /// `write_file_failure_does_not_trigger_incremental_index_update`.
86    #[cfg(test)]
87    fn with_index_notifier(
88        mut self,
89        notifier: impl Fn(&std::path::Path, &[PathBuf]) + Send + Sync + 'static,
90    ) -> Self {
91        self.index_notifier = Arc::new(notifier);
92        self
93    }
94
95    /// Write `content` to `path`, creating parent directories as needed.
96    ///
97    /// Why: Centralises the IO path so `execute` stays short.
98    /// What: Scopes path, creates parent dirs, writes bytes, returns unit.
99    /// Test: All `WriteFileTool` unit tests.
100    fn write_inner(&self, path: &std::path::Path, content: &str) -> Result<(), FsError> {
101        let scoped = scoped_path(&self.working_dir, path)?;
102
103        // Create any missing parent directories.
104        if let Some(parent) = scoped.parent() {
105            std::fs::create_dir_all(parent).map_err(|e| FsError::io(parent, e))?;
106        }
107
108        std::fs::write(&scoped, content).map_err(|e| FsError::io(&scoped, e))?;
109        Ok(())
110    }
111}
112
113#[async_trait]
114impl ToolExecutor for WriteFileTool {
115    fn name(&self) -> &str {
116        "write_file"
117    }
118
119    /// OpenAI function-call schema for `write_file`.
120    ///
121    /// Why: The LLM uses this schema to construct its tool call.
122    /// What: JSON object with `path` and `content` (both required).
123    /// Test: `schema_has_required_fields`.
124    fn schema(&self) -> Value {
125        json!({
126            "type": "function",
127            "function": {
128                "name": "write_file",
129                "description": "Create or overwrite a file with the provided content. Parent directories are created automatically. The path must be inside the working directory.",
130                "parameters": {
131                    "type": "object",
132                    "properties": {
133                        "path": {
134                            "type": "string",
135                            "description": "Relative or absolute path to the file (must be inside the working directory)."
136                        },
137                        "content": {
138                            "type": "string",
139                            "description": "Text content to write to the file."
140                        }
141                    },
142                    "required": ["path", "content"],
143                    "additionalProperties": false
144                }
145            }
146        })
147    }
148
149    /// Execute a `write_file` tool call.
150    ///
151    /// Why: Writes content to a file within the working directory.
152    /// What: Parses `{path, content}` from `args`, calls `write_inner`, and
153    /// converts the result into a `ToolResult`. On success, best-effort fires
154    /// a mid-task incremental trusty-search index update (issue: mid-task
155    /// incremental re-indexing) for the written path so `search_code` can see
156    /// it within the same task — this never affects the returned
157    /// `ToolResult`; see [`trusty_common::search_index::index_files_best_effort`]'s
158    /// fail-open contract.
159    /// Test: `write_creates_new_file`, `write_creates_parent_dirs`, etc.
160    async fn execute(&self, args: Value) -> ToolResult {
161        let Some(path_str) = args.get("path").and_then(Value::as_str) else {
162            return ToolResult::err("write_file: missing required argument 'path'");
163        };
164        let Some(content) = args.get("content").and_then(Value::as_str) else {
165            return ToolResult::err("write_file: missing required argument 'content'");
166        };
167
168        match self.write_inner(std::path::Path::new(path_str), content) {
169            Ok(()) => {
170                (self.index_notifier)(&self.working_dir, &[PathBuf::from(path_str)]);
171                ToolResult::ok(format!("wrote {path_str}"))
172            }
173            Err(e) => ToolResult::err(e.to_string()),
174        }
175    }
176}
177
178// ── Tests ─────────────────────────────────────────────────────────────────────
179
180#[cfg(test)]
181mod tests {
182    use std::fs;
183
184    use serde_json::json;
185
186    use super::*;
187    use crate::tools::traits::ToolExecutor;
188
189    fn make_tool(tmp: &tempfile::TempDir) -> WriteFileTool {
190        WriteFileTool::new(tmp.path())
191    }
192
193    /// `write_file` creates a new file with the provided content.
194    ///
195    /// Why: Basic contract — write then re-read must return the same bytes.
196    /// What: `execute({path:"new.py", content:"# hello"})`, then read the file.
197    /// Test: This test.
198    #[tokio::test]
199    async fn write_creates_new_file() {
200        let tmp = tempfile::tempdir().expect("tempdir");
201        let tool = make_tool(&tmp);
202        let result = tool
203            .execute(json!({"path": "new.py", "content": "# hello"}))
204            .await;
205        assert!(!result.is_error(), "unexpected error: {}", result.content());
206        let content = fs::read_to_string(tmp.path().join("new.py")).expect("read back");
207        assert_eq!(content, "# hello");
208    }
209
210    /// `write_file` creates missing parent directories.
211    ///
212    /// Why: AI agents write deeply-nested files (e.g. `src/pkg/__init__.py`).
213    /// What: Write to `a/b/c.txt`; assert all dirs created and file readable.
214    /// Test: This test.
215    #[tokio::test]
216    async fn write_creates_parent_dirs() {
217        let tmp = tempfile::tempdir().expect("tempdir");
218        let tool = make_tool(&tmp);
219        let result = tool
220            .execute(json!({"path": "a/b/c.txt", "content": "deep"}))
221            .await;
222        assert!(!result.is_error(), "{}", result.content());
223        let content = fs::read_to_string(tmp.path().join("a/b/c.txt")).expect("read back");
224        assert_eq!(content, "deep");
225    }
226
227    /// `write_file` overwrites an existing file.
228    ///
229    /// Why: Agents re-emit files during iteration; overwrite must succeed.
230    /// What: Write `v1`, then write `v2` to the same path, assert `v2` on disk.
231    /// Test: This test.
232    #[tokio::test]
233    async fn write_overwrites_existing_file() {
234        let tmp = tempfile::tempdir().expect("tempdir");
235        fs::write(tmp.path().join("f.txt"), "v1").expect("seed");
236        let tool = make_tool(&tmp);
237        let result = tool
238            .execute(json!({"path": "f.txt", "content": "v2"}))
239            .await;
240        assert!(!result.is_error(), "{}", result.content());
241        let content = fs::read_to_string(tmp.path().join("f.txt")).expect("read back");
242        assert_eq!(content, "v2");
243    }
244
245    /// `write_file` rejects a path that escapes the working directory.
246    ///
247    /// Why: Path traversal must be blocked at the tool boundary.
248    /// What: `execute({path:"../../evil.sh", content:"..."})` must return error.
249    /// Test: This test.
250    #[tokio::test]
251    async fn path_traversal_is_rejected() {
252        let tmp = tempfile::tempdir().expect("tempdir");
253        let tool = make_tool(&tmp);
254        let result = tool
255            .execute(json!({"path": "../../evil.sh", "content": "harm"}))
256            .await;
257        assert!(result.is_error());
258        assert!(
259            result.content().contains("escapes"),
260            "unexpected message: {}",
261            result.content()
262        );
263    }
264
265    /// The schema lists both `path` and `content` as required.
266    ///
267    /// Why: The LLM must always provide both arguments.
268    /// What: Parses `schema()` and checks both appear in `required`.
269    /// Test: This test.
270    #[test]
271    fn schema_has_required_fields() {
272        let tmp = tempfile::tempdir().expect("tempdir");
273        let tool = make_tool(&tmp);
274        let schema = tool.schema();
275        let required = schema["function"]["parameters"]["required"]
276            .as_array()
277            .expect("required array");
278        let names: Vec<&str> = required.iter().filter_map(Value::as_str).collect();
279        assert!(names.contains(&"path"), "must require 'path'");
280        assert!(names.contains(&"content"), "must require 'content'");
281    }
282
283    // ── Mid-task incremental re-index hook ──────────────────────────────────
284
285    /// Recorded `(working_dir, paths)` arguments from a test's injected
286    /// `index_notifier` closure.
287    type RecordedCalls = Arc<std::sync::Mutex<Vec<(PathBuf, Vec<PathBuf>)>>>;
288
289    /// A successful `write_file` invokes the mid-task incremental
290    /// trusty-search index hook exactly once, with the working directory and
291    /// the written path.
292    ///
293    /// Why: this is the acceptance criterion for the "search_code sees code
294    /// written during the task" feature — without this hook, `search_code`
295    /// only ever reflects the project's state at task start. Uses the
296    /// injectable `index_notifier` seam (see its doc comment) rather than a
297    /// real network daemon, so this test has zero dependence on process-global
298    /// state and cannot race with any other test in this crate's parallel
299    /// suite.
300    /// What: constructs a `WriteFileTool` with a notifier that records its
301    /// arguments into a shared `Vec`, writes a file, asserts the write
302    /// succeeded, and asserts the notifier fired exactly once with the
303    /// tool's `working_dir` and `[path]`.
304    /// Test: this test.
305    #[tokio::test]
306    async fn write_file_success_triggers_incremental_index_update() {
307        let calls: RecordedCalls = Arc::new(std::sync::Mutex::new(Vec::new()));
308        let recorder = calls.clone();
309        let tmp = tempfile::tempdir().expect("tempdir");
310        let tool = WriteFileTool::new(tmp.path()).with_index_notifier(move |root, paths| {
311            recorder
312                .lock()
313                .expect("lock")
314                .push((root.to_path_buf(), paths.to_vec()));
315        });
316
317        let result = tool
318            .execute(json!({"path": "src/lib.rs", "content": "pub fn hi() {}\n"}))
319            .await;
320        assert!(!result.is_error(), "{}", result.content());
321
322        let recorded = calls.lock().expect("lock");
323        assert_eq!(
324            recorded.len(),
325            1,
326            "the incremental-index hook must fire exactly once for a successful write"
327        );
328        let (root, paths) = &recorded[0];
329        assert_eq!(root, tmp.path());
330        assert_eq!(paths, &[PathBuf::from("src/lib.rs")]);
331    }
332
333    /// A FAILED `write_file` (path traversal) does NOT invoke the
334    /// incremental-index hook.
335    ///
336    /// Why: the hook only makes sense for content that actually landed on
337    /// disk; firing it for a rejected write would post stale-or-nonexistent
338    /// file state to the index.
339    /// What: constructs a `WriteFileTool` with a recording notifier, attempts
340    /// a traversal-escaping write, asserts it errors, and asserts the
341    /// notifier never fired.
342    /// Test: this test.
343    #[tokio::test]
344    async fn write_file_failure_does_not_trigger_incremental_index_update() {
345        let calls: RecordedCalls = Arc::new(std::sync::Mutex::new(Vec::new()));
346        let recorder = calls.clone();
347        let tmp = tempfile::tempdir().expect("tempdir");
348        let tool = WriteFileTool::new(tmp.path()).with_index_notifier(move |root, paths| {
349            recorder
350                .lock()
351                .expect("lock")
352                .push((root.to_path_buf(), paths.to_vec()));
353        });
354
355        let result = tool
356            .execute(json!({"path": "../../evil.sh", "content": "harm"}))
357            .await;
358        assert!(result.is_error());
359        assert!(
360            calls.lock().expect("lock").is_empty(),
361            "the incremental-index hook must not fire for a failed write"
362        );
363    }
364}