blob: fb0431993c56078d05e284f70ea3a91a13dbd93b [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
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -070016 "github.com/pkg/diff"
Earl Lee2e463fb2025-04-17 11:22:22 -070017 "sketch.dev/claudetool/editbuf"
18 "sketch.dev/claudetool/patchkit"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070019 "sketch.dev/llm"
Earl Lee2e463fb2025-04-17 11:22:22 -070020)
21
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000022// PatchCallback defines the signature for patch tool callbacks.
23// It runs after the patch tool has executed.
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -070024// It receives the patch input and the tool output,
25// and returns a new, possibly altered tool output.
26type PatchCallback func(input PatchInput, output llm.ToolOut) llm.ToolOut
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000027
Josh Bleecher Snyder04f16a52025-07-30 11:46:25 -070028// PatchTool specifies an llm.Tool for patching files.
Josh Bleecher Snyder534783d2025-07-29 08:17:37 -070029// PatchTools are not concurrency-safe.
Josh Bleecher Snyder04f16a52025-07-30 11:46:25 -070030type PatchTool struct {
31 Callback PatchCallback // may be nil
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -070032 // Pwd is the working directory for resolving relative paths
33 Pwd string
Josh Bleecher Snyder04f16a52025-07-30 11:46:25 -070034}
35
36// Tool returns an llm.Tool based on p.
37func (p *PatchTool) Tool() *llm.Tool {
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000038 return &llm.Tool{
39 Name: PatchName,
40 Description: strings.TrimSpace(PatchDescription),
41 InputSchema: llm.MustSchema(PatchInputSchema),
Josh Bleecher Snyder534783d2025-07-29 08:17:37 -070042 Run: p.Run,
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000043 }
Earl Lee2e463fb2025-04-17 11:22:22 -070044}
45
46const (
47 PatchName = "patch"
48 PatchDescription = `
49File modification tool for precise text edits.
50
51Operations:
Josh Bleecher Snyder534783d2025-07-29 08:17:37 -070052- replace: Substitute unique text with new content
Earl Lee2e463fb2025-04-17 11:22:22 -070053- append_eof: Append new text at the end of the file
54- prepend_bof: Insert new text at the beginning of the file
55- overwrite: Replace the entire file with new content (automatically creates the file)
56
57Usage notes:
58- All inputs are interpreted literally (no automatic newline or whitespace handling)
59- For replace operations, oldText must appear EXACTLY ONCE in the file
60`
61
62 // If you modify this, update the termui template for prettier rendering.
63 PatchInputSchema = `
64{
65 "type": "object",
66 "required": ["path", "patches"],
67 "properties": {
68 "path": {
69 "type": "string",
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -070070 "description": "Path to the file to patch"
Earl Lee2e463fb2025-04-17 11:22:22 -070071 },
72 "patches": {
73 "type": "array",
74 "description": "List of patch requests to apply",
75 "items": {
76 "type": "object",
77 "required": ["operation", "newText"],
78 "properties": {
79 "operation": {
80 "type": "string",
81 "enum": ["replace", "append_eof", "prepend_bof", "overwrite"],
82 "description": "Type of operation to perform"
83 },
84 "oldText": {
85 "type": "string",
86 "description": "Text to locate for the operation (must be unique in file, required for replace)"
87 },
88 "newText": {
89 "type": "string",
90 "description": "The new text to use (empty for deletions)"
91 }
92 }
93 }
94 }
95 }
96}
97`
98)
99
100// TODO: maybe rename PatchRequest to PatchOperation or PatchSpec or PatchPart or just Patch?
101
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000102// PatchInput represents the input structure for patch operations.
103type PatchInput struct {
Earl Lee2e463fb2025-04-17 11:22:22 -0700104 Path string `json:"path"`
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000105 Patches []PatchRequest `json:"patches"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700106}
107
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700108// PatchInputOne is a simplified version of PatchInput for single patch operations.
109type PatchInputOne struct {
110 Path string `json:"path"`
111 Patches PatchRequest `json:"patches"`
112}
113
114type PatchInputOneString struct {
115 Path string `json:"path"`
116 Patches string `json:"patches"` // contains Patches as a JSON string 🤦
117}
118
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000119// PatchRequest represents a single patch operation.
120type PatchRequest struct {
Earl Lee2e463fb2025-04-17 11:22:22 -0700121 Operation string `json:"operation"`
122 OldText string `json:"oldText,omitempty"`
123 NewText string `json:"newText,omitempty"`
124}
125
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700126// Run implements the patch tool logic.
127func (p *PatchTool) Run(ctx context.Context, m json.RawMessage) llm.ToolOut {
128 input, err := p.patchParse(m)
129 var output llm.ToolOut
130 if err != nil {
131 output = llm.ErrorToolOut(err)
132 } else {
133 output = p.patchRun(ctx, m, &input)
134 }
135 if p.Callback != nil {
136 return p.Callback(input, output)
137 }
138 return output
139}
140
141// patchParse parses the input message into a PatchInput structure.
142// It accepts a few different formats, because empirically,
143// LLMs sometimes generate slightly different JSON structures,
144// and we may as well accept such near misses.
145func (p *PatchTool) patchParse(m json.RawMessage) (PatchInput, error) {
146 var input PatchInput
147 originalErr := json.Unmarshal(m, &input)
148 if originalErr == nil {
149 return input, nil
150 }
151 var inputOne PatchInputOne
152 if err := json.Unmarshal(m, &inputOne); err == nil {
153 return PatchInput{Path: inputOne.Path, Patches: []PatchRequest{inputOne.Patches}}, nil
154 }
155 var inputOneString PatchInputOneString
156 if err := json.Unmarshal(m, &inputOneString); err == nil {
157 var onePatch PatchRequest
158 if err := json.Unmarshal([]byte(inputOneString.Patches), &onePatch); err == nil {
159 return PatchInput{Path: inputOneString.Path, Patches: []PatchRequest{onePatch}}, nil
160 }
161 var patches []PatchRequest
162 if err := json.Unmarshal([]byte(inputOneString.Patches), &patches); err == nil {
163 return PatchInput{Path: inputOneString.Path, Patches: patches}, nil
164 }
165 }
166 return PatchInput{}, fmt.Errorf("failed to unmarshal patch input: %w", originalErr)
167}
168
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000169// patchRun implements the guts of the patch tool.
170// It populates input from m.
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700171func (p *PatchTool) patchRun(ctx context.Context, m json.RawMessage, input *PatchInput) llm.ToolOut {
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700172 path := input.Path
Earl Lee2e463fb2025-04-17 11:22:22 -0700173 if !filepath.IsAbs(input.Path) {
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700174 if p.Pwd == "" {
175 return llm.ErrorfToolOut("path %q is not absolute and no working directory is set", input.Path)
176 }
177 path = filepath.Join(p.Pwd, input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700178 }
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700179 input.Path = path
Earl Lee2e463fb2025-04-17 11:22:22 -0700180 if len(input.Patches) == 0 {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700181 return llm.ErrorToolOut(fmt.Errorf("no patches provided"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700182 }
183 // TODO: check whether the file is autogenerated, and if so, require a "force" flag to modify it.
184
185 orig, err := os.ReadFile(input.Path)
186 // If the file doesn't exist, we can still apply patches
187 // that don't require finding existing text.
188 switch {
189 case errors.Is(err, os.ErrNotExist):
190 for _, patch := range input.Patches {
191 switch patch.Operation {
192 case "prepend_bof", "append_eof", "overwrite":
193 default:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700194 return llm.ErrorfToolOut("file %q does not exist", input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700195 }
196 }
197 case err != nil:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700198 return llm.ErrorfToolOut("failed to read file %q: %w", input.Path, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700199 }
200
201 likelyGoFile := strings.HasSuffix(input.Path, ".go")
202
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000203 autogenerated := likelyGoFile && IsAutogeneratedGoFile(orig)
Earl Lee2e463fb2025-04-17 11:22:22 -0700204
205 origStr := string(orig)
206 // Process the patches "simultaneously", minimizing them along the way.
207 // Claude generates patches that interact with each other.
208 buf := editbuf.NewBuffer(orig)
209
210 // TODO: is it better to apply the patches that apply cleanly and report on the failures?
211 // or instead have it be all-or-nothing?
212 // For now, it is all-or-nothing.
213 // TODO: when the model gets into a "cannot apply patch" cycle of doom, how do we get it unstuck?
214 // Also: how do we detect that it's in a cycle?
215 var patchErr error
216 for i, patch := range input.Patches {
217 switch patch.Operation {
218 case "prepend_bof":
219 buf.Insert(0, patch.NewText)
220 case "append_eof":
221 buf.Insert(len(orig), patch.NewText)
222 case "overwrite":
223 buf.Replace(0, len(orig), patch.NewText)
224 case "replace":
225 if patch.OldText == "" {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700226 return llm.ErrorfToolOut("patch %d: oldText cannot be empty for %s operation", i, patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700227 }
228
229 // Attempt to apply the patch.
230 spec, count := patchkit.Unique(origStr, patch.OldText, patch.NewText)
231 switch count {
232 case 0:
233 // no matches, maybe recoverable, continued below
234 case 1:
235 // exact match, apply
236 slog.DebugContext(ctx, "patch_applied", "method", "unique")
237 spec.ApplyToEditBuf(buf)
238 continue
239 case 2:
240 // multiple matches
241 patchErr = errors.Join(patchErr, fmt.Errorf("old text not unique:\n%s", patch.OldText))
242 default:
243 // TODO: return an error instead of using agentPatch
244 slog.ErrorContext(ctx, "unique returned unexpected count", "count", count)
245 patchErr = errors.Join(patchErr, fmt.Errorf("internal error"))
246 continue
247 }
248
249 // The following recovery mechanisms are heuristic.
250 // They aren't perfect, but they appear safe,
251 // and the cases they cover appear with some regularity.
252
253 // Try adjusting the whitespace prefix.
254 spec, ok := patchkit.UniqueDedent(origStr, patch.OldText, patch.NewText)
255 if ok {
256 slog.DebugContext(ctx, "patch_applied", "method", "unique_dedent")
257 spec.ApplyToEditBuf(buf)
258 continue
259 }
260
261 // Try ignoring leading/trailing whitespace in a semantically safe way.
262 spec, ok = patchkit.UniqueInValidGo(origStr, patch.OldText, patch.NewText)
263 if ok {
264 slog.DebugContext(ctx, "patch_applied", "method", "unique_in_valid_go")
265 spec.ApplyToEditBuf(buf)
266 continue
267 }
268
269 // Try ignoring semantically insignificant whitespace.
270 spec, ok = patchkit.UniqueGoTokens(origStr, patch.OldText, patch.NewText)
271 if ok {
272 slog.DebugContext(ctx, "patch_applied", "method", "unique_go_tokens")
273 spec.ApplyToEditBuf(buf)
274 continue
275 }
276
277 // Try trimming the first line of the patch, if we can do so safely.
278 spec, ok = patchkit.UniqueTrim(origStr, patch.OldText, patch.NewText)
279 if ok {
280 slog.DebugContext(ctx, "patch_applied", "method", "unique_trim")
281 spec.ApplyToEditBuf(buf)
282 continue
283 }
284
285 // No dice.
286 patchErr = errors.Join(patchErr, fmt.Errorf("old text not found:\n%s", patch.OldText))
287 continue
288 default:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700289 return llm.ErrorfToolOut("unrecognized operation %q", patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700290 }
291 }
292
293 if patchErr != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700294 return llm.ErrorToolOut(patchErr)
Earl Lee2e463fb2025-04-17 11:22:22 -0700295 }
296
297 patched, err := buf.Bytes()
298 if err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700299 return llm.ErrorToolOut(err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700300 }
301 if err := os.MkdirAll(filepath.Dir(input.Path), 0o700); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700302 return llm.ErrorfToolOut("failed to create directory %q: %w", filepath.Dir(input.Path), err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700303 }
304 if err := os.WriteFile(input.Path, patched, 0o600); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700305 return llm.ErrorfToolOut("failed to write patched contents to file %q: %w", input.Path, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700306 }
307
308 response := new(strings.Builder)
309 fmt.Fprintf(response, "- Applied all patches\n")
310
Earl Lee2e463fb2025-04-17 11:22:22 -0700311 if autogenerated {
312 fmt.Fprintf(response, "- WARNING: %q appears to be autogenerated. Patches were applied anyway.\n", input.Path)
313 }
314
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -0700315 diff := generateUnifiedDiff(input.Path, string(orig), string(patched))
316
Earl Lee2e463fb2025-04-17 11:22:22 -0700317 // TODO: maybe report the patch result to the model, i.e. some/all of the new code after the patches and formatting.
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -0700318 return llm.ToolOut{
319 LLMContent: llm.TextContent(response.String()),
320 Display: diff,
321 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700322}
323
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000324// IsAutogeneratedGoFile reports whether a Go file has markers indicating it was autogenerated.
325func IsAutogeneratedGoFile(buf []byte) bool {
Earl Lee2e463fb2025-04-17 11:22:22 -0700326 for _, sig := range autogeneratedSignals {
327 if bytes.Contains(buf, []byte(sig)) {
328 return true
329 }
330 }
331
332 // https://pkg.go.dev/cmd/go#hdr-Generate_Go_files_by_processing_source
333 // "This line must appear before the first non-comment, non-blank text in the file."
334 // Approximate that by looking for it at the top of the file, before the last of the imports.
335 // (Sometimes people put it after the package declaration, because of course they do.)
336 // At least in the imports region we know it's not part of their actual code;
337 // we don't want to ignore the generator (which also includes these strings!),
338 // just the generated code.
339 fset := token.NewFileSet()
340 f, err := parser.ParseFile(fset, "x.go", buf, parser.ImportsOnly|parser.ParseComments)
341 if err == nil {
342 for _, cg := range f.Comments {
343 t := strings.ToLower(cg.Text())
344 for _, sig := range autogeneratedHeaderSignals {
345 if strings.Contains(t, sig) {
346 return true
347 }
348 }
349 }
350 }
351
352 return false
353}
354
355// autogeneratedSignals are signals that a file is autogenerated, when present anywhere in the file.
356var autogeneratedSignals = [][]byte{
357 []byte("\nfunc bindataRead("), // pre-embed bindata packed file
358}
359
360// autogeneratedHeaderSignals are signals that a file is autogenerated, when present at the top of the file.
361var autogeneratedHeaderSignals = []string{
362 // canonical would be `(?m)^// Code generated .* DO NOT EDIT\.$`
363 // but people screw it up, a lot, so be more lenient
364 strings.ToLower("generate"),
365 strings.ToLower("DO NOT EDIT"),
366 strings.ToLower("export by"),
367}
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -0700368
369func generateUnifiedDiff(filePath, original, patched string) string {
370 buf := new(strings.Builder)
371 err := diff.Text(filePath, filePath, original, patched, buf)
372 if err != nil {
373 return fmt.Sprintf("(diff generation failed: %v)\n", err)
374 }
375 return buf.String()
376}