diff --git a/tools/file/editfile.go b/tools/file/editfile.go index c1f43d7..2bad1bb 100644 --- a/tools/file/editfile.go +++ b/tools/file/editfile.go @@ -91,7 +91,11 @@ func (t *EditFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T newContent := strings.Replace(content, in.OldString, in.NewString, 1) - if err := os.WriteFile(in.Path, []byte(newContent), 0o644); err != nil { + mode := os.FileMode(0o600) + if info, statErr := os.Stat(in.Path); statErr == nil { + mode = info.Mode().Perm() + } + if err := tool.WriteFileAtomic(in.Path, []byte(newContent), mode); err != nil { return tool.ToolResult{Error: fmt.Sprintf("failed to write file: %v", err)}, nil } diff --git a/tools/file/editfile_perm_test.go b/tools/file/editfile_perm_test.go new file mode 100644 index 0000000..8289bea --- /dev/null +++ b/tools/file/editfile_perm_test.go @@ -0,0 +1,34 @@ +package file + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestEditFilePreservesMode(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "code.txt") + require.NoError(t, os.WriteFile(path, []byte("alpha beta"), 0o640)) + + tool := &EditFileTool{WorkDir: dir} + in, _ := json.Marshal(map[string]string{ + "path": path, + "old_string": "alpha", + "new_string": "gamma", + }) + res, err := tool.Execute(context.Background(), in) + require.NoError(t, err) + require.Empty(t, res.Error) + + data, _ := os.ReadFile(path) + require.Equal(t, "gamma beta", string(data)) + + info, err := os.Stat(path) + require.NoError(t, err) + require.Equal(t, os.FileMode(0o640), info.Mode().Perm()) +}