| 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 | 994e984 | 2025-07-30 20:26:47 -0700 | [diff] [blame] | 34 | // Simplified indicates whether to use the simplified input schema. |
| 35 | // Helpful for weaker models. |
| 36 | Simplified bool |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 37 | // ClipboardEnabled controls whether clipboard functionality is enabled. |
| Josh Bleecher Snyder | 994e984 | 2025-07-30 20:26:47 -0700 | [diff] [blame] | 38 | // Ignored if Simplified is true. |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 39 | // 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 Snyder | 04f16a5 | 2025-07-30 11:46:25 -0700 | [diff] [blame] | 44 | } |
| 45 | |
| 46 | // Tool returns an llm.Tool based on p. |
| 47 | func (p *PatchTool) Tool() *llm.Tool { |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 48 | description := PatchBaseDescription + PatchUsageNotes |
| 49 | schema := PatchStandardInputSchema |
| Josh Bleecher Snyder | 994e984 | 2025-07-30 20:26:47 -0700 | [diff] [blame] | 50 | switch { |
| 51 | case p.Simplified: |
| 52 | schema = PatchStandardSimplifiedSchema |
| 53 | case p.ClipboardEnabled: |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 54 | description = PatchBaseDescription + PatchClipboardDescription + PatchUsageNotes |
| 55 | schema = PatchClipboardInputSchema |
| 56 | } |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 57 | return &llm.Tool{ |
| 58 | Name: PatchName, |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 59 | Description: strings.TrimSpace(description), |
| 60 | InputSchema: llm.MustSchema(schema), |
| Josh Bleecher Snyder | 534783d | 2025-07-29 08:17:37 -0700 | [diff] [blame] | 61 | Run: p.Run, |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 62 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 63 | } |
| 64 | |
| 65 | const ( |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 66 | PatchName = "patch" |
| 67 | PatchBaseDescription = ` |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 68 | File modification tool for precise text edits. |
| 69 | |
| 70 | Operations: |
| Josh Bleecher Snyder | 534783d | 2025-07-29 08:17:37 -0700 | [diff] [blame] | 71 | - replace: Substitute unique text with new content |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 72 | - 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 Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 75 | ` |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 76 | |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 77 | PatchClipboardDescription = ` |
| 78 | Clipboard: |
| 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 | |
| 85 | Indentation 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 | |
| 90 | Recipes: |
| 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 98 | Usage 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 Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 104 | PatchStandardInputSchema = ` |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 105 | { |
| 106 | "type": "object", |
| 107 | "required": ["path", "patches"], |
| 108 | "properties": { |
| 109 | "path": { |
| 110 | "type": "string", |
| Josh Bleecher Snyder | 136b66d | 2025-07-30 11:48:58 -0700 | [diff] [blame] | 111 | "description": "Path to the file to patch" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 112 | }, |
| 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 Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 139 | |
| Josh Bleecher Snyder | 994e984 | 2025-07-30 20:26:47 -0700 | [diff] [blame] | 140 | 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 Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 170 | 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 227 | ) |
| 228 | |
| 229 | // TODO: maybe rename PatchRequest to PatchOperation or PatchSpec or PatchPart or just Patch? |
| 230 | |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 231 | // PatchInput represents the input structure for patch operations. |
| 232 | type PatchInput struct { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 233 | Path string `json:"path"` |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 234 | Patches []PatchRequest `json:"patches"` |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 235 | } |
| 236 | |
| Josh Bleecher Snyder | fcf7590 | 2025-07-30 16:37:44 -0700 | [diff] [blame] | 237 | // PatchInputOne is a simplified version of PatchInput for single patch operations. |
| 238 | type PatchInputOne struct { |
| Josh Bleecher Snyder | 994e984 | 2025-07-30 20:26:47 -0700 | [diff] [blame] | 239 | Path string `json:"path"` |
| 240 | Patches *PatchRequest `json:"patches"` |
| 241 | } |
| 242 | |
| 243 | // PatchInputOneSingular is PatchInputOne with a better name for the singular case. |
| 244 | type PatchInputOneSingular struct { |
| 245 | Path string `json:"path"` |
| 246 | Patch *PatchRequest `json:"patch"` |
| Josh Bleecher Snyder | fcf7590 | 2025-07-30 16:37:44 -0700 | [diff] [blame] | 247 | } |
| 248 | |
| 249 | type PatchInputOneString struct { |
| 250 | Path string `json:"path"` |
| 251 | Patches string `json:"patches"` // contains Patches as a JSON string 🤦 |
| 252 | } |
| 253 | |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 254 | // PatchRequest represents a single patch operation. |
| 255 | type PatchRequest struct { |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 256 | 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. |
| 265 | type 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 272 | } |
| 273 | |
| Josh Bleecher Snyder | fcf7590 | 2025-07-30 16:37:44 -0700 | [diff] [blame] | 274 | // Run implements the patch tool logic. |
| 275 | 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] | 276 | if p.clipboards == nil { |
| 277 | p.clipboards = make(map[string]string) |
| 278 | } |
| Josh Bleecher Snyder | fcf7590 | 2025-07-30 16:37:44 -0700 | [diff] [blame] | 279 | input, err := p.patchParse(m) |
| 280 | var output llm.ToolOut |
| 281 | if err != nil { |
| 282 | output = llm.ErrorToolOut(err) |
| 283 | } else { |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 284 | output = p.patchRun(ctx, &input) |
| Josh Bleecher Snyder | fcf7590 | 2025-07-30 16:37:44 -0700 | [diff] [blame] | 285 | } |
| 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. |
| 296 | func (p *PatchTool) patchParse(m json.RawMessage) (PatchInput, error) { |
| 297 | var input PatchInput |
| 298 | originalErr := json.Unmarshal(m, &input) |
| Josh Bleecher Snyder | 994e984 | 2025-07-30 20:26:47 -0700 | [diff] [blame] | 299 | if originalErr == nil && len(input.Patches) > 0 { |
| Josh Bleecher Snyder | fcf7590 | 2025-07-30 16:37:44 -0700 | [diff] [blame] | 300 | return input, nil |
| 301 | } |
| 302 | var inputOne PatchInputOne |
| Josh Bleecher Snyder | 994e984 | 2025-07-30 20:26:47 -0700 | [diff] [blame] | 303 | 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 Snyder | fcf7590 | 2025-07-30 16:37:44 -0700 | [diff] [blame] | 309 | } |
| 310 | var inputOneString PatchInputOneString |
| 311 | if err := json.Unmarshal(m, &inputOneString); err == nil { |
| 312 | var onePatch PatchRequest |
| Josh Bleecher Snyder | 994e984 | 2025-07-30 20:26:47 -0700 | [diff] [blame] | 313 | if err := json.Unmarshal([]byte(inputOneString.Patches), &onePatch); err == nil && onePatch.Operation != "" { |
| Josh Bleecher Snyder | fcf7590 | 2025-07-30 16:37:44 -0700 | [diff] [blame] | 314 | 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 Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 324 | // patchRun implements the guts of the patch tool. |
| 325 | // It populates input from m. |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 326 | func (p *PatchTool) patchRun(ctx context.Context, input *PatchInput) llm.ToolOut { |
| Josh Bleecher Snyder | 136b66d | 2025-07-30 11:48:58 -0700 | [diff] [blame] | 327 | path := input.Path |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 328 | if !filepath.IsAbs(input.Path) { |
| Josh Bleecher Snyder | 136b66d | 2025-07-30 11:48:58 -0700 | [diff] [blame] | 329 | 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 333 | } |
| Josh Bleecher Snyder | 136b66d | 2025-07-30 11:48:58 -0700 | [diff] [blame] | 334 | input.Path = path |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 335 | if len(input.Patches) == 0 { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 336 | return llm.ErrorToolOut(fmt.Errorf("no patches provided")) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 337 | } |
| 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 Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 349 | return llm.ErrorfToolOut("file %q does not exist", input.Path) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 350 | } |
| 351 | } |
| 352 | case err != nil: |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 353 | return llm.ErrorfToolOut("failed to read file %q: %w", input.Path, err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 354 | } |
| 355 | |
| 356 | likelyGoFile := strings.HasSuffix(input.Path, ".go") |
| 357 | |
| Josh Bleecher Snyder | f4047bb | 2025-05-05 23:02:56 +0000 | [diff] [blame] | 358 | autogenerated := likelyGoFile && IsAutogeneratedGoFile(orig) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 359 | |
| 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 Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 371 | |
| 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 383 | for i, patch := range input.Patches { |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 384 | // 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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 414 | switch patch.Operation { |
| 415 | case "prepend_bof": |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 416 | buf.Insert(0, newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 417 | case "append_eof": |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 418 | buf.Insert(len(orig), newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 419 | case "overwrite": |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 420 | buf.Replace(0, len(orig), newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 421 | case "replace": |
| 422 | if patch.OldText == "" { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 423 | 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] | 424 | } |
| 425 | |
| 426 | // Attempt to apply the patch. |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 427 | spec, count := patchkit.Unique(origStr, patch.OldText, newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 428 | 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 Snyder | dba25ee | 2025-07-30 19:40:22 -0700 | [diff] [blame] | 439 | continue |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 440 | default: |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 441 | 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 Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 451 | spec, ok := patchkit.UniqueDedent(origStr, patch.OldText, newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 452 | if ok { |
| 453 | slog.DebugContext(ctx, "patch_applied", "method", "unique_dedent") |
| 454 | spec.ApplyToEditBuf(buf) |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 455 | updateToClipboard(patch, spec) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 456 | continue |
| 457 | } |
| 458 | |
| 459 | // Try ignoring leading/trailing whitespace in a semantically safe way. |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 460 | spec, ok = patchkit.UniqueInValidGo(origStr, patch.OldText, newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 461 | if ok { |
| 462 | slog.DebugContext(ctx, "patch_applied", "method", "unique_in_valid_go") |
| 463 | spec.ApplyToEditBuf(buf) |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 464 | updateToClipboard(patch, spec) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 465 | continue |
| 466 | } |
| 467 | |
| 468 | // Try ignoring semantically insignificant whitespace. |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 469 | spec, ok = patchkit.UniqueGoTokens(origStr, patch.OldText, newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 470 | if ok { |
| 471 | slog.DebugContext(ctx, "patch_applied", "method", "unique_go_tokens") |
| 472 | spec.ApplyToEditBuf(buf) |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 473 | updateToClipboard(patch, spec) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 474 | continue |
| 475 | } |
| 476 | |
| 477 | // 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] | 478 | spec, ok = patchkit.UniqueTrim(origStr, patch.OldText, newText) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 479 | if ok { |
| 480 | slog.DebugContext(ctx, "patch_applied", "method", "unique_trim") |
| 481 | spec.ApplyToEditBuf(buf) |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 482 | // Do NOT call updateToClipboard here, |
| 483 | // because the trimmed text may vary significantly from the original text. |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 484 | 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 Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 491 | return llm.ErrorfToolOut("unrecognized operation %q", patch.Operation) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 492 | } |
| 493 | } |
| 494 | |
| 495 | if patchErr != nil { |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 496 | errorMsg := patchErr.Error() |
| 497 | for _, msg := range clipboardsModified { |
| 498 | errorMsg += "\n" + msg |
| 499 | } |
| 500 | return llm.ErrorToolOut(fmt.Errorf("%s", errorMsg)) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 501 | } |
| 502 | |
| 503 | patched, err := buf.Bytes() |
| 504 | if err != nil { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 505 | return llm.ErrorToolOut(err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 506 | } |
| 507 | if err := os.MkdirAll(filepath.Dir(input.Path), 0o700); err != nil { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 508 | 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] | 509 | } |
| 510 | if err := os.WriteFile(input.Path, patched, 0o600); err != nil { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 511 | 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] | 512 | } |
| 513 | |
| 514 | response := new(strings.Builder) |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 515 | fmt.Fprintf(response, "<patches_applied>all</patches_applied>\n") |
| 516 | for _, msg := range clipboardsModified { |
| 517 | fmt.Fprintln(response, msg) |
| 518 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 519 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 520 | if autogenerated { |
| Josh Bleecher Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 521 | 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] | 522 | } |
| 523 | |
| Josh Bleecher Snyder | 3dd3e41 | 2025-07-22 20:32:03 -0700 | [diff] [blame] | 524 | diff := generateUnifiedDiff(input.Path, string(orig), string(patched)) |
| 525 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 526 | // 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] | 527 | return llm.ToolOut{ |
| 528 | LLMContent: llm.TextContent(response.String()), |
| 529 | Display: diff, |
| 530 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 531 | } |
| 532 | |
| Josh Bleecher Snyder | f4047bb | 2025-05-05 23:02:56 +0000 | [diff] [blame] | 533 | // IsAutogeneratedGoFile reports whether a Go file has markers indicating it was autogenerated. |
| 534 | func IsAutogeneratedGoFile(buf []byte) bool { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 535 | 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. |
| 565 | var 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. |
| 570 | var 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 Snyder | 3dd3e41 | 2025-07-22 20:32:03 -0700 | [diff] [blame] | 577 | |
| 578 | func 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 Snyder | 7f18fb6 | 2025-07-30 18:12:29 -0700 | [diff] [blame] | 586 | |
| 587 | // reindent applies indentation adjustments to text. |
| 588 | func 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 | } |