blob: 1f3231c92b338423cd8a096574d0944092d03b83 [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
161 origStr := string(orig)
162 // Process the patches "simultaneously", minimizing them along the way.
163 // Claude generates patches that interact with each other.
164 buf := editbuf.NewBuffer(orig)
165
166 // TODO: is it better to apply the patches that apply cleanly and report on the failures?
167 // or instead have it be all-or-nothing?
168 // For now, it is all-or-nothing.
169 // TODO: when the model gets into a "cannot apply patch" cycle of doom, how do we get it unstuck?
170 // Also: how do we detect that it's in a cycle?
171 var patchErr error
172 for i, patch := range input.Patches {
173 switch patch.Operation {
174 case "prepend_bof":
175 buf.Insert(0, patch.NewText)
176 case "append_eof":
177 buf.Insert(len(orig), patch.NewText)
178 case "overwrite":
179 buf.Replace(0, len(orig), patch.NewText)
180 case "replace":
181 if patch.OldText == "" {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700182 return llm.ErrorfToolOut("patch %d: oldText cannot be empty for %s operation", i, patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700183 }
184
185 // Attempt to apply the patch.
186 spec, count := patchkit.Unique(origStr, patch.OldText, patch.NewText)
187 switch count {
188 case 0:
189 // no matches, maybe recoverable, continued below
190 case 1:
191 // exact match, apply
192 slog.DebugContext(ctx, "patch_applied", "method", "unique")
193 spec.ApplyToEditBuf(buf)
194 continue
195 case 2:
196 // multiple matches
197 patchErr = errors.Join(patchErr, fmt.Errorf("old text not unique:\n%s", patch.OldText))
198 default:
199 // TODO: return an error instead of using agentPatch
200 slog.ErrorContext(ctx, "unique returned unexpected count", "count", count)
201 patchErr = errors.Join(patchErr, fmt.Errorf("internal error"))
202 continue
203 }
204
205 // The following recovery mechanisms are heuristic.
206 // They aren't perfect, but they appear safe,
207 // and the cases they cover appear with some regularity.
208
209 // Try adjusting the whitespace prefix.
210 spec, ok := patchkit.UniqueDedent(origStr, patch.OldText, patch.NewText)
211 if ok {
212 slog.DebugContext(ctx, "patch_applied", "method", "unique_dedent")
213 spec.ApplyToEditBuf(buf)
214 continue
215 }
216
217 // Try ignoring leading/trailing whitespace in a semantically safe way.
218 spec, ok = patchkit.UniqueInValidGo(origStr, patch.OldText, patch.NewText)
219 if ok {
220 slog.DebugContext(ctx, "patch_applied", "method", "unique_in_valid_go")
221 spec.ApplyToEditBuf(buf)
222 continue
223 }
224
225 // Try ignoring semantically insignificant whitespace.
226 spec, ok = patchkit.UniqueGoTokens(origStr, patch.OldText, patch.NewText)
227 if ok {
228 slog.DebugContext(ctx, "patch_applied", "method", "unique_go_tokens")
229 spec.ApplyToEditBuf(buf)
230 continue
231 }
232
233 // Try trimming the first line of the patch, if we can do so safely.
234 spec, ok = patchkit.UniqueTrim(origStr, patch.OldText, patch.NewText)
235 if ok {
236 slog.DebugContext(ctx, "patch_applied", "method", "unique_trim")
237 spec.ApplyToEditBuf(buf)
238 continue
239 }
240
241 // No dice.
242 patchErr = errors.Join(patchErr, fmt.Errorf("old text not found:\n%s", patch.OldText))
243 continue
244 default:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700245 return llm.ErrorfToolOut("unrecognized operation %q", patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700246 }
247 }
248
249 if patchErr != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700250 return llm.ErrorToolOut(patchErr)
Earl Lee2e463fb2025-04-17 11:22:22 -0700251 }
252
253 patched, err := buf.Bytes()
254 if err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700255 return llm.ErrorToolOut(err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700256 }
257 if err := os.MkdirAll(filepath.Dir(input.Path), 0o700); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700258 return llm.ErrorfToolOut("failed to create directory %q: %w", filepath.Dir(input.Path), err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700259 }
260 if err := os.WriteFile(input.Path, patched, 0o600); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700261 return llm.ErrorfToolOut("failed to write patched contents to file %q: %w", input.Path, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700262 }
263
264 response := new(strings.Builder)
265 fmt.Fprintf(response, "- Applied all patches\n")
266
Earl Lee2e463fb2025-04-17 11:22:22 -0700267 if autogenerated {
268 fmt.Fprintf(response, "- WARNING: %q appears to be autogenerated. Patches were applied anyway.\n", input.Path)
269 }
270
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -0700271 diff := generateUnifiedDiff(input.Path, string(orig), string(patched))
272
Earl Lee2e463fb2025-04-17 11:22:22 -0700273 // 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 -0700274 return llm.ToolOut{
275 LLMContent: llm.TextContent(response.String()),
276 Display: diff,
277 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700278}
279
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000280// IsAutogeneratedGoFile reports whether a Go file has markers indicating it was autogenerated.
281func IsAutogeneratedGoFile(buf []byte) bool {
Earl Lee2e463fb2025-04-17 11:22:22 -0700282 for _, sig := range autogeneratedSignals {
283 if bytes.Contains(buf, []byte(sig)) {
284 return true
285 }
286 }
287
288 // https://pkg.go.dev/cmd/go#hdr-Generate_Go_files_by_processing_source
289 // "This line must appear before the first non-comment, non-blank text in the file."
290 // Approximate that by looking for it at the top of the file, before the last of the imports.
291 // (Sometimes people put it after the package declaration, because of course they do.)
292 // At least in the imports region we know it's not part of their actual code;
293 // we don't want to ignore the generator (which also includes these strings!),
294 // just the generated code.
295 fset := token.NewFileSet()
296 f, err := parser.ParseFile(fset, "x.go", buf, parser.ImportsOnly|parser.ParseComments)
297 if err == nil {
298 for _, cg := range f.Comments {
299 t := strings.ToLower(cg.Text())
300 for _, sig := range autogeneratedHeaderSignals {
301 if strings.Contains(t, sig) {
302 return true
303 }
304 }
305 }
306 }
307
308 return false
309}
310
311// autogeneratedSignals are signals that a file is autogenerated, when present anywhere in the file.
312var autogeneratedSignals = [][]byte{
313 []byte("\nfunc bindataRead("), // pre-embed bindata packed file
314}
315
316// autogeneratedHeaderSignals are signals that a file is autogenerated, when present at the top of the file.
317var autogeneratedHeaderSignals = []string{
318 // canonical would be `(?m)^// Code generated .* DO NOT EDIT\.$`
319 // but people screw it up, a lot, so be more lenient
320 strings.ToLower("generate"),
321 strings.ToLower("DO NOT EDIT"),
322 strings.ToLower("export by"),
323}
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -0700324
325func generateUnifiedDiff(filePath, original, patched string) string {
326 buf := new(strings.Builder)
327 err := diff.Text(filePath, filePath, original, patched, buf)
328 if err != nil {
329 return fmt.Sprintf("(diff generation failed: %v)\n", err)
330 }
331 return buf.String()
332}