blob: 815cf88905bb40475cc65623817cf0583acd357e [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001package claudetool
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "go/parser"
10 "go/token"
11 "log/slog"
12 "os"
13 "path/filepath"
14 "strings"
15
Earl Lee2e463fb2025-04-17 11:22:22 -070016 "sketch.dev/claudetool/editbuf"
17 "sketch.dev/claudetool/patchkit"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070018 "sketch.dev/llm"
Earl Lee2e463fb2025-04-17 11:22:22 -070019)
20
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000021// PatchCallback defines the signature for patch tool callbacks.
22// It runs after the patch tool has executed.
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -070023// It receives the patch input and the tool output,
24// and returns a new, possibly altered tool output.
25type PatchCallback func(input PatchInput, output llm.ToolOut) llm.ToolOut
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000026
27// Patch creates a patch tool. The callback may be nil.
28func Patch(callback PatchCallback) *llm.Tool {
29 return &llm.Tool{
30 Name: PatchName,
31 Description: strings.TrimSpace(PatchDescription),
32 InputSchema: llm.MustSchema(PatchInputSchema),
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -070033 Run: func(ctx context.Context, m json.RawMessage) llm.ToolOut {
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000034 var input PatchInput
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -070035 output := patchRun(ctx, m, &input)
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000036 if callback != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -070037 return callback(input, output)
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000038 }
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -070039 return output
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000040 },
41 }
Earl Lee2e463fb2025-04-17 11:22:22 -070042}
43
44const (
45 PatchName = "patch"
46 PatchDescription = `
47File modification tool for precise text edits.
48
49Operations:
50- replace: Substitute text with new content
51- append_eof: Append new text at the end of the file
52- prepend_bof: Insert new text at the beginning of the file
53- overwrite: Replace the entire file with new content (automatically creates the file)
54
55Usage notes:
56- All inputs are interpreted literally (no automatic newline or whitespace handling)
57- For replace operations, oldText must appear EXACTLY ONCE in the file
58`
59
60 // If you modify this, update the termui template for prettier rendering.
61 PatchInputSchema = `
62{
63 "type": "object",
64 "required": ["path", "patches"],
65 "properties": {
66 "path": {
67 "type": "string",
68 "description": "Absolute path to the file to patch"
69 },
70 "patches": {
71 "type": "array",
72 "description": "List of patch requests to apply",
73 "items": {
74 "type": "object",
75 "required": ["operation", "newText"],
76 "properties": {
77 "operation": {
78 "type": "string",
79 "enum": ["replace", "append_eof", "prepend_bof", "overwrite"],
80 "description": "Type of operation to perform"
81 },
82 "oldText": {
83 "type": "string",
84 "description": "Text to locate for the operation (must be unique in file, required for replace)"
85 },
86 "newText": {
87 "type": "string",
88 "description": "The new text to use (empty for deletions)"
89 }
90 }
91 }
92 }
93 }
94}
95`
96)
97
98// TODO: maybe rename PatchRequest to PatchOperation or PatchSpec or PatchPart or just Patch?
99
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000100// PatchInput represents the input structure for patch operations.
101type PatchInput struct {
Earl Lee2e463fb2025-04-17 11:22:22 -0700102 Path string `json:"path"`
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000103 Patches []PatchRequest `json:"patches"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700104}
105
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000106// PatchRequest represents a single patch operation.
107type PatchRequest struct {
Earl Lee2e463fb2025-04-17 11:22:22 -0700108 Operation string `json:"operation"`
109 OldText string `json:"oldText,omitempty"`
110 NewText string `json:"newText,omitempty"`
111}
112
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000113// patchRun implements the guts of the patch tool.
114// It populates input from m.
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700115func patchRun(ctx context.Context, m json.RawMessage, input *PatchInput) llm.ToolOut {
Earl Lee2e463fb2025-04-17 11:22:22 -0700116 if err := json.Unmarshal(m, &input); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700117 return llm.ErrorfToolOut("failed to unmarshal user_patch input: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700118 }
119
120 // Validate the input
121 if !filepath.IsAbs(input.Path) {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700122 return llm.ErrorfToolOut("path %q is not absolute", input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700123 }
124 if len(input.Patches) == 0 {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700125 return llm.ErrorToolOut(fmt.Errorf("no patches provided"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700126 }
127 // TODO: check whether the file is autogenerated, and if so, require a "force" flag to modify it.
128
129 orig, err := os.ReadFile(input.Path)
130 // If the file doesn't exist, we can still apply patches
131 // that don't require finding existing text.
132 switch {
133 case errors.Is(err, os.ErrNotExist):
134 for _, patch := range input.Patches {
135 switch patch.Operation {
136 case "prepend_bof", "append_eof", "overwrite":
137 default:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700138 return llm.ErrorfToolOut("file %q does not exist", input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700139 }
140 }
141 case err != nil:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700142 return llm.ErrorfToolOut("failed to read file %q: %w", input.Path, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700143 }
144
145 likelyGoFile := strings.HasSuffix(input.Path, ".go")
146
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000147 autogenerated := likelyGoFile && IsAutogeneratedGoFile(orig)
Earl Lee2e463fb2025-04-17 11:22:22 -0700148 parsed := likelyGoFile && parseGo(orig) != nil
149
150 origStr := string(orig)
151 // Process the patches "simultaneously", minimizing them along the way.
152 // Claude generates patches that interact with each other.
153 buf := editbuf.NewBuffer(orig)
154
155 // TODO: is it better to apply the patches that apply cleanly and report on the failures?
156 // or instead have it be all-or-nothing?
157 // For now, it is all-or-nothing.
158 // TODO: when the model gets into a "cannot apply patch" cycle of doom, how do we get it unstuck?
159 // Also: how do we detect that it's in a cycle?
160 var patchErr error
161 for i, patch := range input.Patches {
162 switch patch.Operation {
163 case "prepend_bof":
164 buf.Insert(0, patch.NewText)
165 case "append_eof":
166 buf.Insert(len(orig), patch.NewText)
167 case "overwrite":
168 buf.Replace(0, len(orig), patch.NewText)
169 case "replace":
170 if patch.OldText == "" {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700171 return llm.ErrorfToolOut("patch %d: oldText cannot be empty for %s operation", i, patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700172 }
173
174 // Attempt to apply the patch.
175 spec, count := patchkit.Unique(origStr, patch.OldText, patch.NewText)
176 switch count {
177 case 0:
178 // no matches, maybe recoverable, continued below
179 case 1:
180 // exact match, apply
181 slog.DebugContext(ctx, "patch_applied", "method", "unique")
182 spec.ApplyToEditBuf(buf)
183 continue
184 case 2:
185 // multiple matches
186 patchErr = errors.Join(patchErr, fmt.Errorf("old text not unique:\n%s", patch.OldText))
187 default:
188 // TODO: return an error instead of using agentPatch
189 slog.ErrorContext(ctx, "unique returned unexpected count", "count", count)
190 patchErr = errors.Join(patchErr, fmt.Errorf("internal error"))
191 continue
192 }
193
194 // The following recovery mechanisms are heuristic.
195 // They aren't perfect, but they appear safe,
196 // and the cases they cover appear with some regularity.
197
198 // Try adjusting the whitespace prefix.
199 spec, ok := patchkit.UniqueDedent(origStr, patch.OldText, patch.NewText)
200 if ok {
201 slog.DebugContext(ctx, "patch_applied", "method", "unique_dedent")
202 spec.ApplyToEditBuf(buf)
203 continue
204 }
205
206 // Try ignoring leading/trailing whitespace in a semantically safe way.
207 spec, ok = patchkit.UniqueInValidGo(origStr, patch.OldText, patch.NewText)
208 if ok {
209 slog.DebugContext(ctx, "patch_applied", "method", "unique_in_valid_go")
210 spec.ApplyToEditBuf(buf)
211 continue
212 }
213
214 // Try ignoring semantically insignificant whitespace.
215 spec, ok = patchkit.UniqueGoTokens(origStr, patch.OldText, patch.NewText)
216 if ok {
217 slog.DebugContext(ctx, "patch_applied", "method", "unique_go_tokens")
218 spec.ApplyToEditBuf(buf)
219 continue
220 }
221
222 // Try trimming the first line of the patch, if we can do so safely.
223 spec, ok = patchkit.UniqueTrim(origStr, patch.OldText, patch.NewText)
224 if ok {
225 slog.DebugContext(ctx, "patch_applied", "method", "unique_trim")
226 spec.ApplyToEditBuf(buf)
227 continue
228 }
229
230 // No dice.
231 patchErr = errors.Join(patchErr, fmt.Errorf("old text not found:\n%s", patch.OldText))
232 continue
233 default:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700234 return llm.ErrorfToolOut("unrecognized operation %q", patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700235 }
236 }
237
238 if patchErr != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700239 return llm.ErrorToolOut(patchErr)
Earl Lee2e463fb2025-04-17 11:22:22 -0700240 }
241
242 patched, err := buf.Bytes()
243 if err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700244 return llm.ErrorToolOut(err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700245 }
246 if err := os.MkdirAll(filepath.Dir(input.Path), 0o700); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700247 return llm.ErrorfToolOut("failed to create directory %q: %w", filepath.Dir(input.Path), err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700248 }
249 if err := os.WriteFile(input.Path, patched, 0o600); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700250 return llm.ErrorfToolOut("failed to write patched contents to file %q: %w", input.Path, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700251 }
252
253 response := new(strings.Builder)
254 fmt.Fprintf(response, "- Applied all patches\n")
255
256 if parsed {
257 parseErr := parseGo(patched)
258 if parseErr != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700259 return llm.ErrorfToolOut("after applying all patches, the file no longer parses:\n%w", parseErr)
Earl Lee2e463fb2025-04-17 11:22:22 -0700260 }
261 }
262
263 if autogenerated {
264 fmt.Fprintf(response, "- WARNING: %q appears to be autogenerated. Patches were applied anyway.\n", input.Path)
265 }
266
267 // TODO: maybe report the patch result to the model, i.e. some/all of the new code after the patches and formatting.
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700268 return llm.ToolOut{LLMContent: llm.TextContent(response.String())}
Earl Lee2e463fb2025-04-17 11:22:22 -0700269}
270
271func parseGo(buf []byte) error {
272 fset := token.NewFileSet()
273 _, err := parser.ParseFile(fset, "", buf, parser.SkipObjectResolution)
274 return err
275}
276
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000277// IsAutogeneratedGoFile reports whether a Go file has markers indicating it was autogenerated.
278func IsAutogeneratedGoFile(buf []byte) bool {
Earl Lee2e463fb2025-04-17 11:22:22 -0700279 for _, sig := range autogeneratedSignals {
280 if bytes.Contains(buf, []byte(sig)) {
281 return true
282 }
283 }
284
285 // https://pkg.go.dev/cmd/go#hdr-Generate_Go_files_by_processing_source
286 // "This line must appear before the first non-comment, non-blank text in the file."
287 // Approximate that by looking for it at the top of the file, before the last of the imports.
288 // (Sometimes people put it after the package declaration, because of course they do.)
289 // At least in the imports region we know it's not part of their actual code;
290 // we don't want to ignore the generator (which also includes these strings!),
291 // just the generated code.
292 fset := token.NewFileSet()
293 f, err := parser.ParseFile(fset, "x.go", buf, parser.ImportsOnly|parser.ParseComments)
294 if err == nil {
295 for _, cg := range f.Comments {
296 t := strings.ToLower(cg.Text())
297 for _, sig := range autogeneratedHeaderSignals {
298 if strings.Contains(t, sig) {
299 return true
300 }
301 }
302 }
303 }
304
305 return false
306}
307
308// autogeneratedSignals are signals that a file is autogenerated, when present anywhere in the file.
309var autogeneratedSignals = [][]byte{
310 []byte("\nfunc bindataRead("), // pre-embed bindata packed file
311}
312
313// autogeneratedHeaderSignals are signals that a file is autogenerated, when present at the top of the file.
314var autogeneratedHeaderSignals = []string{
315 // canonical would be `(?m)^// Code generated .* DO NOT EDIT\.$`
316 // but people screw it up, a lot, so be more lenient
317 strings.ToLower("generate"),
318 strings.ToLower("DO NOT EDIT"),
319 strings.ToLower("export by"),
320}