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