blob: bd01fa80363023702e19262d4c203bd01fde55e7 [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 Snyder7f18fb62025-07-30 18:12:29 -070034 // ClipboardEnabled controls whether clipboard functionality is enabled.
35 // NB: The actual implementation of the patch tool is unchanged,
36 // this flag merely extends the description and input schema to include the clipboard operations.
37 ClipboardEnabled bool
38 // clipboards stores clipboard name -> text
39 clipboards map[string]string
Josh Bleecher Snyder04f16a52025-07-30 11:46:25 -070040}
41
42// Tool returns an llm.Tool based on p.
43func (p *PatchTool) Tool() *llm.Tool {
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -070044 description := PatchBaseDescription + PatchUsageNotes
45 schema := PatchStandardInputSchema
46 if p.ClipboardEnabled {
47 description = PatchBaseDescription + PatchClipboardDescription + PatchUsageNotes
48 schema = PatchClipboardInputSchema
49 }
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000050 return &llm.Tool{
51 Name: PatchName,
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -070052 Description: strings.TrimSpace(description),
53 InputSchema: llm.MustSchema(schema),
Josh Bleecher Snyder534783d2025-07-29 08:17:37 -070054 Run: p.Run,
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +000055 }
Earl Lee2e463fb2025-04-17 11:22:22 -070056}
57
58const (
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -070059 PatchName = "patch"
60 PatchBaseDescription = `
Earl Lee2e463fb2025-04-17 11:22:22 -070061File modification tool for precise text edits.
62
63Operations:
Josh Bleecher Snyder534783d2025-07-29 08:17:37 -070064- replace: Substitute unique text with new content
Earl Lee2e463fb2025-04-17 11:22:22 -070065- append_eof: Append new text at the end of the file
66- prepend_bof: Insert new text at the beginning of the file
67- overwrite: Replace the entire file with new content (automatically creates the file)
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -070068`
Earl Lee2e463fb2025-04-17 11:22:22 -070069
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -070070 PatchClipboardDescription = `
71Clipboard:
72- toClipboard: Store oldText to a named clipboard before the operation
73- fromClipboard: Use clipboard content as newText (ignores provided newText)
74- Clipboards persist across patch calls
75- Always use clipboards when moving/copying code (within or across files), even when the moved/copied code will also have edits.
76 This prevents transcription errors and distinguishes intentional changes from unintentional changes.
77
78Indentation adjustment:
79- reindent applies to whatever text is being inserted
80- First strips the specified prefix from each line, then adds the new prefix
81- Useful when moving code from one indentation to another
82
83Recipes:
84- cut: replace with empty newText and toClipboard
85- copy: replace with toClipboard and fromClipboard using the same clipboard name
86- paste: replace with fromClipboard
87- in-place indentation change: same as copy, but add indentation adjustment
88`
89
90 PatchUsageNotes = `
Earl Lee2e463fb2025-04-17 11:22:22 -070091Usage notes:
92- All inputs are interpreted literally (no automatic newline or whitespace handling)
93- For replace operations, oldText must appear EXACTLY ONCE in the file
94`
95
96 // If you modify this, update the termui template for prettier rendering.
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -070097 PatchStandardInputSchema = `
Earl Lee2e463fb2025-04-17 11:22:22 -070098{
99 "type": "object",
100 "required": ["path", "patches"],
101 "properties": {
102 "path": {
103 "type": "string",
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700104 "description": "Path to the file to patch"
Earl Lee2e463fb2025-04-17 11:22:22 -0700105 },
106 "patches": {
107 "type": "array",
108 "description": "List of patch requests to apply",
109 "items": {
110 "type": "object",
111 "required": ["operation", "newText"],
112 "properties": {
113 "operation": {
114 "type": "string",
115 "enum": ["replace", "append_eof", "prepend_bof", "overwrite"],
116 "description": "Type of operation to perform"
117 },
118 "oldText": {
119 "type": "string",
120 "description": "Text to locate for the operation (must be unique in file, required for replace)"
121 },
122 "newText": {
123 "type": "string",
124 "description": "The new text to use (empty for deletions)"
125 }
126 }
127 }
128 }
129 }
130}
131`
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700132
133 PatchClipboardInputSchema = `
134{
135 "type": "object",
136 "required": ["path", "patches"],
137 "properties": {
138 "path": {
139 "type": "string",
140 "description": "Path to the file to patch"
141 },
142 "patches": {
143 "type": "array",
144 "description": "List of patch requests to apply",
145 "items": {
146 "type": "object",
147 "required": ["operation"],
148 "properties": {
149 "operation": {
150 "type": "string",
151 "enum": ["replace", "append_eof", "prepend_bof", "overwrite"],
152 "description": "Type of operation to perform"
153 },
154 "oldText": {
155 "type": "string",
156 "description": "Text to locate (must be unique in file, required for replace)"
157 },
158 "newText": {
159 "type": "string",
160 "description": "The new text to use (empty for deletions, leave empty if fromClipboard is set)"
161 },
162 "toClipboard": {
163 "type": "string",
164 "description": "Save oldText to this named clipboard before the operation"
165 },
166 "fromClipboard": {
167 "type": "string",
168 "description": "Use content from this clipboard as newText (overrides newText field)"
169 },
170 "reindent": {
171 "type": "object",
172 "description": "Modify indentation of the inserted text (newText or fromClipboard) before insertion",
173 "properties": {
174 "strip": {
175 "type": "string",
176 "description": "Remove this prefix from each non-empty line before insertion"
177 },
178 "add": {
179 "type": "string",
180 "description": "Add this prefix to each non-empty line after stripping"
181 }
182 }
183 }
184 }
185 }
186 }
187 }
188}
189`
Earl Lee2e463fb2025-04-17 11:22:22 -0700190)
191
192// TODO: maybe rename PatchRequest to PatchOperation or PatchSpec or PatchPart or just Patch?
193
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000194// PatchInput represents the input structure for patch operations.
195type PatchInput struct {
Earl Lee2e463fb2025-04-17 11:22:22 -0700196 Path string `json:"path"`
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000197 Patches []PatchRequest `json:"patches"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700198}
199
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700200// PatchInputOne is a simplified version of PatchInput for single patch operations.
201type PatchInputOne struct {
202 Path string `json:"path"`
203 Patches PatchRequest `json:"patches"`
204}
205
206type PatchInputOneString struct {
207 Path string `json:"path"`
208 Patches string `json:"patches"` // contains Patches as a JSON string 🤦
209}
210
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000211// PatchRequest represents a single patch operation.
212type PatchRequest struct {
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700213 Operation string `json:"operation"`
214 OldText string `json:"oldText,omitempty"`
215 NewText string `json:"newText,omitempty"`
216 ToClipboard string `json:"toClipboard,omitempty"`
217 FromClipboard string `json:"fromClipboard,omitempty"`
218 Reindent *Reindent `json:"reindent,omitempty"`
219}
220
221// Reindent represents indentation adjustment configuration.
222type Reindent struct {
223 // TODO: it might be nice to make this more flexible,
224 // so it can e.g. strip all whitespace,
225 // or strip the prefix only on lines where it is present,
226 // or strip based on a regex.
227 Strip string `json:"strip,omitempty"`
228 Add string `json:"add,omitempty"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700229}
230
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700231// Run implements the patch tool logic.
232func (p *PatchTool) Run(ctx context.Context, m json.RawMessage) llm.ToolOut {
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700233 if p.clipboards == nil {
234 p.clipboards = make(map[string]string)
235 }
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700236 input, err := p.patchParse(m)
237 var output llm.ToolOut
238 if err != nil {
239 output = llm.ErrorToolOut(err)
240 } else {
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700241 output = p.patchRun(ctx, &input)
Josh Bleecher Snyderfcf75902025-07-30 16:37:44 -0700242 }
243 if p.Callback != nil {
244 return p.Callback(input, output)
245 }
246 return output
247}
248
249// patchParse parses the input message into a PatchInput structure.
250// It accepts a few different formats, because empirically,
251// LLMs sometimes generate slightly different JSON structures,
252// and we may as well accept such near misses.
253func (p *PatchTool) patchParse(m json.RawMessage) (PatchInput, error) {
254 var input PatchInput
255 originalErr := json.Unmarshal(m, &input)
256 if originalErr == nil {
257 return input, nil
258 }
259 var inputOne PatchInputOne
260 if err := json.Unmarshal(m, &inputOne); err == nil {
261 return PatchInput{Path: inputOne.Path, Patches: []PatchRequest{inputOne.Patches}}, nil
262 }
263 var inputOneString PatchInputOneString
264 if err := json.Unmarshal(m, &inputOneString); err == nil {
265 var onePatch PatchRequest
266 if err := json.Unmarshal([]byte(inputOneString.Patches), &onePatch); err == nil {
267 return PatchInput{Path: inputOneString.Path, Patches: []PatchRequest{onePatch}}, nil
268 }
269 var patches []PatchRequest
270 if err := json.Unmarshal([]byte(inputOneString.Patches), &patches); err == nil {
271 return PatchInput{Path: inputOneString.Path, Patches: patches}, nil
272 }
273 }
274 return PatchInput{}, fmt.Errorf("failed to unmarshal patch input: %w", originalErr)
275}
276
Josh Bleecher Snyder238c18f2025-06-30 22:26:54 +0000277// patchRun implements the guts of the patch tool.
278// It populates input from m.
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700279func (p *PatchTool) patchRun(ctx context.Context, input *PatchInput) llm.ToolOut {
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700280 path := input.Path
Earl Lee2e463fb2025-04-17 11:22:22 -0700281 if !filepath.IsAbs(input.Path) {
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700282 if p.Pwd == "" {
283 return llm.ErrorfToolOut("path %q is not absolute and no working directory is set", input.Path)
284 }
285 path = filepath.Join(p.Pwd, input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700286 }
Josh Bleecher Snyder136b66d2025-07-30 11:48:58 -0700287 input.Path = path
Earl Lee2e463fb2025-04-17 11:22:22 -0700288 if len(input.Patches) == 0 {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700289 return llm.ErrorToolOut(fmt.Errorf("no patches provided"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700290 }
291 // TODO: check whether the file is autogenerated, and if so, require a "force" flag to modify it.
292
293 orig, err := os.ReadFile(input.Path)
294 // If the file doesn't exist, we can still apply patches
295 // that don't require finding existing text.
296 switch {
297 case errors.Is(err, os.ErrNotExist):
298 for _, patch := range input.Patches {
299 switch patch.Operation {
300 case "prepend_bof", "append_eof", "overwrite":
301 default:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700302 return llm.ErrorfToolOut("file %q does not exist", input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700303 }
304 }
305 case err != nil:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700306 return llm.ErrorfToolOut("failed to read file %q: %w", input.Path, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700307 }
308
309 likelyGoFile := strings.HasSuffix(input.Path, ".go")
310
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000311 autogenerated := likelyGoFile && IsAutogeneratedGoFile(orig)
Earl Lee2e463fb2025-04-17 11:22:22 -0700312
313 origStr := string(orig)
314 // Process the patches "simultaneously", minimizing them along the way.
315 // Claude generates patches that interact with each other.
316 buf := editbuf.NewBuffer(orig)
317
318 // TODO: is it better to apply the patches that apply cleanly and report on the failures?
319 // or instead have it be all-or-nothing?
320 // For now, it is all-or-nothing.
321 // TODO: when the model gets into a "cannot apply patch" cycle of doom, how do we get it unstuck?
322 // Also: how do we detect that it's in a cycle?
323 var patchErr error
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700324
325 var clipboardsModified []string
326 updateToClipboard := func(patch PatchRequest, spec *patchkit.Spec) {
327 if patch.ToClipboard == "" {
328 return
329 }
330 // Update clipboard with the actual matched text
331 matchedOldText := origStr[spec.Off : spec.Off+spec.Len]
332 p.clipboards[patch.ToClipboard] = matchedOldText
333 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))
334 }
335
Earl Lee2e463fb2025-04-17 11:22:22 -0700336 for i, patch := range input.Patches {
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700337 // Process toClipboard first, so that copy works
338 if patch.ToClipboard != "" {
339 if patch.Operation != "replace" {
340 return llm.ErrorfToolOut("toClipboard (%s): can only be used with replace operation", patch.ToClipboard)
341 }
342 if patch.OldText == "" {
343 return llm.ErrorfToolOut("toClipboard (%s): oldText cannot be empty when using toClipboard", patch.ToClipboard)
344 }
345 p.clipboards[patch.ToClipboard] = patch.OldText
346 }
347
348 // Handle fromClipboard
349 newText := patch.NewText
350 if patch.FromClipboard != "" {
351 clipboardText, ok := p.clipboards[patch.FromClipboard]
352 if !ok {
353 return llm.ErrorfToolOut("fromClipboard (%s): no clipboard with that name", patch.FromClipboard)
354 }
355 newText = clipboardText
356 }
357
358 // Apply indentation adjustment if specified
359 if patch.Reindent != nil {
360 reindentedText, err := reindent(newText, patch.Reindent)
361 if err != nil {
362 return llm.ErrorfToolOut("reindent(%q -> %q): %w", patch.Reindent.Strip, patch.Reindent.Add, err)
363 }
364 newText = reindentedText
365 }
366
Earl Lee2e463fb2025-04-17 11:22:22 -0700367 switch patch.Operation {
368 case "prepend_bof":
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700369 buf.Insert(0, newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700370 case "append_eof":
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700371 buf.Insert(len(orig), newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700372 case "overwrite":
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700373 buf.Replace(0, len(orig), newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700374 case "replace":
375 if patch.OldText == "" {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700376 return llm.ErrorfToolOut("patch %d: oldText cannot be empty for %s operation", i, patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700377 }
378
379 // Attempt to apply the patch.
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700380 spec, count := patchkit.Unique(origStr, patch.OldText, newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700381 switch count {
382 case 0:
383 // no matches, maybe recoverable, continued below
384 case 1:
385 // exact match, apply
386 slog.DebugContext(ctx, "patch_applied", "method", "unique")
387 spec.ApplyToEditBuf(buf)
388 continue
389 case 2:
390 // multiple matches
391 patchErr = errors.Join(patchErr, fmt.Errorf("old text not unique:\n%s", patch.OldText))
Josh Bleecher Snyderdba25ee2025-07-30 19:40:22 -0700392 continue
Earl Lee2e463fb2025-04-17 11:22:22 -0700393 default:
Earl Lee2e463fb2025-04-17 11:22:22 -0700394 slog.ErrorContext(ctx, "unique returned unexpected count", "count", count)
395 patchErr = errors.Join(patchErr, fmt.Errorf("internal error"))
396 continue
397 }
398
399 // The following recovery mechanisms are heuristic.
400 // They aren't perfect, but they appear safe,
401 // and the cases they cover appear with some regularity.
402
403 // Try adjusting the whitespace prefix.
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700404 spec, ok := patchkit.UniqueDedent(origStr, patch.OldText, newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700405 if ok {
406 slog.DebugContext(ctx, "patch_applied", "method", "unique_dedent")
407 spec.ApplyToEditBuf(buf)
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700408 updateToClipboard(patch, spec)
Earl Lee2e463fb2025-04-17 11:22:22 -0700409 continue
410 }
411
412 // Try ignoring leading/trailing whitespace in a semantically safe way.
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700413 spec, ok = patchkit.UniqueInValidGo(origStr, patch.OldText, newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700414 if ok {
415 slog.DebugContext(ctx, "patch_applied", "method", "unique_in_valid_go")
416 spec.ApplyToEditBuf(buf)
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700417 updateToClipboard(patch, spec)
Earl Lee2e463fb2025-04-17 11:22:22 -0700418 continue
419 }
420
421 // Try ignoring semantically insignificant whitespace.
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700422 spec, ok = patchkit.UniqueGoTokens(origStr, patch.OldText, newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700423 if ok {
424 slog.DebugContext(ctx, "patch_applied", "method", "unique_go_tokens")
425 spec.ApplyToEditBuf(buf)
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700426 updateToClipboard(patch, spec)
Earl Lee2e463fb2025-04-17 11:22:22 -0700427 continue
428 }
429
430 // Try trimming the first line of the patch, if we can do so safely.
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700431 spec, ok = patchkit.UniqueTrim(origStr, patch.OldText, newText)
Earl Lee2e463fb2025-04-17 11:22:22 -0700432 if ok {
433 slog.DebugContext(ctx, "patch_applied", "method", "unique_trim")
434 spec.ApplyToEditBuf(buf)
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700435 // Do NOT call updateToClipboard here,
436 // because the trimmed text may vary significantly from the original text.
Earl Lee2e463fb2025-04-17 11:22:22 -0700437 continue
438 }
439
440 // No dice.
441 patchErr = errors.Join(patchErr, fmt.Errorf("old text not found:\n%s", patch.OldText))
442 continue
443 default:
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700444 return llm.ErrorfToolOut("unrecognized operation %q", patch.Operation)
Earl Lee2e463fb2025-04-17 11:22:22 -0700445 }
446 }
447
448 if patchErr != nil {
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700449 errorMsg := patchErr.Error()
450 for _, msg := range clipboardsModified {
451 errorMsg += "\n" + msg
452 }
453 return llm.ErrorToolOut(fmt.Errorf("%s", errorMsg))
Earl Lee2e463fb2025-04-17 11:22:22 -0700454 }
455
456 patched, err := buf.Bytes()
457 if err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700458 return llm.ErrorToolOut(err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700459 }
460 if err := os.MkdirAll(filepath.Dir(input.Path), 0o700); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700461 return llm.ErrorfToolOut("failed to create directory %q: %w", filepath.Dir(input.Path), err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700462 }
463 if err := os.WriteFile(input.Path, patched, 0o600); err != nil {
Josh Bleecher Snyder43b60b92025-07-21 14:57:10 -0700464 return llm.ErrorfToolOut("failed to write patched contents to file %q: %w", input.Path, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700465 }
466
467 response := new(strings.Builder)
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700468 fmt.Fprintf(response, "<patches_applied>all</patches_applied>\n")
469 for _, msg := range clipboardsModified {
470 fmt.Fprintln(response, msg)
471 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700472
Earl Lee2e463fb2025-04-17 11:22:22 -0700473 if autogenerated {
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700474 fmt.Fprintf(response, "<warning>%q appears to be autogenerated. Patches were applied anyway.</warning>\n", input.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700475 }
476
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -0700477 diff := generateUnifiedDiff(input.Path, string(orig), string(patched))
478
Earl Lee2e463fb2025-04-17 11:22:22 -0700479 // 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 -0700480 return llm.ToolOut{
481 LLMContent: llm.TextContent(response.String()),
482 Display: diff,
483 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700484}
485
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000486// IsAutogeneratedGoFile reports whether a Go file has markers indicating it was autogenerated.
487func IsAutogeneratedGoFile(buf []byte) bool {
Earl Lee2e463fb2025-04-17 11:22:22 -0700488 for _, sig := range autogeneratedSignals {
489 if bytes.Contains(buf, []byte(sig)) {
490 return true
491 }
492 }
493
494 // https://pkg.go.dev/cmd/go#hdr-Generate_Go_files_by_processing_source
495 // "This line must appear before the first non-comment, non-blank text in the file."
496 // Approximate that by looking for it at the top of the file, before the last of the imports.
497 // (Sometimes people put it after the package declaration, because of course they do.)
498 // At least in the imports region we know it's not part of their actual code;
499 // we don't want to ignore the generator (which also includes these strings!),
500 // just the generated code.
501 fset := token.NewFileSet()
502 f, err := parser.ParseFile(fset, "x.go", buf, parser.ImportsOnly|parser.ParseComments)
503 if err == nil {
504 for _, cg := range f.Comments {
505 t := strings.ToLower(cg.Text())
506 for _, sig := range autogeneratedHeaderSignals {
507 if strings.Contains(t, sig) {
508 return true
509 }
510 }
511 }
512 }
513
514 return false
515}
516
517// autogeneratedSignals are signals that a file is autogenerated, when present anywhere in the file.
518var autogeneratedSignals = [][]byte{
519 []byte("\nfunc bindataRead("), // pre-embed bindata packed file
520}
521
522// autogeneratedHeaderSignals are signals that a file is autogenerated, when present at the top of the file.
523var autogeneratedHeaderSignals = []string{
524 // canonical would be `(?m)^// Code generated .* DO NOT EDIT\.$`
525 // but people screw it up, a lot, so be more lenient
526 strings.ToLower("generate"),
527 strings.ToLower("DO NOT EDIT"),
528 strings.ToLower("export by"),
529}
Josh Bleecher Snyder3dd3e412025-07-22 20:32:03 -0700530
531func generateUnifiedDiff(filePath, original, patched string) string {
532 buf := new(strings.Builder)
533 err := diff.Text(filePath, filePath, original, patched, buf)
534 if err != nil {
535 return fmt.Sprintf("(diff generation failed: %v)\n", err)
536 }
537 return buf.String()
538}
Josh Bleecher Snyder7f18fb62025-07-30 18:12:29 -0700539
540// reindent applies indentation adjustments to text.
541func reindent(text string, adj *Reindent) (string, error) {
542 if adj == nil {
543 return text, nil
544 }
545
546 lines := strings.Split(text, "\n")
547
548 for i, line := range lines {
549 if line == "" {
550 continue
551 }
552 var ok bool
553 lines[i], ok = strings.CutPrefix(line, adj.Strip)
554 if !ok {
555 return "", fmt.Errorf("strip precondition failed: line %q does not start with %q", line, adj.Strip)
556 }
557 }
558
559 for i, line := range lines {
560 if line == "" {
561 continue
562 }
563 lines[i] = adj.Add + line
564 }
565
566 return strings.Join(lines, "\n"), nil
567}