blob: d0be33260341eb00fa7c0f70fae5945c33c70c11 [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.
29type PatchTool struct {
30 Callback PatchCallback // may be nil
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -070031 // Pwd is the working directory for resolving relative paths
32 Pwd string
Josh Bleecher Snyder04f16a52025-07-30 11:46:25 -070033}
34
35// Tool returns an llm.Tool based on p.
36func (p *PatchTool) Tool() *llm.Tool {
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000037 return &llm.Tool{
38 Name: PatchName,
39 Description: strings.TrimSpace(PatchDescription),
40 InputSchema: llm.MustSchema(PatchInputSchema),
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -070041 Run: func(ctx context.Context, m json.RawMessage) llm.ToolOut {
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000042 var input PatchInput
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -070043 output := p.patchRun(ctx, m, &input)
Josh Bleecher Snyder04f16a52025-07-30 11:46:25 -070044 if p.Callback != nil {
45 return p.Callback(input, output)
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000046 }
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -070047 return output
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000048 },
49 }
Earl Lee2e463fb2025-04-17 11:22:22 -070050}
51
52const (
53 PatchName = "patch"
54 PatchDescription = `
55File modification tool for precise text edits.
56
57Operations:
58- replace: Substitute text with new content
59- append_eof: Append new text at the end of the file
60- prepend_bof: Insert new text at the beginning of the file
61- overwrite: Replace the entire file with new content (automatically creates the file)
62
63Usage notes:
64- All inputs are interpreted literally (no automatic newline or whitespace handling)
65- For replace operations, oldText must appear EXACTLY ONCE in the file
66`
67
68 // If you modify this, update the termui template for prettier rendering.
69 PatchInputSchema = `
70{
71 "type": "object",
72 "required": ["path", "patches"],
73 "properties": {
74 "path": {
75 "type": "string",
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -070076 "description": "Path to the file to patch"
Earl Lee2e463fb2025-04-17 11:22:22 -070077 },
78 "patches": {
79 "type": "array",
80 "description": "List of patch requests to apply",
81 "items": {
82 "type": "object",
83 "required": ["operation", "newText"],
84 "properties": {
85 "operation": {
86 "type": "string",
87 "enum": ["replace", "append_eof", "prepend_bof", "overwrite"],
88 "description": "Type of operation to perform"
89 },
90 "oldText": {
91 "type": "string",
92 "description": "Text to locate for the operation (must be unique in file, required for replace)"
93 },
94 "newText": {
95 "type": "string",
96 "description": "The new text to use (empty for deletions)"
97 }
98 }
99 }
100 }
101 }
102}
103`
104)
105
106// TODO: maybe rename PatchRequest to PatchOperation or PatchSpec or PatchPart or just Patch?
107
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000108// PatchInput represents the input structure for patch operations.
109type PatchInput struct {
Earl Lee2e463fb2025-04-17 11:22:22 -0700110 Path string `json:"path"`
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000111 Patches []PatchRequest `json:"patches"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700112}
113
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700114// PatchInputOne is a simplified version of PatchInput for single patch operations.
115type PatchInputOne struct {
116 Path string `json:"path"`
117 Patches PatchRequest `json:"patches"`
118}
119
120type PatchInputOneString struct {
121 Path string `json:"path"`
122 Patches string `json:"patches"` // contains Patches as a JSON string 🤦
123}
124
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000125// PatchRequest represents a single patch operation.
126type PatchRequest struct {
Earl Lee2e463fb2025-04-17 11:22:22 -0700127 Operation string `json:"operation"`
128 OldText string `json:"oldText,omitempty"`
129 NewText string `json:"newText,omitempty"`
130}
131
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700132// Run implements the patch tool logic.
133func (p *PatchTool) Run(ctx context.Context, m json.RawMessage) llm.ToolOut {
134 input, err := p.patchParse(m)
135 var output llm.ToolOut
136 if err != nil {
137 output = llm.ErrorToolOut(err)
138 } else {
139 output = p.patchRun(ctx, m, &input)
140 }
141 if p.Callback != nil {
142 return p.Callback(input, output)
143 }
144 return output
145}
146
147// patchParse parses the input message into a PatchInput structure.
148// It accepts a few different formats, because empirically,
149// LLMs sometimes generate slightly different JSON structures,
150// and we may as well accept such near misses.
151func (p *PatchTool) patchParse(m json.RawMessage) (PatchInput, error) {
152 var input PatchInput
153 originalErr := json.Unmarshal(m, &input)
154 if originalErr == nil {
155 return input, nil
156 }
157 var inputOne PatchInputOne
158 if err := json.Unmarshal(m, &inputOne); err == nil {
159 return PatchInput{Path: inputOne.Path, Patches: []PatchRequest{inputOne.Patches}}, nil
160 }
161 var inputOneString PatchInputOneString
162 if err := json.Unmarshal(m, &inputOneString); err == nil {
163 var onePatch PatchRequest
164 if err := json.Unmarshal([]byte(inputOneString.Patches), &onePatch); err == nil {
165 return PatchInput{Path: inputOneString.Path, Patches: []PatchRequest{onePatch}}, nil
166 }
167 var patches []PatchRequest
168 if err := json.Unmarshal([]byte(inputOneString.Patches), &patches); err == nil {
169 return PatchInput{Path: inputOneString.Path, Patches: patches}, nil
170 }
171 }
172 return PatchInput{}, fmt.Errorf("failed to unmarshal patch input: %w", originalErr)
173}
174
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000175// patchRun implements the guts of the patch tool.
176// It populates input from m.
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700177func (p *PatchTool) patchRun(ctx context.Context, m json.RawMessage, input *PatchInput) llm.ToolOut {
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700178 path := input.Path
Earl Lee2e463fb2025-04-17 11:22:22 -0700179 if !filepath.IsAbs(input.Path) {
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700180 if p.Pwd == "" {
181 return llm.ErrorfToolOut("path %q is not absolute and no working directory is set", input.Path)
182 }
183 path = filepath.Join(p.Pwd, input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700184 }
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700185 input.Path = path
Earl Lee2e463fb2025-04-17 11:22:22 -0700186 if len(input.Patches) == 0 {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700187 return llm.ErrorToolOut(fmt.Errorf("no patches provided"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700188 }
189 // TODO: check whether the file is autogenerated, and if so, require a "force" flag to modify it.
190
191 orig, err := os.ReadFile(input.Path)
192 // If the file doesn't exist, we can still apply patches
193 // that don't require finding existing text.
194 switch {
195 case errors.Is(err, os.ErrNotExist):
196 for _, patch := range input.Patches {
197 switch patch.Operation {
198 case "prepend_bof", "append_eof", "overwrite":
199 default:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700200 return llm.ErrorfToolOut("file %q does not exist", input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700201 }
202 }
203 case err != nil:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700204 return llm.ErrorfToolOut("failed to read file %q: %w", input.Path, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700205 }
206
207 likelyGoFile := strings.HasSuffix(input.Path, ".go")
208
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000209 autogenerated := likelyGoFile && IsAutogeneratedGoFile(orig)
Earl Lee2e463fb2025-04-17 11:22:22 -0700210
211 origStr := string(orig)
212 // Process the patches "simultaneously", minimizing them along the way.
213 // Claude generates patches that interact with each other.
214 buf := editbuf.NewBuffer(orig)
215
216 // TODO: is it better to apply the patches that apply cleanly and report on the failures?
217 // or instead have it be all-or-nothing?
218 // For now, it is all-or-nothing.
219 // TODO: when the model gets into a "cannot apply patch" cycle of doom, how do we get it unstuck?
220 // Also: how do we detect that it's in a cycle?
221 var patchErr error
222 for i, patch := range input.Patches {
223 switch patch.Operation {
224 case "prepend_bof":
225 buf.Insert(0, patch.NewText)
226 case "append_eof":
227 buf.Insert(len(orig), patch.NewText)
228 case "overwrite":
229 buf.Replace(0, len(orig), patch.NewText)
230 case "replace":
231 if patch.OldText == "" {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700232 return llm.ErrorfToolOut("patch %d: oldText cannot be empty for %s operation", i, patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700233 }
234
235 // Attempt to apply the patch.
236 spec, count := patchkit.Unique(origStr, patch.OldText, patch.NewText)
237 switch count {
238 case 0:
239 // no matches, maybe recoverable, continued below
240 case 1:
241 // exact match, apply
242 slog.DebugContext(ctx, "patch_applied", "method", "unique")
243 spec.ApplyToEditBuf(buf)
244 continue
245 case 2:
246 // multiple matches
247 patchErr = errors.Join(patchErr, fmt.Errorf("old text not unique:\n%s", patch.OldText))
248 default:
249 // TODO: return an error instead of using agentPatch
250 slog.ErrorContext(ctx, "unique returned unexpected count", "count", count)
251 patchErr = errors.Join(patchErr, fmt.Errorf("internal error"))
252 continue
253 }
254
255 // The following recovery mechanisms are heuristic.
256 // They aren't perfect, but they appear safe,
257 // and the cases they cover appear with some regularity.
258
259 // Try adjusting the whitespace prefix.
260 spec, ok := patchkit.UniqueDedent(origStr, patch.OldText, patch.NewText)
261 if ok {
262 slog.DebugContext(ctx, "patch_applied", "method", "unique_dedent")
263 spec.ApplyToEditBuf(buf)
264 continue
265 }
266
267 // Try ignoring leading/trailing whitespace in a semantically safe way.
268 spec, ok = patchkit.UniqueInValidGo(origStr, patch.OldText, patch.NewText)
269 if ok {
270 slog.DebugContext(ctx, "patch_applied", "method", "unique_in_valid_go")
271 spec.ApplyToEditBuf(buf)
272 continue
273 }
274
275 // Try ignoring semantically insignificant whitespace.
276 spec, ok = patchkit.UniqueGoTokens(origStr, patch.OldText, patch.NewText)
277 if ok {
278 slog.DebugContext(ctx, "patch_applied", "method", "unique_go_tokens")
279 spec.ApplyToEditBuf(buf)
280 continue
281 }
282
283 // Try trimming the first line of the patch, if we can do so safely.
284 spec, ok = patchkit.UniqueTrim(origStr, patch.OldText, patch.NewText)
285 if ok {
286 slog.DebugContext(ctx, "patch_applied", "method", "unique_trim")
287 spec.ApplyToEditBuf(buf)
288 continue
289 }
290
291 // No dice.
292 patchErr = errors.Join(patchErr, fmt.Errorf("old text not found:\n%s", patch.OldText))
293 continue
294 default:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700295 return llm.ErrorfToolOut("unrecognized operation %q", patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700296 }
297 }
298
299 if patchErr != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700300 return llm.ErrorToolOut(patchErr)
Earl Lee2e463fb2025-04-17 11:22:22 -0700301 }
302
303 patched, err := buf.Bytes()
304 if err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700305 return llm.ErrorToolOut(err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700306 }
307 if err := os.MkdirAll(filepath.Dir(input.Path), 0o700); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700308 return llm.ErrorfToolOut("failed to create directory %q: %w", filepath.Dir(input.Path), err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700309 }
310 if err := os.WriteFile(input.Path, patched, 0o600); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700311 return llm.ErrorfToolOut("failed to write patched contents to file %q: %w", input.Path, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700312 }
313
314 response := new(strings.Builder)
315 fmt.Fprintf(response, "- Applied all patches\n")
316
Earl Lee2e463fb2025-04-17 11:22:22 -0700317 if autogenerated {
318 fmt.Fprintf(response, "- WARNING: %q appears to be autogenerated. Patches were applied anyway.\n", input.Path)
319 }
320
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -0700321 diff := generateUnifiedDiff(input.Path, string(orig), string(patched))
322
Earl Lee2e463fb2025-04-17 11:22:22 -0700323 // 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 -0700324 return llm.ToolOut{
325 LLMContent: llm.TextContent(response.String()),
326 Display: diff,
327 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700328}
329
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000330// IsAutogeneratedGoFile reports whether a Go file has markers indicating it was autogenerated.
331func IsAutogeneratedGoFile(buf []byte) bool {
Earl Lee2e463fb2025-04-17 11:22:22 -0700332 for _, sig := range autogeneratedSignals {
333 if bytes.Contains(buf, []byte(sig)) {
334 return true
335 }
336 }
337
338 // https://pkg.go.dev/cmd/go#hdr-Generate_Go_files_by_processing_source
339 // "This line must appear before the first non-comment, non-blank text in the file."
340 // Approximate that by looking for it at the top of the file, before the last of the imports.
341 // (Sometimes people put it after the package declaration, because of course they do.)
342 // At least in the imports region we know it's not part of their actual code;
343 // we don't want to ignore the generator (which also includes these strings!),
344 // just the generated code.
345 fset := token.NewFileSet()
346 f, err := parser.ParseFile(fset, "x.go", buf, parser.ImportsOnly|parser.ParseComments)
347 if err == nil {
348 for _, cg := range f.Comments {
349 t := strings.ToLower(cg.Text())
350 for _, sig := range autogeneratedHeaderSignals {
351 if strings.Contains(t, sig) {
352 return true
353 }
354 }
355 }
356 }
357
358 return false
359}
360
361// autogeneratedSignals are signals that a file is autogenerated, when present anywhere in the file.
362var autogeneratedSignals = [][]byte{
363 []byte("\nfunc bindataRead("), // pre-embed bindata packed file
364}
365
366// autogeneratedHeaderSignals are signals that a file is autogenerated, when present at the top of the file.
367var autogeneratedHeaderSignals = []string{
368 // canonical would be `(?m)^// Code generated .* DO NOT EDIT\.$`
369 // but people screw it up, a lot, so be more lenient
370 strings.ToLower("generate"),
371 strings.ToLower("DO NOT EDIT"),
372 strings.ToLower("export by"),
373}
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -0700374
375func generateUnifiedDiff(filePath, original, patched string) string {
376 buf := new(strings.Builder)
377 err := diff.Text(filePath, filePath, original, patched, buf)
378 if err != nil {
379 return fmt.Sprintf("(diff generation failed: %v)\n", err)
380 }
381 return buf.String()
382}