1package tools
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "os"
9 "strings"
10
11 "github.com/bnema/zut/packages/agent/lsp"
12 "github.com/bnema/zut/packages/core"
13 "github.com/bnema/zut/packages/provider"
14)
15
16// EditTool applies one or more exact-match replacements to a file.
17type EditTool struct {
18 CWD string
19 Sandbox *Sandbox
20 LSP *lsp.Manager
21 LSPDiagnostics bool
22}
23
24type editOp struct {
25 OldText string `json:"oldText"`
26 NewText string `json:"newText"`
27}
28
29type editArgs struct {
30 Path string `json:"path"`
31 Edits []editOp `json:"edits"`
32}
33
34const editSchema = `{"type":"object","properties":{"path":{"type":"string","description":"File to modify, given as an absolute path or one relative to the working directory."},"edits":{"type":"array","description":"A set of non-overlapping substitutions, all located in the file content as it existed before this call.","items":{"type":"object","properties":{"oldText":{"type":"string","description":"A verbatim excerpt from the file being modified with enough surrounding text to identify exactly one location, without intersecting another edit."},"newText":{"type":"string","description":"Content that will replace the matched excerpt."}},"required":["oldText","newText"]}}},"required":["path","edits"]}`
35
36func (t *EditTool) Name() string { return "edit" }
37func (t *EditTool) Description() string {
38 return "Apply exact substitutions to an existing file. Inspect that file before editing and take every oldText directly from its current contents. Use a verbatim excerpt with enough surrounding text to identify exactly one location; choose write when replacing most or all of a file."
39}
40func (t *EditTool) Schema() json.RawMessage { return json.RawMessage(editSchema) }
41
42type editPlan struct {
43 path string
44 final []byte
45 result core.ToolResult
46}
47
48// Preview validates the edit against the current file and returns the exact
49// diff without writing anything. The confirmation UI shows this result before
50// the user decides whether Execute may apply it.
51func (t *EditTool) Preview(ctx context.Context, raw json.RawMessage) (core.ToolResult, error) {
52 plan, err := t.plan(raw)
53 if err != nil {
54 return core.ToolResult{}, err
55 }
56 return plan.result, nil
57}
58
59func (t *EditTool) Execute(ctx context.Context, raw json.RawMessage, progress func(string)) (core.ToolResult, error) {
60 plan, err := t.plan(raw)
61 if err != nil {
62 return core.ToolResult{}, err
63 }
64 if err := os.WriteFile(plan.path, plan.final, 0o644); err != nil {
65 return core.ToolResult{}, err
66 }
67 if t.LSPDiagnostics {
68 attachWriteDiagnostics(ctx, t.CWD, plan.path, t.LSP, &plan.result)
69 }
70 return plan.result, nil
71}
72
73func (t *EditTool) plan(raw json.RawMessage) (editPlan, error) {
74 var a editArgs
75 if err := json.Unmarshal(raw, &a); err != nil {
76 return editPlan{}, fmt.Errorf("invalid args: %w", err)
77 }
78 if a.Path == "" {
79 return editPlan{}, fmt.Errorf("path is required")
80 }
81 if len(a.Edits) == 0 {
82 return editPlan{}, fmt.Errorf("at least one edit is required")
83 }
84 path := resolvePath(t.CWD, a.Path)
85 if err := t.Sandbox.CheckWritePath(path); err != nil {
86 return editPlan{}, err
87 }
88
89 orig, err := os.ReadFile(path)
90 if err != nil {
91 return editPlan{}, err
92 }
93
94 // Detect BOM and line endings.
95 var bom []byte
96 if bytes.HasPrefix(orig, []byte{0xEF, 0xBB, 0xBF}) {
97 bom = orig[:3]
98 orig = orig[3:]
99 }
100 nl := detectLineEnding(orig)
101 // Normalize the file and edit operands to \n for matching and replacement.
102 body := normalizeLineEndings(string(orig))
103
104 // Validate all edits against the original content and build their spans in
105 // the same pass. This keeps validation and application anchored to the same
106 // match instead of locating each oldText a second time.
107 type span struct {
108 start, end int
109 replacement string
110 }
111 spans := make([]span, 0, len(a.Edits))
112 for i, e := range a.Edits {
113 oldText := normalizeLineEndings(e.OldText)
114 newText := normalizeLineEndings(e.NewText)
115 if oldText == "" {
116 return editPlan{}, fmt.Errorf("edit %d: oldText must not be empty", i+1)
117 }
118 if oldText == newText {
119 return editPlan{}, fmt.Errorf("edit %d: oldText equals newText", i+1)
120 }
121 matches := summarizeMatches(body, oldText)
122 if matches.count == 0 {
123 return editPlan{}, fmt.Errorf("edit %d: oldText not found in %s; inspect that file again and use a verbatim excerpt with matching spaces and line breaks", i+1, a.Path)
124 }
125 if matches.count > 1 {
126 return editPlan{}, fmt.Errorf("edit %d: oldText matches %d times (must be unique) in %s at %s; read %s with a bounded context window around those lines, then retry with a verbatim excerpt containing enough surrounding text to identify exactly one location", i+1, matches.count, a.Path, formatMatchLines(matches.lines, matches.count), a.Path)
127 }
128 spans = append(spans, span{
129 start: matches.start,
130 end: matches.start + len(oldText),
131 replacement: newText,
132 })
133 }
134
135 // Apply atomically (sorted by position so offsets stay valid as we splice).
136 // Check for overlaps.
137 for i := 0; i < len(spans); i++ {
138 for j := i + 1; j < len(spans); j++ {
139 if spans[i].start < spans[j].end && spans[j].start < spans[i].end {
140 return editPlan{}, fmt.Errorf("edits overlap; merge them into one edit")
141 }
142 }
143 }
144 // Sort ascending.
145 for i := 1; i < len(spans); i++ {
146 for j := i; j > 0 && spans[j-1].start > spans[j].start; j-- {
147 spans[j-1], spans[j] = spans[j], spans[j-1]
148 }
149 }
150 var out strings.Builder
151 prev := 0
152 for _, s := range spans {
153 out.WriteString(body[prev:s.start])
154 out.WriteString(s.replacement)
155 prev = s.end
156 }
157 out.WriteString(body[prev:])
158 newBody := out.String()
159
160 // Restore line endings.
161 if nl == "\r\n" {
162 newBody = strings.ReplaceAll(newBody, "\n", "\r\n")
163 }
164 final := append([]byte{}, bom...)
165 final = append(final, []byte(newBody)...)
166
167 diff := unifiedDiff(a.Path, string(orig), strings.ReplaceAll(newBody, "\r\n", "\n"))
168 // The tool-call header renders the path above the result, so the
169 // result body is just the context diff. Details carries metadata for
170 // programmatic consumers and confirmation previews.
171 result := core.ToolResult{
172 Content: []provider.Content{provider.TextBlock{Text: diff}},
173 Details: map[string]any{"path": path, "edits": len(a.Edits), "diff": diff},
174 }
175 return editPlan{path: path, final: final, result: result}, nil
176}
177
178const maxReportedMatchLines = 5
179
180type matchSummary struct {
181 count int
182 start int
183 lines []int
184}
185
186// summarizeMatches counts every possible match start, including overlaps,
187// while retaining only the line numbers useful for recovery guidance.
188func summarizeMatches(body, oldText string) matchSummary {
189 var summary matchSummary
190 for searchFrom := 0; searchFrom < len(body); {
191 relative := strings.Index(body[searchFrom:], oldText)
192 if relative < 0 {
193 break
194 }
195 start := searchFrom + relative
196 if summary.count == 0 {
197 summary.start = start
198 }
199 summary.count++
200 if len(summary.lines) < maxReportedMatchLines {
201 summary.lines = append(summary.lines, 1+strings.Count(body[:start], "\n"))
202 }
203 searchFrom = start + 1
204 }
205 return summary
206}
207
208func formatMatchLines(lines []int, count int) string {
209 parts := make([]string, len(lines))
210 for i, line := range lines {
211 parts[i] = fmt.Sprintf("%d", line)
212 }
213
214 var list string
215 switch len(parts) {
216 case 1:
217 list = parts[0]
218 case 2:
219 list = parts[0] + " and " + parts[1]
220 default:
221 list = strings.Join(parts[:len(parts)-1], ", ") + ", and " + parts[len(parts)-1]
222 }
223 if omitted := count - len(lines); omitted > 0 {
224 list += fmt.Sprintf(" (and %d more)", omitted)
225 }
226 return "lines " + list
227}
228
229func normalizeLineEndings(s string) string {
230 return strings.ReplaceAll(s, "\r\n", "\n")
231}
232
233func detectLineEnding(b []byte) string {
234 if bytes.Contains(b, []byte("\r\n")) {
235 return "\r\n"
236 }
237 return "\n"
238}
239
240// diffContextLines is the number of unchanged lines kept on each
241// side of an edit when rendering the diff. 3 is the git-diff
242// default and balances readability with transcript size.
243const diffContextLines = 3
244
245// unifiedDiff emits a context diff for the edit tool's result.
246//
247// Shape: each output row is either
248// - " <line>" unchanged context
249// - "-<line>" deletion (from a)
250// - "+<line>" addition (to b)
251// - "..." context break between hunks
252//
253// The legacy "--- name / +++ name" header is omitted because the
254// tool-call header above the result already shows the path. Only
255// lines within diffContextLines of a +/- row are kept; longer
256// runs of unchanged content collapse into a single "..." row so
257// a one-line edit in a thousand-line file produces a short
258// transcript.
259func unifiedDiff(name, a, b string) string {
260 if a == b {
261 return ""
262 }
263 aLines := strings.Split(a, "\n")
264 bLines := strings.Split(b, "\n")
265 ops := diffLines(aLines, bLines)
266
267 // Mark ops that sit within diffContextLines of any +/- op.
268 keep := make([]bool, len(ops))
269 for i, op := range ops {
270 if op.kind == '+' || op.kind == '-' {
271 keep[i] = true
272 for d := 1; d <= diffContextLines; d++ {
273 if i-d >= 0 {
274 keep[i-d] = true
275 }
276 if i+d < len(ops) {
277 keep[i+d] = true
278 }
279 }
280 }
281 }
282
283 var sb strings.Builder
284 prevKept := false
285 anyOutput := false
286 for i, op := range ops {
287 if !keep[i] {
288 if prevKept {
289 sb.WriteString("...\n")
290 prevKept = false
291 }
292 continue
293 }
294 if !prevKept && anyOutput {
295 sb.WriteString("...\n")
296 }
297 switch op.kind {
298 case ' ':
299 fmt.Fprintf(&sb, " %s\n", op.line)
300 case '-':
301 fmt.Fprintf(&sb, "-%s\n", op.line)
302 case '+':
303 fmt.Fprintf(&sb, "+%s\n", op.line)
304 }
305 prevKept = true
306 anyOutput = true
307 }
308 _ = name // header dropped; kept in signature for call-site stability
309 return sb.String()
310}
311
312type diffOp struct {
313 kind byte
314 line string
315}
316
317func diffLines(a, b []string) []diffOp {
318 // LCS table.
319 m, n := len(a), len(b)
320 dp := make([][]int, m+1)
321 for i := range dp {
322 dp[i] = make([]int, n+1)
323 }
324 for i := 0; i < m; i++ {
325 for j := 0; j < n; j++ {
326 if a[i] == b[j] {
327 dp[i+1][j+1] = dp[i][j] + 1
328 } else if dp[i+1][j] >= dp[i][j+1] {
329 dp[i+1][j+1] = dp[i+1][j]
330 } else {
331 dp[i+1][j+1] = dp[i][j+1]
332 }
333 }
334 }
335 // Backtrack.
336 var ops []diffOp
337 i, j := m, n
338 for i > 0 && j > 0 {
339 if a[i-1] == b[j-1] {
340 ops = append([]diffOp{{' ', a[i-1]}}, ops...)
341 i--
342 j--
343 } else if dp[i][j-1] >= dp[i-1][j] {
344 ops = append([]diffOp{{'+', b[j-1]}}, ops...)
345 j--
346 } else {
347 ops = append([]diffOp{{'-', a[i-1]}}, ops...)
348 i--
349 }
350 }
351 for i > 0 {
352 ops = append([]diffOp{{'-', a[i-1]}}, ops...)
353 i--
354 }
355 for j > 0 {
356 ops = append([]diffOp{{'+', b[j-1]}}, ops...)
357 j--
358 }
359 return ops
360}