blob: 04ea942526964997daecd033b1dcc0d19c8cad40 [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
28// Patch creates a patch tool. The callback may be nil.
29func Patch(callback PatchCallback) *llm.Tool {
30 return &llm.Tool{
31 Name: PatchName,
32 Description: strings.TrimSpace(PatchDescription),
33 InputSchema: llm.MustSchema(PatchInputSchema),
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -070034 Run: func(ctx context.Context, m json.RawMessage) llm.ToolOut {
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000035 var input PatchInput
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -070036 output := patchRun(ctx, m, &input)
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000037 if callback != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -070038 return callback(input, output)
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000039 }
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -070040 return output
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000041 },
42 }
Earl Lee2e463fb2025-04-17 11:22:22 -070043}
44
45const (
46 PatchName = "patch"
47 PatchDescription = `
48File modification tool for precise text edits.
49
50Operations:
51- replace: Substitute text with new content
52- append_eof: Append new text at the end of the file
53- prepend_bof: Insert new text at the beginning of the file
54- overwrite: Replace the entire file with new content (automatically creates the file)
55
56Usage notes:
57- All inputs are interpreted literally (no automatic newline or whitespace handling)
58- For replace operations, oldText must appear EXACTLY ONCE in the file
59`
60
61 // If you modify this, update the termui template for prettier rendering.
62 PatchInputSchema = `
63{
64 "type": "object",
65 "required": ["path", "patches"],
66 "properties": {
67 "path": {
68 "type": "string",
69 "description": "Absolute path to the file to patch"
70 },
71 "patches": {
72 "type": "array",
73 "description": "List of patch requests to apply",
74 "items": {
75 "type": "object",
76 "required": ["operation", "newText"],
77 "properties": {
78 "operation": {
79 "type": "string",
80 "enum": ["replace", "append_eof", "prepend_bof", "overwrite"],
81 "description": "Type of operation to perform"
82 },
83 "oldText": {
84 "type": "string",
85 "description": "Text to locate for the operation (must be unique in file, required for replace)"
86 },
87 "newText": {
88 "type": "string",
89 "description": "The new text to use (empty for deletions)"
90 }
91 }
92 }
93 }
94 }
95}
96`
97)
98
99// TODO: maybe rename PatchRequest to PatchOperation or PatchSpec or PatchPart or just Patch?
100
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000101// PatchInput represents the input structure for patch operations.
102type PatchInput struct {
Earl Lee2e463fb2025-04-17 11:22:22 -0700103 Path string `json:"path"`
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000104 Patches []PatchRequest `json:"patches"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700105}
106
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000107// PatchRequest represents a single patch operation.
108type PatchRequest struct {
Earl Lee2e463fb2025-04-17 11:22:22 -0700109 Operation string `json:"operation"`
110 OldText string `json:"oldText,omitempty"`
111 NewText string `json:"newText,omitempty"`
112}
113
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000114// patchRun implements the guts of the patch tool.
115// It populates input from m.
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700116func patchRun(ctx context.Context, m json.RawMessage, input *PatchInput) llm.ToolOut {
Earl Lee2e463fb2025-04-17 11:22:22 -0700117 if err := json.Unmarshal(m, &input); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700118 return llm.ErrorfToolOut("failed to unmarshal user_patch input: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700119 }
120
121 // Validate the input
122 if !filepath.IsAbs(input.Path) {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700123 return llm.ErrorfToolOut("path %q is not absolute", input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700124 }
125 if len(input.Patches) == 0 {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700126 return llm.ErrorToolOut(fmt.Errorf("no patches provided"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700127 }
128 // TODO: check whether the file is autogenerated, and if so, require a "force" flag to modify it.
129
130 orig, err := os.ReadFile(input.Path)
131 // If the file doesn't exist, we can still apply patches
132 // that don't require finding existing text.
133 switch {
134 case errors.Is(err, os.ErrNotExist):
135 for _, patch := range input.Patches {
136 switch patch.Operation {
137 case "prepend_bof", "append_eof", "overwrite":
138 default:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700139 return llm.ErrorfToolOut("file %q does not exist", input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700140 }
141 }
142 case err != nil:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700143 return llm.ErrorfToolOut("failed to read file %q: %w", input.Path, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700144 }
145
146 likelyGoFile := strings.HasSuffix(input.Path, ".go")
147
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000148 autogenerated := likelyGoFile && IsAutogeneratedGoFile(orig)
Earl Lee2e463fb2025-04-17 11:22:22 -0700149 parsed := likelyGoFile && parseGo(orig) != nil
150
151 origStr := string(orig)
152 // Process the patches "simultaneously", minimizing them along the way.
153 // Claude generates patches that interact with each other.
154 buf := editbuf.NewBuffer(orig)
155
156 // TODO: is it better to apply the patches that apply cleanly and report on the failures?
157 // or instead have it be all-or-nothing?
158 // For now, it is all-or-nothing.
159 // TODO: when the model gets into a "cannot apply patch" cycle of doom, how do we get it unstuck?
160 // Also: how do we detect that it's in a cycle?
161 var patchErr error
162 for i, patch := range input.Patches {
163 switch patch.Operation {
164 case "prepend_bof":
165 buf.Insert(0, patch.NewText)
166 case "append_eof":
167 buf.Insert(len(orig), patch.NewText)
168 case "overwrite":
169 buf.Replace(0, len(orig), patch.NewText)
170 case "replace":
171 if patch.OldText == "" {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700172 return llm.ErrorfToolOut("patch %d: oldText cannot be empty for %s operation", i, patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700173 }
174
175 // Attempt to apply the patch.
176 spec, count := patchkit.Unique(origStr, patch.OldText, patch.NewText)
177 switch count {
178 case 0:
179 // no matches, maybe recoverable, continued below
180 case 1:
181 // exact match, apply
182 slog.DebugContext(ctx, "patch_applied", "method", "unique")
183 spec.ApplyToEditBuf(buf)
184 continue
185 case 2:
186 // multiple matches
187 patchErr = errors.Join(patchErr, fmt.Errorf("old text not unique:\n%s", patch.OldText))
188 default:
189 // TODO: return an error instead of using agentPatch
190 slog.ErrorContext(ctx, "unique returned unexpected count", "count", count)
191 patchErr = errors.Join(patchErr, fmt.Errorf("internal error"))
192 continue
193 }
194
195 // The following recovery mechanisms are heuristic.
196 // They aren't perfect, but they appear safe,
197 // and the cases they cover appear with some regularity.
198
199 // Try adjusting the whitespace prefix.
200 spec, ok := patchkit.UniqueDedent(origStr, patch.OldText, patch.NewText)
201 if ok {
202 slog.DebugContext(ctx, "patch_applied", "method", "unique_dedent")
203 spec.ApplyToEditBuf(buf)
204 continue
205 }
206
207 // Try ignoring leading/trailing whitespace in a semantically safe way.
208 spec, ok = patchkit.UniqueInValidGo(origStr, patch.OldText, patch.NewText)
209 if ok {
210 slog.DebugContext(ctx, "patch_applied", "method", "unique_in_valid_go")
211 spec.ApplyToEditBuf(buf)
212 continue
213 }
214
215 // Try ignoring semantically insignificant whitespace.
216 spec, ok = patchkit.UniqueGoTokens(origStr, patch.OldText, patch.NewText)
217 if ok {
218 slog.DebugContext(ctx, "patch_applied", "method", "unique_go_tokens")
219 spec.ApplyToEditBuf(buf)
220 continue
221 }
222
223 // Try trimming the first line of the patch, if we can do so safely.
224 spec, ok = patchkit.UniqueTrim(origStr, patch.OldText, patch.NewText)
225 if ok {
226 slog.DebugContext(ctx, "patch_applied", "method", "unique_trim")
227 spec.ApplyToEditBuf(buf)
228 continue
229 }
230
231 // No dice.
232 patchErr = errors.Join(patchErr, fmt.Errorf("old text not found:\n%s", patch.OldText))
233 continue
234 default:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700235 return llm.ErrorfToolOut("unrecognized operation %q", patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700236 }
237 }
238
239 if patchErr != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700240 return llm.ErrorToolOut(patchErr)
Earl Lee2e463fb2025-04-17 11:22:22 -0700241 }
242
243 patched, err := buf.Bytes()
244 if err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700245 return llm.ErrorToolOut(err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700246 }
247 if err := os.MkdirAll(filepath.Dir(input.Path), 0o700); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700248 return llm.ErrorfToolOut("failed to create directory %q: %w", filepath.Dir(input.Path), err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700249 }
250 if err := os.WriteFile(input.Path, patched, 0o600); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700251 return llm.ErrorfToolOut("failed to write patched contents to file %q: %w", input.Path, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700252 }
253
254 response := new(strings.Builder)
255 fmt.Fprintf(response, "- Applied all patches\n")
256
257 if parsed {
258 parseErr := parseGo(patched)
259 if parseErr != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700260 return llm.ErrorfToolOut("after applying all patches, the file no longer parses:\n%w", parseErr)
Earl Lee2e463fb2025-04-17 11:22:22 -0700261 }
262 }
263
264 if autogenerated {
265 fmt.Fprintf(response, "- WARNING: %q appears to be autogenerated. Patches were applied anyway.\n", input.Path)
266 }
267
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -0700268 diff := generateUnifiedDiff(input.Path, string(orig), string(patched))
269
Earl Lee2e463fb2025-04-17 11:22:22 -0700270 // 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 -0700271 return llm.ToolOut{
272 LLMContent: llm.TextContent(response.String()),
273 Display: diff,
274 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700275}
276
277func parseGo(buf []byte) error {
278 fset := token.NewFileSet()
279 _, err := parser.ParseFile(fset, "", buf, parser.SkipObjectResolution)
280 return err
281}
282
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000283// IsAutogeneratedGoFile reports whether a Go file has markers indicating it was autogenerated.
284func IsAutogeneratedGoFile(buf []byte) bool {
Earl Lee2e463fb2025-04-17 11:22:22 -0700285 for _, sig := range autogeneratedSignals {
286 if bytes.Contains(buf, []byte(sig)) {
287 return true
288 }
289 }
290
291 // https://pkg.go.dev/cmd/go#hdr-Generate_Go_files_by_processing_source
292 // "This line must appear before the first non-comment, non-blank text in the file."
293 // Approximate that by looking for it at the top of the file, before the last of the imports.
294 // (Sometimes people put it after the package declaration, because of course they do.)
295 // At least in the imports region we know it's not part of their actual code;
296 // we don't want to ignore the generator (which also includes these strings!),
297 // just the generated code.
298 fset := token.NewFileSet()
299 f, err := parser.ParseFile(fset, "x.go", buf, parser.ImportsOnly|parser.ParseComments)
300 if err == nil {
301 for _, cg := range f.Comments {
302 t := strings.ToLower(cg.Text())
303 for _, sig := range autogeneratedHeaderSignals {
304 if strings.Contains(t, sig) {
305 return true
306 }
307 }
308 }
309 }
310
311 return false
312}
313
314// autogeneratedSignals are signals that a file is autogenerated, when present anywhere in the file.
315var autogeneratedSignals = [][]byte{
316 []byte("\nfunc bindataRead("), // pre-embed bindata packed file
317}
318
319// autogeneratedHeaderSignals are signals that a file is autogenerated, when present at the top of the file.
320var autogeneratedHeaderSignals = []string{
321 // canonical would be `(?m)^// Code generated .* DO NOT EDIT\.$`
322 // but people screw it up, a lot, so be more lenient
323 strings.ToLower("generate"),
324 strings.ToLower("DO NOT EDIT"),
325 strings.ToLower("export by"),
326}
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -0700327
328func generateUnifiedDiff(filePath, original, patched string) string {
329 buf := new(strings.Builder)
330 err := diff.Text(filePath, filePath, original, patched, buf)
331 if err != nil {
332 return fmt.Sprintf("(diff generation failed: %v)\n", err)
333 }
334 return buf.String()
335}