on main help sign in
perf(tools): eliminate redundant file read in write tool

When overwriting an existing file, os.ReadFile was called twice: once to check if content matches, and again to get oldContent for diff generation. Now reads once and reuses the result.

commite7a7bf3271ebe764818a1382ae49d713b4e06cd6 authoriko <mail@iko.soy> dateThu 9 Jul 2026, 02:58 (3 months ago) parentd3d1c35
1 file changed+7−11
internal/agent/tools/write.go+7−11
internal/agent/tools/write.go+7−11
@@ -66,6 +66,7 @@ func NewWriteTool(
6666 filePath := filepathext.SmartJoin(workingDir, params.FilePath)
6767
6868 fileInfo, err := os.Stat(filePath)
69+ oldContent := ""
6970 if err == nil {
7071 if fileInfo.IsDir() {
7172 return fantasy.NewTextErrorResponse(fmt.Sprintf("Path is a directory, not a file: %s", filePath)), nil
@@ -78,9 +79,12 @@ func NewWriteTool(
7879 filePath, modTime.Format(time.RFC3339), lastRead.Format(time.RFC3339))), nil
7980 }
8081
81− oldContent, readErr := os.ReadFile(filePath)
82− if readErr == nil && string(oldContent) == params.Content {
83− return fantasy.NewTextErrorResponse(fmt.Sprintf("File %s already contains the exact content. No changes made.", filePath)), nil
82+ oldBytes, readErr := os.ReadFile(filePath)
83+ if readErr == nil {
84+ oldContent = string(oldBytes)
85+ if oldContent == params.Content {
86+ return fantasy.NewTextErrorResponse(fmt.Sprintf("File %s already contains the exact content. No changes made.", filePath)), nil
87+ }
8488 }
8589 } else if !os.IsNotExist(err) {
8690 return fantasy.ToolResponse{}, fmt.Errorf("error checking file: %w", err)
@@ -91,14 +95,6 @@ func NewWriteTool(
9195 return fantasy.ToolResponse{}, fmt.Errorf("error creating directory: %w", err)
9296 }
9397
94− oldContent := ""
95− if fileInfo != nil && !fileInfo.IsDir() {
96− oldBytes, readErr := os.ReadFile(filePath)
97− if readErr == nil {
98− oldContent = string(oldBytes)
99− }
100− }
101−
10298 diff, additions, removals := diff.GenerateDiff(
10399 oldContent,
104100 params.Content,