| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 1 | package claudetool |
| 2 | |
| 3 | import ( |
| 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 Snyder | 3dd3e41 | 2025-07-22 20:32:03 -0700 | [diff] [blame] | 16 | "github.com/pkg/diff" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 17 | "sketch.dev/claudetool/editbuf" |
| 18 | "sketch.dev/claudetool/patchkit" |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 19 | "sketch.dev/llm" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 20 | ) |
| 21 | |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 22 | // PatchCallback defines the signature for patch tool callbacks. |
| 23 | // It runs after the patch tool has executed. |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 24 | // It receives the patch input and the tool output, |
| 25 | // and returns a new, possibly altered tool output. |
| 26 | type PatchCallback func(input PatchInput, output llm.ToolOut) llm.ToolOut |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 27 | |
| Josh Bleecher Snyder | 04f16a5 | 2025-07-30 11:46:25 -0700 | [diff] [blame] | 28 | // PatchTool specifies an llm.Tool for patching files. |
| Josh Bleecher Snyder | 534783d | 2025-07-29 08:17:37 -0700 | [diff] [blame] | 29 | // PatchTools are not concurrency-safe. |
| Josh Bleecher Snyder | 04f16a5 | 2025-07-30 11:46:25 -0700 | [diff] [blame] | 30 | type PatchTool struct { |
| 31 | Callback PatchCallback // may be nil |
| Josh Bleecher Snyder | 136b66d | 2025-07-30 11:48:58 -0700 | [diff] [blame] | 32 | // Pwd is the working directory for resolving relative paths |
| 33 | Pwd string |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 34 | // 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 Snyder | 04f16a5 | 2025-07-30 11:46:25 -0700 | [diff] [blame] | 40 | } |
| 41 | |
| 42 | // Tool returns an llm.Tool based on p. |
| 43 | func (p *PatchTool) Tool() *llm.Tool { |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 44 | description := PatchBaseDescription + PatchUsageNotes |
| 45 | schema := PatchStandardInputSchema |
| 46 | if p.ClipboardEnabled { |
| 47 | description = PatchBaseDescription + PatchClipboardDescription + PatchUsageNotes |
| 48 | schema = PatchClipboardInputSchema |
| 49 | } |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 50 | return &llm.Tool{ |
| 51 | Name: PatchName, |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 52 | Description: strings.TrimSpace(description), |
| 53 | InputSchema: llm.MustSchema(schema), |
| Josh Bleecher Snyder | 534783d | 2025-07-29 08:17:37 -0700 | [diff] [blame] | 54 | Run: p.Run, |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 55 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 56 | } |
| 57 | |
| 58 | const ( |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 59 | PatchName = "patch" |
| 60 | PatchBaseDescription = ` |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 61 | File modification tool for precise text edits. |
| 62 | |
| 63 | Operations: |
| Josh Bleecher Snyder | 534783d | 2025-07-29 08:17:37 -0700 | [diff] [blame] | 64 | - replace: Substitute unique text with new content |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 65 | - 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 Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 68 | ` |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 69 | |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 70 | PatchClipboardDescription = ` |
| 71 | Clipboard: |
| 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 | |
| 78 | Indentation 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 | |
| 83 | Recipes: |
| 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 91 | Usage 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 Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 97 | PatchStandardInputSchema = ` |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 98 | { |
| 99 | "type": "object", |
| 100 | "required": ["path", "patches"], |
| 101 | "properties": { |
| 102 | "path": { |
| 103 | "type": "string", |
| Josh Bleecher Snyder | 136b66d | 2025-07-30 11:48:58 -0700 | [diff] [blame] | 104 | "description": "Path to the file to patch" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 105 | }, |
| 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 Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 132 | |
| 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 190 | ) |
| 191 | |
| 192 | // TODO: maybe rename PatchRequest to PatchOperation or PatchSpec or PatchPart or just Patch? |
| 193 | |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 194 | // PatchInput represents the input structure for patch operations. |
| 195 | type PatchInput struct { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 196 | Path string `json:"path"` |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 197 | Patches []PatchRequest `json:"patches"` |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 198 | } |
| 199 | |
| Josh Bleecher Snyder | fcf7590 | 2025-07-30 16:37:44 -0700 | [diff] [blame] | 200 | // PatchInputOne is a simplified version of PatchInput for single patch operations. |
| 201 | type PatchInputOne struct { |
| 202 | Path string `json:"path"` |
| 203 | Patches PatchRequest `json:"patches"` |
| 204 | } |
| 205 | |
| 206 | type PatchInputOneString struct { |
| 207 | Path string `json:"path"` |
| 208 | Patches string `json:"patches"` // contains Patches as a JSON string 🤦 |
| 209 | } |
| 210 | |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 211 | // PatchRequest represents a single patch operation. |
| 212 | type PatchRequest struct { |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 213 | 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. |
| 222 | type 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 229 | } |
| 230 | |
| Josh Bleecher Snyder | fcf7590 | 2025-07-30 16:37:44 -0700 | [diff] [blame] | 231 | // Run implements the patch tool logic. |
| 232 | func (p *PatchTool) Run(ctx context.Context, m json.RawMessage) llm.ToolOut { |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 233 | if p.clipboards == nil { |
| 234 | p.clipboards = make(map[string]string) |
| 235 | } |
| Josh Bleecher Snyder | fcf7590 | 2025-07-30 16:37:44 -0700 | [diff] [blame] | 236 | input, err := p.patchParse(m) |
| 237 | var output llm.ToolOut |
| 238 | if err != nil { |
| 239 | output = llm.ErrorToolOut(err) |
| 240 | } else { |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 241 | output = p.patchRun(ctx, &input) |
| Josh Bleecher Snyder | fcf7590 | 2025-07-30 16:37:44 -0700 | [diff] [blame] | 242 | } |
| 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. |
| 253 | func (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 Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 277 | // patchRun implements the guts of the patch tool. |
| 278 | // It populates input from m. |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 279 | func (p *PatchTool) patchRun(ctx context.Context, input *PatchInput) llm.ToolOut { |
| Josh Bleecher Snyder | 136b66d | 2025-07-30 11:48:58 -0700 | [diff] [blame] | 280 | path := input.Path |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 281 | if !filepath.IsAbs(input.Path) { |
| Josh Bleecher Snyder | 136b66d | 2025-07-30 11:48:58 -0700 | [diff] [blame] | 282 | 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 286 | } |
| Josh Bleecher Snyder | 136b66d | 2025-07-30 11:48:58 -0700 | [diff] [blame] | 287 | input.Path = path |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 288 | if len(input.Patches) == 0 { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 289 | return llm.ErrorToolOut(fmt.Errorf("no patches provided")) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 290 | } |
| 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 Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 302 | return llm.ErrorfToolOut("file %q does not exist", input.Path) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 303 | } |
| 304 | } |
| 305 | case err != nil: |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 306 | return llm.ErrorfToolOut("failed to read file %q: %w", input.Path, err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 307 | } |
| 308 | |
| 309 | likelyGoFile := strings.HasSuffix(input.Path, ".go") |
| 310 | |
| Josh Bleecher Snyder | f4047bb | 2025-05-05 23:02:56 +0000 | [diff] [blame] | 311 | autogenerated := likelyGoFile && IsAutogeneratedGoFile(orig) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 312 | |
| 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 Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 324 | |
| 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 336 | for i, patch := range input.Patches { |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 337 | // 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 367 | switch patch.Operation { |
| 368 | case "prepend_bof": |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 369 | buf.Insert(0, newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 370 | case "append_eof": |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 371 | buf.Insert(len(orig), newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 372 | case "overwrite": |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 373 | buf.Replace(0, len(orig), newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 374 | case "replace": |
| 375 | if patch.OldText == "" { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 376 | return llm.ErrorfToolOut("patch %d: oldText cannot be empty for %s operation", i, patch.Operation) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 377 | } |
| 378 | |
| 379 | // Attempt to apply the patch. |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 380 | spec, count := patchkit.Unique(origStr, patch.OldText, newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 381 | 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 Snyder | dba25ee | 2025-07-30 19:40:22 -0700 | [diff] [blame] | 392 | continue |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 393 | default: |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 394 | 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 Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 404 | spec, ok := patchkit.UniqueDedent(origStr, patch.OldText, newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 405 | if ok { |
| 406 | slog.DebugContext(ctx, "patch_applied", "method", "unique_dedent") |
| 407 | spec.ApplyToEditBuf(buf) |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 408 | updateToClipboard(patch, spec) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 409 | continue |
| 410 | } |
| 411 | |
| 412 | // Try ignoring leading/trailing whitespace in a semantically safe way. |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 413 | spec, ok = patchkit.UniqueInValidGo(origStr, patch.OldText, newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 414 | if ok { |
| 415 | slog.DebugContext(ctx, "patch_applied", "method", "unique_in_valid_go") |
| 416 | spec.ApplyToEditBuf(buf) |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 417 | updateToClipboard(patch, spec) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 418 | continue |
| 419 | } |
| 420 | |
| 421 | // Try ignoring semantically insignificant whitespace. |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 422 | spec, ok = patchkit.UniqueGoTokens(origStr, patch.OldText, newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 423 | if ok { |
| 424 | slog.DebugContext(ctx, "patch_applied", "method", "unique_go_tokens") |
| 425 | spec.ApplyToEditBuf(buf) |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 426 | updateToClipboard(patch, spec) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 427 | continue |
| 428 | } |
| 429 | |
| 430 | // Try trimming the first line of the patch, if we can do so safely. |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 431 | spec, ok = patchkit.UniqueTrim(origStr, patch.OldText, newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 432 | if ok { |
| 433 | slog.DebugContext(ctx, "patch_applied", "method", "unique_trim") |
| 434 | spec.ApplyToEditBuf(buf) |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 435 | // Do NOT call updateToClipboard here, |
| 436 | // because the trimmed text may vary significantly from the original text. |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 437 | 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 Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 444 | return llm.ErrorfToolOut("unrecognized operation %q", patch.Operation) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 445 | } |
| 446 | } |
| 447 | |
| 448 | if patchErr != nil { |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 449 | errorMsg := patchErr.Error() |
| 450 | for _, msg := range clipboardsModified { |
| 451 | errorMsg += "\n" + msg |
| 452 | } |
| 453 | return llm.ErrorToolOut(fmt.Errorf("%s", errorMsg)) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 454 | } |
| 455 | |
| 456 | patched, err := buf.Bytes() |
| 457 | if err != nil { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 458 | return llm.ErrorToolOut(err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 459 | } |
| 460 | if err := os.MkdirAll(filepath.Dir(input.Path), 0o700); err != nil { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 461 | return llm.ErrorfToolOut("failed to create directory %q: %w", filepath.Dir(input.Path), err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 462 | } |
| 463 | if err := os.WriteFile(input.Path, patched, 0o600); err != nil { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 464 | return llm.ErrorfToolOut("failed to write patched contents to file %q: %w", input.Path, err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 465 | } |
| 466 | |
| 467 | response := new(strings.Builder) |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 468 | fmt.Fprintf(response, "<patches_applied>all</patches_applied>\n") |
| 469 | for _, msg := range clipboardsModified { |
| 470 | fmt.Fprintln(response, msg) |
| 471 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 472 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 473 | if autogenerated { |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 474 | fmt.Fprintf(response, "<warning>%q appears to be autogenerated. Patches were applied anyway.</warning>\n", input.Path) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 475 | } |
| 476 | |
| Josh Bleecher Snyder | 3dd3e41 | 2025-07-22 20:32:03 -0700 | [diff] [blame] | 477 | diff := generateUnifiedDiff(input.Path, string(orig), string(patched)) |
| 478 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 479 | // TODO: maybe report the patch result to the model, i.e. some/all of the new code after the patches and formatting. |
| Josh Bleecher Snyder | 3dd3e41 | 2025-07-22 20:32:03 -0700 | [diff] [blame] | 480 | return llm.ToolOut{ |
| 481 | LLMContent: llm.TextContent(response.String()), |
| 482 | Display: diff, |
| 483 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 484 | } |
| 485 | |
| Josh Bleecher Snyder | f4047bb | 2025-05-05 23:02:56 +0000 | [diff] [blame] | 486 | // IsAutogeneratedGoFile reports whether a Go file has markers indicating it was autogenerated. |
| 487 | func IsAutogeneratedGoFile(buf []byte) bool { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 488 | 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. |
| 518 | var 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. |
| 523 | var 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 Snyder | 3dd3e41 | 2025-07-22 20:32:03 -0700 | [diff] [blame] | 530 | |
| 531 | func 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 Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame^] | 539 | |
| 540 | // reindent applies indentation adjustments to text. |
| 541 | func 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 | } |