use std::path::PathBuf;
use std::sync::Arc;
use async_trait::async_trait;
use serde_json::{Value, json};
use crate::tools::fs::{FsError, scoped_path};
use crate::tools::traits::{ToolExecutor, ToolResult};
type IndexNotifier = Arc<dyn Fn(&std::path::Path, &[PathBuf]) + Send + Sync>;
pub struct WriteFileTool {
working_dir: PathBuf,
index_notifier: IndexNotifier,
}
impl WriteFileTool {
pub fn new(working_dir: impl Into<PathBuf>) -> Self {
Self {
working_dir: working_dir.into(),
index_notifier: Arc::new(trusty_common::search_index::index_files_best_effort),
}
}
#[cfg(test)]
fn with_index_notifier(
mut self,
notifier: impl Fn(&std::path::Path, &[PathBuf]) + Send + Sync + 'static,
) -> Self {
self.index_notifier = Arc::new(notifier);
self
}
fn write_inner(&self, path: &std::path::Path, content: &str) -> Result<(), FsError> {
let scoped = scoped_path(&self.working_dir, path)?;
if let Some(parent) = scoped.parent() {
std::fs::create_dir_all(parent).map_err(|e| FsError::io(parent, e))?;
}
std::fs::write(&scoped, content).map_err(|e| FsError::io(&scoped, e))?;
Ok(())
}
}
#[async_trait]
impl ToolExecutor for WriteFileTool {
fn name(&self) -> &str {
"write_file"
}
fn schema(&self) -> Value {
json!({
"type": "function",
"function": {
"name": "write_file",
"description": "Create or overwrite a file with the provided content. Parent directories are created automatically. The path must be inside the working directory.",
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Relative or absolute path to the file (must be inside the working directory)."
},
"content": {
"type": "string",
"description": "Text content to write to the file."
}
},
"required": ["path", "content"],
"additionalProperties": false
}
}
})
}
async fn execute(&self, args: Value) -> ToolResult {
let Some(path_str) = args.get("path").and_then(Value::as_str) else {
return ToolResult::err("write_file: missing required argument 'path'");
};
let Some(content) = args.get("content").and_then(Value::as_str) else {
return ToolResult::err("write_file: missing required argument 'content'");
};
match self.write_inner(std::path::Path::new(path_str), content) {
Ok(()) => {
(self.index_notifier)(&self.working_dir, &[PathBuf::from(path_str)]);
ToolResult::ok(format!("wrote {path_str}"))
}
Err(e) => ToolResult::err(e.to_string()),
}
}
}
#[cfg(test)]
mod tests {
use std::fs;
use serde_json::json;
use super::*;
use crate::tools::traits::ToolExecutor;
fn make_tool(tmp: &tempfile::TempDir) -> WriteFileTool {
WriteFileTool::new(tmp.path())
}
#[tokio::test]
async fn write_creates_new_file() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = make_tool(&tmp);
let result = tool
.execute(json!({"path": "new.py", "content": "# hello"}))
.await;
assert!(!result.is_error(), "unexpected error: {}", result.content());
let content = fs::read_to_string(tmp.path().join("new.py")).expect("read back");
assert_eq!(content, "# hello");
}
#[tokio::test]
async fn write_creates_parent_dirs() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = make_tool(&tmp);
let result = tool
.execute(json!({"path": "a/b/c.txt", "content": "deep"}))
.await;
assert!(!result.is_error(), "{}", result.content());
let content = fs::read_to_string(tmp.path().join("a/b/c.txt")).expect("read back");
assert_eq!(content, "deep");
}
#[tokio::test]
async fn write_overwrites_existing_file() {
let tmp = tempfile::tempdir().expect("tempdir");
fs::write(tmp.path().join("f.txt"), "v1").expect("seed");
let tool = make_tool(&tmp);
let result = tool
.execute(json!({"path": "f.txt", "content": "v2"}))
.await;
assert!(!result.is_error(), "{}", result.content());
let content = fs::read_to_string(tmp.path().join("f.txt")).expect("read back");
assert_eq!(content, "v2");
}
#[tokio::test]
async fn path_traversal_is_rejected() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = make_tool(&tmp);
let result = tool
.execute(json!({"path": "../../evil.sh", "content": "harm"}))
.await;
assert!(result.is_error());
assert!(
result.content().contains("escapes"),
"unexpected message: {}",
result.content()
);
}
#[test]
fn schema_has_required_fields() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = make_tool(&tmp);
let schema = tool.schema();
let required = schema["function"]["parameters"]["required"]
.as_array()
.expect("required array");
let names: Vec<&str> = required.iter().filter_map(Value::as_str).collect();
assert!(names.contains(&"path"), "must require 'path'");
assert!(names.contains(&"content"), "must require 'content'");
}
type RecordedCalls = Arc<std::sync::Mutex<Vec<(PathBuf, Vec<PathBuf>)>>>;
#[tokio::test]
async fn write_file_success_triggers_incremental_index_update() {
let calls: RecordedCalls = Arc::new(std::sync::Mutex::new(Vec::new()));
let recorder = calls.clone();
let tmp = tempfile::tempdir().expect("tempdir");
let tool = WriteFileTool::new(tmp.path()).with_index_notifier(move |root, paths| {
recorder
.lock()
.expect("lock")
.push((root.to_path_buf(), paths.to_vec()));
});
let result = tool
.execute(json!({"path": "src/lib.rs", "content": "pub fn hi() {}\n"}))
.await;
assert!(!result.is_error(), "{}", result.content());
let recorded = calls.lock().expect("lock");
assert_eq!(
recorded.len(),
1,
"the incremental-index hook must fire exactly once for a successful write"
);
let (root, paths) = &recorded[0];
assert_eq!(root, tmp.path());
assert_eq!(paths, &[PathBuf::from("src/lib.rs")]);
}
#[tokio::test]
async fn write_file_failure_does_not_trigger_incremental_index_update() {
let calls: RecordedCalls = Arc::new(std::sync::Mutex::new(Vec::new()));
let recorder = calls.clone();
let tmp = tempfile::tempdir().expect("tempdir");
let tool = WriteFileTool::new(tmp.path()).with_index_notifier(move |root, paths| {
recorder
.lock()
.expect("lock")
.push((root.to_path_buf(), paths.to_vec()));
});
let result = tool
.execute(json!({"path": "../../evil.sh", "content": "harm"}))
.await;
assert!(result.is_error());
assert!(
calls.lock().expect("lock").is_empty(),
"the incremental-index hook must not fire for a failed write"
);
}
}