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