| 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 | |
| 28 | // Patch creates a patch tool. The callback may be nil. |
| 29 | func Patch(callback PatchCallback) *llm.Tool { |
| 30 | return &llm.Tool{ |
| 31 | Name: PatchName, |
| 32 | Description: strings.TrimSpace(PatchDescription), |
| 33 | InputSchema: llm.MustSchema(PatchInputSchema), |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 34 | Run: func(ctx context.Context, m json.RawMessage) llm.ToolOut { |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 35 | var input PatchInput |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 36 | output := patchRun(ctx, m, &input) |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 37 | if callback != nil { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 38 | return callback(input, output) |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 39 | } |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 40 | return output |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 41 | }, |
| 42 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 43 | } |
| 44 | |
| 45 | const ( |
| 46 | PatchName = "patch" |
| 47 | PatchDescription = ` |
| 48 | File modification tool for precise text edits. |
| 49 | |
| 50 | Operations: |
| 51 | - replace: Substitute text with new content |
| 52 | - append_eof: Append new text at the end of the file |
| 53 | - prepend_bof: Insert new text at the beginning of the file |
| 54 | - overwrite: Replace the entire file with new content (automatically creates the file) |
| 55 | |
| 56 | Usage notes: |
| 57 | - All inputs are interpreted literally (no automatic newline or whitespace handling) |
| 58 | - For replace operations, oldText must appear EXACTLY ONCE in the file |
| 59 | ` |
| 60 | |
| 61 | // If you modify this, update the termui template for prettier rendering. |
| 62 | PatchInputSchema = ` |
| 63 | { |
| 64 | "type": "object", |
| 65 | "required": ["path", "patches"], |
| 66 | "properties": { |
| 67 | "path": { |
| 68 | "type": "string", |
| 69 | "description": "Absolute path to the file to patch" |
| 70 | }, |
| 71 | "patches": { |
| 72 | "type": "array", |
| 73 | "description": "List of patch requests to apply", |
| 74 | "items": { |
| 75 | "type": "object", |
| 76 | "required": ["operation", "newText"], |
| 77 | "properties": { |
| 78 | "operation": { |
| 79 | "type": "string", |
| 80 | "enum": ["replace", "append_eof", "prepend_bof", "overwrite"], |
| 81 | "description": "Type of operation to perform" |
| 82 | }, |
| 83 | "oldText": { |
| 84 | "type": "string", |
| 85 | "description": "Text to locate for the operation (must be unique in file, required for replace)" |
| 86 | }, |
| 87 | "newText": { |
| 88 | "type": "string", |
| 89 | "description": "The new text to use (empty for deletions)" |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | ` |
| 97 | ) |
| 98 | |
| 99 | // TODO: maybe rename PatchRequest to PatchOperation or PatchSpec or PatchPart or just Patch? |
| 100 | |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 101 | // PatchInput represents the input structure for patch operations. |
| 102 | type PatchInput struct { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 103 | Path string `json:"path"` |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 104 | Patches []PatchRequest `json:"patches"` |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 105 | } |
| 106 | |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 107 | // PatchRequest represents a single patch operation. |
| 108 | type PatchRequest struct { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 109 | Operation string `json:"operation"` |
| 110 | OldText string `json:"oldText,omitempty"` |
| 111 | NewText string `json:"newText,omitempty"` |
| 112 | } |
| 113 | |
| Josh Bleecher Snyder | 238c18f | 2025-06-30 22:26:54 +0000 | [diff] [blame] | 114 | // patchRun implements the guts of the patch tool. |
| 115 | // It populates input from m. |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 116 | func patchRun(ctx context.Context, m json.RawMessage, input *PatchInput) llm.ToolOut { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 117 | if err := json.Unmarshal(m, &input); err != nil { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 118 | return llm.ErrorfToolOut("failed to unmarshal user_patch input: %w", err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 119 | } |
| 120 | |
| 121 | // Validate the input |
| 122 | if !filepath.IsAbs(input.Path) { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 123 | return llm.ErrorfToolOut("path %q is not absolute", input.Path) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 124 | } |
| 125 | if len(input.Patches) == 0 { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 126 | return llm.ErrorToolOut(fmt.Errorf("no patches provided")) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 127 | } |
| 128 | // TODO: check whether the file is autogenerated, and if so, require a "force" flag to modify it. |
| 129 | |
| 130 | orig, err := os.ReadFile(input.Path) |
| 131 | // If the file doesn't exist, we can still apply patches |
| 132 | // that don't require finding existing text. |
| 133 | switch { |
| 134 | case errors.Is(err, os.ErrNotExist): |
| 135 | for _, patch := range input.Patches { |
| 136 | switch patch.Operation { |
| 137 | case "prepend_bof", "append_eof", "overwrite": |
| 138 | default: |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 139 | return llm.ErrorfToolOut("file %q does not exist", input.Path) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 140 | } |
| 141 | } |
| 142 | case err != nil: |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 143 | return llm.ErrorfToolOut("failed to read file %q: %w", input.Path, err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 144 | } |
| 145 | |
| 146 | likelyGoFile := strings.HasSuffix(input.Path, ".go") |
| 147 | |
| Josh Bleecher Snyder | f4047bb | 2025-05-05 23:02:56 +0000 | [diff] [blame] | 148 | autogenerated := likelyGoFile && IsAutogeneratedGoFile(orig) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 149 | parsed := likelyGoFile && parseGo(orig) != nil |
| 150 | |
| 151 | origStr := string(orig) |
| 152 | // Process the patches "simultaneously", minimizing them along the way. |
| 153 | // Claude generates patches that interact with each other. |
| 154 | buf := editbuf.NewBuffer(orig) |
| 155 | |
| 156 | // TODO: is it better to apply the patches that apply cleanly and report on the failures? |
| 157 | // or instead have it be all-or-nothing? |
| 158 | // For now, it is all-or-nothing. |
| 159 | // TODO: when the model gets into a "cannot apply patch" cycle of doom, how do we get it unstuck? |
| 160 | // Also: how do we detect that it's in a cycle? |
| 161 | var patchErr error |
| 162 | for i, patch := range input.Patches { |
| 163 | switch patch.Operation { |
| 164 | case "prepend_bof": |
| 165 | buf.Insert(0, patch.NewText) |
| 166 | case "append_eof": |
| 167 | buf.Insert(len(orig), patch.NewText) |
| 168 | case "overwrite": |
| 169 | buf.Replace(0, len(orig), patch.NewText) |
| 170 | case "replace": |
| 171 | if patch.OldText == "" { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 172 | 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] | 173 | } |
| 174 | |
| 175 | // Attempt to apply the patch. |
| 176 | spec, count := patchkit.Unique(origStr, patch.OldText, patch.NewText) |
| 177 | switch count { |
| 178 | case 0: |
| 179 | // no matches, maybe recoverable, continued below |
| 180 | case 1: |
| 181 | // exact match, apply |
| 182 | slog.DebugContext(ctx, "patch_applied", "method", "unique") |
| 183 | spec.ApplyToEditBuf(buf) |
| 184 | continue |
| 185 | case 2: |
| 186 | // multiple matches |
| 187 | patchErr = errors.Join(patchErr, fmt.Errorf("old text not unique:\n%s", patch.OldText)) |
| 188 | default: |
| 189 | // TODO: return an error instead of using agentPatch |
| 190 | slog.ErrorContext(ctx, "unique returned unexpected count", "count", count) |
| 191 | patchErr = errors.Join(patchErr, fmt.Errorf("internal error")) |
| 192 | continue |
| 193 | } |
| 194 | |
| 195 | // The following recovery mechanisms are heuristic. |
| 196 | // They aren't perfect, but they appear safe, |
| 197 | // and the cases they cover appear with some regularity. |
| 198 | |
| 199 | // Try adjusting the whitespace prefix. |
| 200 | spec, ok := patchkit.UniqueDedent(origStr, patch.OldText, patch.NewText) |
| 201 | if ok { |
| 202 | slog.DebugContext(ctx, "patch_applied", "method", "unique_dedent") |
| 203 | spec.ApplyToEditBuf(buf) |
| 204 | continue |
| 205 | } |
| 206 | |
| 207 | // Try ignoring leading/trailing whitespace in a semantically safe way. |
| 208 | spec, ok = patchkit.UniqueInValidGo(origStr, patch.OldText, patch.NewText) |
| 209 | if ok { |
| 210 | slog.DebugContext(ctx, "patch_applied", "method", "unique_in_valid_go") |
| 211 | spec.ApplyToEditBuf(buf) |
| 212 | continue |
| 213 | } |
| 214 | |
| 215 | // Try ignoring semantically insignificant whitespace. |
| 216 | spec, ok = patchkit.UniqueGoTokens(origStr, patch.OldText, patch.NewText) |
| 217 | if ok { |
| 218 | slog.DebugContext(ctx, "patch_applied", "method", "unique_go_tokens") |
| 219 | spec.ApplyToEditBuf(buf) |
| 220 | continue |
| 221 | } |
| 222 | |
| 223 | // Try trimming the first line of the patch, if we can do so safely. |
| 224 | spec, ok = patchkit.UniqueTrim(origStr, patch.OldText, patch.NewText) |
| 225 | if ok { |
| 226 | slog.DebugContext(ctx, "patch_applied", "method", "unique_trim") |
| 227 | spec.ApplyToEditBuf(buf) |
| 228 | continue |
| 229 | } |
| 230 | |
| 231 | // No dice. |
| 232 | patchErr = errors.Join(patchErr, fmt.Errorf("old text not found:\n%s", patch.OldText)) |
| 233 | continue |
| 234 | default: |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 235 | return llm.ErrorfToolOut("unrecognized operation %q", patch.Operation) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 236 | } |
| 237 | } |
| 238 | |
| 239 | if patchErr != nil { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 240 | return llm.ErrorToolOut(patchErr) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 241 | } |
| 242 | |
| 243 | patched, err := buf.Bytes() |
| 244 | if err != nil { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 245 | return llm.ErrorToolOut(err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 246 | } |
| 247 | if err := os.MkdirAll(filepath.Dir(input.Path), 0o700); err != nil { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 248 | 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] | 249 | } |
| 250 | if err := os.WriteFile(input.Path, patched, 0o600); err != nil { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 251 | 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] | 252 | } |
| 253 | |
| 254 | response := new(strings.Builder) |
| 255 | fmt.Fprintf(response, "- Applied all patches\n") |
| 256 | |
| 257 | if parsed { |
| 258 | parseErr := parseGo(patched) |
| 259 | if parseErr != nil { |
| Josh Bleecher Snyder | 43b60b9 | 2025-07-21 14:57:10 -0700 | [diff] [blame] | 260 | return llm.ErrorfToolOut("after applying all patches, the file no longer parses:\n%w", parseErr) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 261 | } |
| 262 | } |
| 263 | |
| 264 | if autogenerated { |
| 265 | fmt.Fprintf(response, "- WARNING: %q appears to be autogenerated. Patches were applied anyway.\n", input.Path) |
| 266 | } |
| 267 | |
| Josh Bleecher Snyder | 3dd3e41 | 2025-07-22 20:32:03 -0700 | [diff] [blame^] | 268 | diff := generateUnifiedDiff(input.Path, string(orig), string(patched)) |
| 269 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 270 | // 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^] | 271 | return llm.ToolOut{ |
| 272 | LLMContent: llm.TextContent(response.String()), |
| 273 | Display: diff, |
| 274 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 275 | } |
| 276 | |
| 277 | func parseGo(buf []byte) error { |
| 278 | fset := token.NewFileSet() |
| 279 | _, err := parser.ParseFile(fset, "", buf, parser.SkipObjectResolution) |
| 280 | return err |
| 281 | } |
| 282 | |
| Josh Bleecher Snyder | f4047bb | 2025-05-05 23:02:56 +0000 | [diff] [blame] | 283 | // IsAutogeneratedGoFile reports whether a Go file has markers indicating it was autogenerated. |
| 284 | func IsAutogeneratedGoFile(buf []byte) bool { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 285 | for _, sig := range autogeneratedSignals { |
| 286 | if bytes.Contains(buf, []byte(sig)) { |
| 287 | return true |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | // https://pkg.go.dev/cmd/go#hdr-Generate_Go_files_by_processing_source |
| 292 | // "This line must appear before the first non-comment, non-blank text in the file." |
| 293 | // Approximate that by looking for it at the top of the file, before the last of the imports. |
| 294 | // (Sometimes people put it after the package declaration, because of course they do.) |
| 295 | // At least in the imports region we know it's not part of their actual code; |
| 296 | // we don't want to ignore the generator (which also includes these strings!), |
| 297 | // just the generated code. |
| 298 | fset := token.NewFileSet() |
| 299 | f, err := parser.ParseFile(fset, "x.go", buf, parser.ImportsOnly|parser.ParseComments) |
| 300 | if err == nil { |
| 301 | for _, cg := range f.Comments { |
| 302 | t := strings.ToLower(cg.Text()) |
| 303 | for _, sig := range autogeneratedHeaderSignals { |
| 304 | if strings.Contains(t, sig) { |
| 305 | return true |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | return false |
| 312 | } |
| 313 | |
| 314 | // autogeneratedSignals are signals that a file is autogenerated, when present anywhere in the file. |
| 315 | var autogeneratedSignals = [][]byte{ |
| 316 | []byte("\nfunc bindataRead("), // pre-embed bindata packed file |
| 317 | } |
| 318 | |
| 319 | // autogeneratedHeaderSignals are signals that a file is autogenerated, when present at the top of the file. |
| 320 | var autogeneratedHeaderSignals = []string{ |
| 321 | // canonical would be `(?m)^// Code generated .* DO NOT EDIT\.$` |
| 322 | // but people screw it up, a lot, so be more lenient |
| 323 | strings.ToLower("generate"), |
| 324 | strings.ToLower("DO NOT EDIT"), |
| 325 | strings.ToLower("export by"), |
| 326 | } |
| Josh Bleecher Snyder | 3dd3e41 | 2025-07-22 20:32:03 -0700 | [diff] [blame^] | 327 | |
| 328 | func generateUnifiedDiff(filePath, original, patched string) string { |
| 329 | buf := new(strings.Builder) |
| 330 | err := diff.Text(filePath, filePath, original, patched, buf) |
| 331 | if err != nil { |
| 332 | return fmt.Sprintf("(diff generation failed: %v)\n", err) |
| 333 | } |
| 334 | return buf.String() |
| 335 | } |