blob: b2b5db666df9720ca6bb4ee3f96de9fc063f618e [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 Snyder238c18f2025-06-30 22:26:54 +0000114// PatchRequest represents a single patch operation.
115type PatchRequest struct {
Earl Lee2e463fb2025-04-17 11:22:22 -0700116 Operation string `json:"operation"`
117 OldText string `json:"oldText,omitempty"`
118 NewText string `json:"newText,omitempty"`
119}
120
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000121// patchRun implements the guts of the patch tool.
122// It populates input from m.
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700123func (p *PatchTool) patchRun(ctx context.Context, m json.RawMessage, input *PatchInput) llm.ToolOut {
Earl Lee2e463fb2025-04-17 11:22:22 -0700124 if err := json.Unmarshal(m, &input); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700125 return llm.ErrorfToolOut("failed to unmarshal user_patch input: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700126 }
127
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700128 path := input.Path
Earl Lee2e463fb2025-04-17 11:22:22 -0700129 if !filepath.IsAbs(input.Path) {
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700130 if p.Pwd == "" {
131 return llm.ErrorfToolOut("path %q is not absolute and no working directory is set", input.Path)
132 }
133 path = filepath.Join(p.Pwd, input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700134 }
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700135 input.Path = path
Earl Lee2e463fb2025-04-17 11:22:22 -0700136 if len(input.Patches) == 0 {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700137 return llm.ErrorToolOut(fmt.Errorf("no patches provided"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700138 }
139 // TODO: check whether the file is autogenerated, and if so, require a "force" flag to modify it.
140
141 orig, err := os.ReadFile(input.Path)
142 // If the file doesn't exist, we can still apply patches
143 // that don't require finding existing text.
144 switch {
145 case errors.Is(err, os.ErrNotExist):
146 for _, patch := range input.Patches {
147 switch patch.Operation {
148 case "prepend_bof", "append_eof", "overwrite":
149 default:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700150 return llm.ErrorfToolOut("file %q does not exist", input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700151 }
152 }
153 case err != nil:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700154 return llm.ErrorfToolOut("failed to read file %q: %w", input.Path, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700155 }
156
157 likelyGoFile := strings.HasSuffix(input.Path, ".go")
158
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000159 autogenerated := likelyGoFile && IsAutogeneratedGoFile(orig)
Earl Lee2e463fb2025-04-17 11:22:22 -0700160 parsed := likelyGoFile && parseGo(orig) != nil
161
162 origStr := string(orig)
163 // Process the patches "simultaneously", minimizing them along the way.
164 // Claude generates patches that interact with each other.
165 buf := editbuf.NewBuffer(orig)
166
167 // TODO: is it better to apply the patches that apply cleanly and report on the failures?
168 // or instead have it be all-or-nothing?
169 // For now, it is all-or-nothing.
170 // TODO: when the model gets into a "cannot apply patch" cycle of doom, how do we get it unstuck?
171 // Also: how do we detect that it's in a cycle?
172 var patchErr error
173 for i, patch := range input.Patches {
174 switch patch.Operation {
175 case "prepend_bof":
176 buf.Insert(0, patch.NewText)
177 case "append_eof":
178 buf.Insert(len(orig), patch.NewText)
179 case "overwrite":
180 buf.Replace(0, len(orig), patch.NewText)
181 case "replace":
182 if patch.OldText == "" {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700183 return llm.ErrorfToolOut("patch %d: oldText cannot be empty for %s operation", i, patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700184 }
185
186 // Attempt to apply the patch.
187 spec, count := patchkit.Unique(origStr, patch.OldText, patch.NewText)
188 switch count {
189 case 0:
190 // no matches, maybe recoverable, continued below
191 case 1:
192 // exact match, apply
193 slog.DebugContext(ctx, "patch_applied", "method", "unique")
194 spec.ApplyToEditBuf(buf)
195 continue
196 case 2:
197 // multiple matches
198 patchErr = errors.Join(patchErr, fmt.Errorf("old text not unique:\n%s", patch.OldText))
199 default:
200 // TODO: return an error instead of using agentPatch
201 slog.ErrorContext(ctx, "unique returned unexpected count", "count", count)
202 patchErr = errors.Join(patchErr, fmt.Errorf("internal error"))
203 continue
204 }
205
206 // The following recovery mechanisms are heuristic.
207 // They aren't perfect, but they appear safe,
208 // and the cases they cover appear with some regularity.
209
210 // Try adjusting the whitespace prefix.
211 spec, ok := patchkit.UniqueDedent(origStr, patch.OldText, patch.NewText)
212 if ok {
213 slog.DebugContext(ctx, "patch_applied", "method", "unique_dedent")
214 spec.ApplyToEditBuf(buf)
215 continue
216 }
217
218 // Try ignoring leading/trailing whitespace in a semantically safe way.
219 spec, ok = patchkit.UniqueInValidGo(origStr, patch.OldText, patch.NewText)
220 if ok {
221 slog.DebugContext(ctx, "patch_applied", "method", "unique_in_valid_go")
222 spec.ApplyToEditBuf(buf)
223 continue
224 }
225
226 // Try ignoring semantically insignificant whitespace.
227 spec, ok = patchkit.UniqueGoTokens(origStr, patch.OldText, patch.NewText)
228 if ok {
229 slog.DebugContext(ctx, "patch_applied", "method", "unique_go_tokens")
230 spec.ApplyToEditBuf(buf)
231 continue
232 }
233
234 // Try trimming the first line of the patch, if we can do so safely.
235 spec, ok = patchkit.UniqueTrim(origStr, patch.OldText, patch.NewText)
236 if ok {
237 slog.DebugContext(ctx, "patch_applied", "method", "unique_trim")
238 spec.ApplyToEditBuf(buf)
239 continue
240 }
241
242 // No dice.
243 patchErr = errors.Join(patchErr, fmt.Errorf("old text not found:\n%s", patch.OldText))
244 continue
245 default:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700246 return llm.ErrorfToolOut("unrecognized operation %q", patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700247 }
248 }
249
250 if patchErr != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700251 return llm.ErrorToolOut(patchErr)
Earl Lee2e463fb2025-04-17 11:22:22 -0700252 }
253
254 patched, err := buf.Bytes()
255 if err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700256 return llm.ErrorToolOut(err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700257 }
258 if err := os.MkdirAll(filepath.Dir(input.Path), 0o700); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700259 return llm.ErrorfToolOut("failed to create directory %q: %w", filepath.Dir(input.Path), err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700260 }
261 if err := os.WriteFile(input.Path, patched, 0o600); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700262 return llm.ErrorfToolOut("failed to write patched contents to file %q: %w", input.Path, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700263 }
264
265 response := new(strings.Builder)
266 fmt.Fprintf(response, "- Applied all patches\n")
267
268 if parsed {
269 parseErr := parseGo(patched)
270 if parseErr != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700271 return llm.ErrorfToolOut("after applying all patches, the file no longer parses:\n%w", parseErr)
Earl Lee2e463fb2025-04-17 11:22:22 -0700272 }
273 }
274
275 if autogenerated {
276 fmt.Fprintf(response, "- WARNING: %q appears to be autogenerated. Patches were applied anyway.\n", input.Path)
277 }
278
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -0700279 diff := generateUnifiedDiff(input.Path, string(orig), string(patched))
280
Earl Lee2e463fb2025-04-17 11:22:22 -0700281 // 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 -0700282 return llm.ToolOut{
283 LLMContent: llm.TextContent(response.String()),
284 Display: diff,
285 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700286}
287
288func parseGo(buf []byte) error {
289 fset := token.NewFileSet()
290 _, err := parser.ParseFile(fset, "", buf, parser.SkipObjectResolution)
291 return err
292}
293
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000294// IsAutogeneratedGoFile reports whether a Go file has markers indicating it was autogenerated.
295func IsAutogeneratedGoFile(buf []byte) bool {
Earl Lee2e463fb2025-04-17 11:22:22 -0700296 for _, sig := range autogeneratedSignals {
297 if bytes.Contains(buf, []byte(sig)) {
298 return true
299 }
300 }
301
302 // https://pkg.go.dev/cmd/go#hdr-Generate_Go_files_by_processing_source
303 // "This line must appear before the first non-comment, non-blank text in the file."
304 // Approximate that by looking for it at the top of the file, before the last of the imports.
305 // (Sometimes people put it after the package declaration, because of course they do.)
306 // At least in the imports region we know it's not part of their actual code;
307 // we don't want to ignore the generator (which also includes these strings!),
308 // just the generated code.
309 fset := token.NewFileSet()
310 f, err := parser.ParseFile(fset, "x.go", buf, parser.ImportsOnly|parser.ParseComments)
311 if err == nil {
312 for _, cg := range f.Comments {
313 t := strings.ToLower(cg.Text())
314 for _, sig := range autogeneratedHeaderSignals {
315 if strings.Contains(t, sig) {
316 return true
317 }
318 }
319 }
320 }
321
322 return false
323}
324
325// autogeneratedSignals are signals that a file is autogenerated, when present anywhere in the file.
326var autogeneratedSignals = [][]byte{
327 []byte("\nfunc bindataRead("), // pre-embed bindata packed file
328}
329
330// autogeneratedHeaderSignals are signals that a file is autogenerated, when present at the top of the file.
331var autogeneratedHeaderSignals = []string{
332 // canonical would be `(?m)^// Code generated .* DO NOT EDIT\.$`
333 // but people screw it up, a lot, so be more lenient
334 strings.ToLower("generate"),
335 strings.ToLower("DO NOT EDIT"),
336 strings.ToLower("export by"),
337}
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -0700338
339func generateUnifiedDiff(filePath, original, patched string) string {
340 buf := new(strings.Builder)
341 err := diff.Text(filePath, filePath, original, patched, buf)
342 if err != nil {
343 return fmt.Sprintf("(diff generation failed: %v)\n", err)
344 }
345 return buf.String()
346}