blob: f398ac6a28cd039b57fc66e3ccdf1291eb0892a2 [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 Snyder994e9842025-07-30 20:26:47 -070034 // Simplified indicates whether to use the simplified input schema.
35 // Helpful for weaker models.
36 Simplified bool
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -070037 // ClipboardEnabled controls whether clipboard functionality is enabled.
Josh Bleecher Snyder994e9842025-07-30 20:26:47 -070038 // Ignored if Simplified is true.
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -070039 // NB: The actual implementation of the patch tool is unchanged,
40 // this flag merely extends the description and input schema to include the clipboard operations.
41 ClipboardEnabled bool
42 // clipboards stores clipboard name -> text
43 clipboards map[string]string
Josh Bleecher Snyder04f16a52025-07-30 11:46:25 -070044}
45
46// Tool returns an llm.Tool based on p.
47func (p *PatchTool) Tool() *llm.Tool {
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -070048 description := PatchBaseDescription + PatchUsageNotes
49 schema := PatchStandardInputSchema
Josh Bleecher Snyder994e9842025-07-30 20:26:47 -070050 switch {
51 case p.Simplified:
52 schema = PatchStandardSimplifiedSchema
53 case p.ClipboardEnabled:
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -070054 description = PatchBaseDescription + PatchClipboardDescription + PatchUsageNotes
55 schema = PatchClipboardInputSchema
56 }
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000057 return &llm.Tool{
58 Name: PatchName,
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -070059 Description: strings.TrimSpace(description),
60 InputSchema: llm.MustSchema(schema),
Josh Bleecher Snyder534783d2025-07-29 08:17:37 -070061 Run: p.Run,
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000062 }
Earl Lee2e463fb2025-04-17 11:22:22 -070063}
64
65const (
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -070066 PatchName = "patch"
67 PatchBaseDescription = `
Earl Lee2e463fb2025-04-17 11:22:22 -070068File modification tool for precise text edits.
69
70Operations:
Josh Bleecher Snyder534783d2025-07-29 08:17:37 -070071- replace: Substitute unique text with new content
Earl Lee2e463fb2025-04-17 11:22:22 -070072- append_eof: Append new text at the end of the file
73- prepend_bof: Insert new text at the beginning of the file
74- overwrite: Replace the entire file with new content (automatically creates the file)
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -070075`
Earl Lee2e463fb2025-04-17 11:22:22 -070076
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -070077 PatchClipboardDescription = `
78Clipboard:
79- toClipboard: Store oldText to a named clipboard before the operation
80- fromClipboard: Use clipboard content as newText (ignores provided newText)
81- Clipboards persist across patch calls
82- Always use clipboards when moving/copying code (within or across files), even when the moved/copied code will also have edits.
83 This prevents transcription errors and distinguishes intentional changes from unintentional changes.
84
85Indentation adjustment:
86- reindent applies to whatever text is being inserted
87- First strips the specified prefix from each line, then adds the new prefix
88- Useful when moving code from one indentation to another
89
90Recipes:
91- cut: replace with empty newText and toClipboard
92- copy: replace with toClipboard and fromClipboard using the same clipboard name
93- paste: replace with fromClipboard
94- in-place indentation change: same as copy, but add indentation adjustment
95`
96
97 PatchUsageNotes = `
Earl Lee2e463fb2025-04-17 11:22:22 -070098Usage notes:
99- All inputs are interpreted literally (no automatic newline or whitespace handling)
100- For replace operations, oldText must appear EXACTLY ONCE in the file
101`
102
103 // If you modify this, update the termui template for prettier rendering.
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700104 PatchStandardInputSchema = `
Earl Lee2e463fb2025-04-17 11:22:22 -0700105{
106 "type": "object",
107 "required": ["path", "patches"],
108 "properties": {
109 "path": {
110 "type": "string",
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700111 "description": "Path to the file to patch"
Earl Lee2e463fb2025-04-17 11:22:22 -0700112 },
113 "patches": {
114 "type": "array",
115 "description": "List of patch requests to apply",
116 "items": {
117 "type": "object",
118 "required": ["operation", "newText"],
119 "properties": {
120 "operation": {
121 "type": "string",
122 "enum": ["replace", "append_eof", "prepend_bof", "overwrite"],
123 "description": "Type of operation to perform"
124 },
125 "oldText": {
126 "type": "string",
127 "description": "Text to locate for the operation (must be unique in file, required for replace)"
128 },
129 "newText": {
130 "type": "string",
131 "description": "The new text to use (empty for deletions)"
132 }
133 }
134 }
135 }
136 }
137}
138`
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700139
Josh Bleecher Snyder994e9842025-07-30 20:26:47 -0700140 PatchStandardSimplifiedSchema = `{
141 "type": "object",
142 "required": ["path", "patch"],
143 "properties": {
144 "path": {
145 "type": "string",
146 "description": "Path to the file to patch"
147 },
148 "patch": {
149 "type": "object",
150 "required": ["operation", "newText"],
151 "properties": {
152 "operation": {
153 "type": "string",
154 "enum": ["replace", "append_eof", "prepend_bof", "overwrite"],
155 "description": "Type of operation to perform"
156 },
157 "oldText": {
158 "type": "string",
159 "description": "Text to locate for the operation (must be unique in file, required for replace)"
160 },
161 "newText": {
162 "type": "string",
163 "description": "The new text to use (empty for deletions)"
164 }
165 }
166 }
167 }
168}`
169
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700170 PatchClipboardInputSchema = `
171{
172 "type": "object",
173 "required": ["path", "patches"],
174 "properties": {
175 "path": {
176 "type": "string",
177 "description": "Path to the file to patch"
178 },
179 "patches": {
180 "type": "array",
181 "description": "List of patch requests to apply",
182 "items": {
183 "type": "object",
184 "required": ["operation"],
185 "properties": {
186 "operation": {
187 "type": "string",
188 "enum": ["replace", "append_eof", "prepend_bof", "overwrite"],
189 "description": "Type of operation to perform"
190 },
191 "oldText": {
192 "type": "string",
193 "description": "Text to locate (must be unique in file, required for replace)"
194 },
195 "newText": {
196 "type": "string",
197 "description": "The new text to use (empty for deletions, leave empty if fromClipboard is set)"
198 },
199 "toClipboard": {
200 "type": "string",
201 "description": "Save oldText to this named clipboard before the operation"
202 },
203 "fromClipboard": {
204 "type": "string",
205 "description": "Use content from this clipboard as newText (overrides newText field)"
206 },
207 "reindent": {
208 "type": "object",
209 "description": "Modify indentation of the inserted text (newText or fromClipboard) before insertion",
210 "properties": {
211 "strip": {
212 "type": "string",
213 "description": "Remove this prefix from each non-empty line before insertion"
214 },
215 "add": {
216 "type": "string",
217 "description": "Add this prefix to each non-empty line after stripping"
218 }
219 }
220 }
221 }
222 }
223 }
224 }
225}
226`
Earl Lee2e463fb2025-04-17 11:22:22 -0700227)
228
229// TODO: maybe rename PatchRequest to PatchOperation or PatchSpec or PatchPart or just Patch?
230
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000231// PatchInput represents the input structure for patch operations.
232type PatchInput struct {
Earl Lee2e463fb2025-04-17 11:22:22 -0700233 Path string `json:"path"`
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000234 Patches []PatchRequest `json:"patches"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700235}
236
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700237// PatchInputOne is a simplified version of PatchInput for single patch operations.
238type PatchInputOne struct {
Josh Bleecher Snyder994e9842025-07-30 20:26:47 -0700239 Path string `json:"path"`
240 Patches *PatchRequest `json:"patches"`
241}
242
243// PatchInputOneSingular is PatchInputOne with a better name for the singular case.
244type PatchInputOneSingular struct {
245 Path string `json:"path"`
246 Patch *PatchRequest `json:"patch"`
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700247}
248
249type PatchInputOneString struct {
250 Path string `json:"path"`
251 Patches string `json:"patches"` // contains Patches as a JSON string 🤦
252}
253
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000254// PatchRequest represents a single patch operation.
255type PatchRequest struct {
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700256 Operation string `json:"operation"`
257 OldText string `json:"oldText,omitempty"`
258 NewText string `json:"newText,omitempty"`
259 ToClipboard string `json:"toClipboard,omitempty"`
260 FromClipboard string `json:"fromClipboard,omitempty"`
261 Reindent *Reindent `json:"reindent,omitempty"`
262}
263
264// Reindent represents indentation adjustment configuration.
265type Reindent struct {
266 // TODO: it might be nice to make this more flexible,
267 // so it can e.g. strip all whitespace,
268 // or strip the prefix only on lines where it is present,
269 // or strip based on a regex.
270 Strip string `json:"strip,omitempty"`
271 Add string `json:"add,omitempty"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700272}
273
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700274// Run implements the patch tool logic.
275func (p *PatchTool) Run(ctx context.Context, m json.RawMessage) llm.ToolOut {
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700276 if p.clipboards == nil {
277 p.clipboards = make(map[string]string)
278 }
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700279 input, err := p.patchParse(m)
280 var output llm.ToolOut
281 if err != nil {
282 output = llm.ErrorToolOut(err)
283 } else {
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700284 output = p.patchRun(ctx, &input)
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700285 }
286 if p.Callback != nil {
287 return p.Callback(input, output)
288 }
289 return output
290}
291
292// patchParse parses the input message into a PatchInput structure.
293// It accepts a few different formats, because empirically,
294// LLMs sometimes generate slightly different JSON structures,
295// and we may as well accept such near misses.
296func (p *PatchTool) patchParse(m json.RawMessage) (PatchInput, error) {
297 var input PatchInput
298 originalErr := json.Unmarshal(m, &input)
Josh Bleecher Snyder994e9842025-07-30 20:26:47 -0700299 if originalErr == nil && len(input.Patches) > 0 {
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700300 return input, nil
301 }
302 var inputOne PatchInputOne
Josh Bleecher Snyder994e9842025-07-30 20:26:47 -0700303 if err := json.Unmarshal(m, &inputOne); err == nil && inputOne.Patches != nil {
304 return PatchInput{Path: inputOne.Path, Patches: []PatchRequest{*inputOne.Patches}}, nil
305 }
306 var inputOneSingular PatchInputOneSingular
307 if err := json.Unmarshal(m, &inputOneSingular); err == nil && inputOneSingular.Patch != nil {
308 return PatchInput{Path: inputOneSingular.Path, Patches: []PatchRequest{*inputOneSingular.Patch}}, nil
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700309 }
310 var inputOneString PatchInputOneString
311 if err := json.Unmarshal(m, &inputOneString); err == nil {
312 var onePatch PatchRequest
Josh Bleecher Snyder994e9842025-07-30 20:26:47 -0700313 if err := json.Unmarshal([]byte(inputOneString.Patches), &onePatch); err == nil && onePatch.Operation != "" {
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700314 return PatchInput{Path: inputOneString.Path, Patches: []PatchRequest{onePatch}}, nil
315 }
316 var patches []PatchRequest
317 if err := json.Unmarshal([]byte(inputOneString.Patches), &patches); err == nil {
318 return PatchInput{Path: inputOneString.Path, Patches: patches}, nil
319 }
320 }
321 return PatchInput{}, fmt.Errorf("failed to unmarshal patch input: %w", originalErr)
322}
323
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000324// patchRun implements the guts of the patch tool.
325// It populates input from m.
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700326func (p *PatchTool) patchRun(ctx context.Context, input *PatchInput) llm.ToolOut {
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700327 path := input.Path
Earl Lee2e463fb2025-04-17 11:22:22 -0700328 if !filepath.IsAbs(input.Path) {
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700329 if p.Pwd == "" {
330 return llm.ErrorfToolOut("path %q is not absolute and no working directory is set", input.Path)
331 }
332 path = filepath.Join(p.Pwd, input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700333 }
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700334 input.Path = path
Earl Lee2e463fb2025-04-17 11:22:22 -0700335 if len(input.Patches) == 0 {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700336 return llm.ErrorToolOut(fmt.Errorf("no patches provided"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700337 }
338 // TODO: check whether the file is autogenerated, and if so, require a "force" flag to modify it.
339
340 orig, err := os.ReadFile(input.Path)
341 // If the file doesn't exist, we can still apply patches
342 // that don't require finding existing text.
343 switch {
344 case errors.Is(err, os.ErrNotExist):
345 for _, patch := range input.Patches {
346 switch patch.Operation {
347 case "prepend_bof", "append_eof", "overwrite":
348 default:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700349 return llm.ErrorfToolOut("file %q does not exist", input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700350 }
351 }
352 case err != nil:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700353 return llm.ErrorfToolOut("failed to read file %q: %w", input.Path, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700354 }
355
356 likelyGoFile := strings.HasSuffix(input.Path, ".go")
357
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000358 autogenerated := likelyGoFile && IsAutogeneratedGoFile(orig)
Earl Lee2e463fb2025-04-17 11:22:22 -0700359
360 origStr := string(orig)
361 // Process the patches "simultaneously", minimizing them along the way.
362 // Claude generates patches that interact with each other.
363 buf := editbuf.NewBuffer(orig)
364
365 // TODO: is it better to apply the patches that apply cleanly and report on the failures?
366 // or instead have it be all-or-nothing?
367 // For now, it is all-or-nothing.
368 // TODO: when the model gets into a "cannot apply patch" cycle of doom, how do we get it unstuck?
369 // Also: how do we detect that it's in a cycle?
370 var patchErr error
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700371
372 var clipboardsModified []string
373 updateToClipboard := func(patch PatchRequest, spec *patchkit.Spec) {
374 if patch.ToClipboard == "" {
375 return
376 }
377 // Update clipboard with the actual matched text
378 matchedOldText := origStr[spec.Off : spec.Off+spec.Len]
379 p.clipboards[patch.ToClipboard] = matchedOldText
380 clipboardsModified = append(clipboardsModified, fmt.Sprintf(`<clipboard_modified name="%s"><message>clipboard contents altered in order to match uniquely</message><new_contents>%q</new_contents></clipboard_modified>`, patch.ToClipboard, matchedOldText))
381 }
382
Earl Lee2e463fb2025-04-17 11:22:22 -0700383 for i, patch := range input.Patches {
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700384 // Process toClipboard first, so that copy works
385 if patch.ToClipboard != "" {
386 if patch.Operation != "replace" {
387 return llm.ErrorfToolOut("toClipboard (%s): can only be used with replace operation", patch.ToClipboard)
388 }
389 if patch.OldText == "" {
390 return llm.ErrorfToolOut("toClipboard (%s): oldText cannot be empty when using toClipboard", patch.ToClipboard)
391 }
392 p.clipboards[patch.ToClipboard] = patch.OldText
393 }
394
395 // Handle fromClipboard
396 newText := patch.NewText
397 if patch.FromClipboard != "" {
398 clipboardText, ok := p.clipboards[patch.FromClipboard]
399 if !ok {
400 return llm.ErrorfToolOut("fromClipboard (%s): no clipboard with that name", patch.FromClipboard)
401 }
402 newText = clipboardText
403 }
404
405 // Apply indentation adjustment if specified
406 if patch.Reindent != nil {
407 reindentedText, err := reindent(newText, patch.Reindent)
408 if err != nil {
409 return llm.ErrorfToolOut("reindent(%q -> %q): %w", patch.Reindent.Strip, patch.Reindent.Add, err)
410 }
411 newText = reindentedText
412 }
413
Earl Lee2e463fb2025-04-17 11:22:22 -0700414 switch patch.Operation {
415 case "prepend_bof":
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700416 buf.Insert(0, newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700417 case "append_eof":
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700418 buf.Insert(len(orig), newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700419 case "overwrite":
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700420 buf.Replace(0, len(orig), newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700421 case "replace":
422 if patch.OldText == "" {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700423 return llm.ErrorfToolOut("patch %d: oldText cannot be empty for %s operation", i, patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700424 }
425
426 // Attempt to apply the patch.
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700427 spec, count := patchkit.Unique(origStr, patch.OldText, newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700428 switch count {
429 case 0:
430 // no matches, maybe recoverable, continued below
431 case 1:
432 // exact match, apply
433 slog.DebugContext(ctx, "patch_applied", "method", "unique")
434 spec.ApplyToEditBuf(buf)
435 continue
436 case 2:
437 // multiple matches
438 patchErr = errors.Join(patchErr, fmt.Errorf("old text not unique:\n%s", patch.OldText))
Josh Bleecher Snyderdba25ee2025-07-30 19:40:22 -0700439 continue
Earl Lee2e463fb2025-04-17 11:22:22 -0700440 default:
Earl Lee2e463fb2025-04-17 11:22:22 -0700441 slog.ErrorContext(ctx, "unique returned unexpected count", "count", count)
442 patchErr = errors.Join(patchErr, fmt.Errorf("internal error"))
443 continue
444 }
445
446 // The following recovery mechanisms are heuristic.
447 // They aren't perfect, but they appear safe,
448 // and the cases they cover appear with some regularity.
449
450 // Try adjusting the whitespace prefix.
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700451 spec, ok := patchkit.UniqueDedent(origStr, patch.OldText, newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700452 if ok {
453 slog.DebugContext(ctx, "patch_applied", "method", "unique_dedent")
454 spec.ApplyToEditBuf(buf)
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700455 updateToClipboard(patch, spec)
Earl Lee2e463fb2025-04-17 11:22:22 -0700456 continue
457 }
458
459 // Try ignoring leading/trailing whitespace in a semantically safe way.
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700460 spec, ok = patchkit.UniqueInValidGo(origStr, patch.OldText, newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700461 if ok {
462 slog.DebugContext(ctx, "patch_applied", "method", "unique_in_valid_go")
463 spec.ApplyToEditBuf(buf)
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700464 updateToClipboard(patch, spec)
Earl Lee2e463fb2025-04-17 11:22:22 -0700465 continue
466 }
467
468 // Try ignoring semantically insignificant whitespace.
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700469 spec, ok = patchkit.UniqueGoTokens(origStr, patch.OldText, newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700470 if ok {
471 slog.DebugContext(ctx, "patch_applied", "method", "unique_go_tokens")
472 spec.ApplyToEditBuf(buf)
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700473 updateToClipboard(patch, spec)
Earl Lee2e463fb2025-04-17 11:22:22 -0700474 continue
475 }
476
477 // Try trimming the first line of the patch, if we can do so safely.
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700478 spec, ok = patchkit.UniqueTrim(origStr, patch.OldText, newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700479 if ok {
480 slog.DebugContext(ctx, "patch_applied", "method", "unique_trim")
481 spec.ApplyToEditBuf(buf)
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700482 // Do NOT call updateToClipboard here,
483 // because the trimmed text may vary significantly from the original text.
Earl Lee2e463fb2025-04-17 11:22:22 -0700484 continue
485 }
486
487 // No dice.
488 patchErr = errors.Join(patchErr, fmt.Errorf("old text not found:\n%s", patch.OldText))
489 continue
490 default:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700491 return llm.ErrorfToolOut("unrecognized operation %q", patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700492 }
493 }
494
495 if patchErr != nil {
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700496 errorMsg := patchErr.Error()
497 for _, msg := range clipboardsModified {
498 errorMsg += "\n" + msg
499 }
500 return llm.ErrorToolOut(fmt.Errorf("%s", errorMsg))
Earl Lee2e463fb2025-04-17 11:22:22 -0700501 }
502
503 patched, err := buf.Bytes()
504 if err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700505 return llm.ErrorToolOut(err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700506 }
507 if err := os.MkdirAll(filepath.Dir(input.Path), 0o700); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700508 return llm.ErrorfToolOut("failed to create directory %q: %w", filepath.Dir(input.Path), err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700509 }
510 if err := os.WriteFile(input.Path, patched, 0o600); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700511 return llm.ErrorfToolOut("failed to write patched contents to file %q: %w", input.Path, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700512 }
513
514 response := new(strings.Builder)
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700515 fmt.Fprintf(response, "<patches_applied>all</patches_applied>\n")
516 for _, msg := range clipboardsModified {
517 fmt.Fprintln(response, msg)
518 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700519
Earl Lee2e463fb2025-04-17 11:22:22 -0700520 if autogenerated {
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700521 fmt.Fprintf(response, "<warning>%q appears to be autogenerated. Patches were applied anyway.</warning>\n", input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700522 }
523
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -0700524 diff := generateUnifiedDiff(input.Path, string(orig), string(patched))
525
Earl Lee2e463fb2025-04-17 11:22:22 -0700526 // 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 -0700527 return llm.ToolOut{
528 LLMContent: llm.TextContent(response.String()),
529 Display: diff,
530 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700531}
532
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000533// IsAutogeneratedGoFile reports whether a Go file has markers indicating it was autogenerated.
534func IsAutogeneratedGoFile(buf []byte) bool {
Earl Lee2e463fb2025-04-17 11:22:22 -0700535 for _, sig := range autogeneratedSignals {
536 if bytes.Contains(buf, []byte(sig)) {
537 return true
538 }
539 }
540
541 // https://pkg.go.dev/cmd/go#hdr-Generate_Go_files_by_processing_source
542 // "This line must appear before the first non-comment, non-blank text in the file."
543 // Approximate that by looking for it at the top of the file, before the last of the imports.
544 // (Sometimes people put it after the package declaration, because of course they do.)
545 // At least in the imports region we know it's not part of their actual code;
546 // we don't want to ignore the generator (which also includes these strings!),
547 // just the generated code.
548 fset := token.NewFileSet()
549 f, err := parser.ParseFile(fset, "x.go", buf, parser.ImportsOnly|parser.ParseComments)
550 if err == nil {
551 for _, cg := range f.Comments {
552 t := strings.ToLower(cg.Text())
553 for _, sig := range autogeneratedHeaderSignals {
554 if strings.Contains(t, sig) {
555 return true
556 }
557 }
558 }
559 }
560
561 return false
562}
563
564// autogeneratedSignals are signals that a file is autogenerated, when present anywhere in the file.
565var autogeneratedSignals = [][]byte{
566 []byte("\nfunc bindataRead("), // pre-embed bindata packed file
567}
568
569// autogeneratedHeaderSignals are signals that a file is autogenerated, when present at the top of the file.
570var autogeneratedHeaderSignals = []string{
571 // canonical would be `(?m)^// Code generated .* DO NOT EDIT\.$`
572 // but people screw it up, a lot, so be more lenient
573 strings.ToLower("generate"),
574 strings.ToLower("DO NOT EDIT"),
575 strings.ToLower("export by"),
576}
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -0700577
578func generateUnifiedDiff(filePath, original, patched string) string {
579 buf := new(strings.Builder)
580 err := diff.Text(filePath, filePath, original, patched, buf)
581 if err != nil {
582 return fmt.Sprintf("(diff generation failed: %v)\n", err)
583 }
584 return buf.String()
585}
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700586
587// reindent applies indentation adjustments to text.
588func reindent(text string, adj *Reindent) (string, error) {
589 if adj == nil {
590 return text, nil
591 }
592
593 lines := strings.Split(text, "\n")
594
595 for i, line := range lines {
596 if line == "" {
597 continue
598 }
599 var ok bool
600 lines[i], ok = strings.CutPrefix(line, adj.Strip)
601 if !ok {
602 return "", fmt.Errorf("strip precondition failed: line %q does not start with %q", line, adj.Strip)
603 }
604 }
605
606 for i, line := range lines {
607 if line == "" {
608 continue
609 }
610 lines[i] = adj.Add + line
611 }
612
613 return strings.Join(lines, "\n"), nil
614}