Skip to main content

eclipse_core/
tools_patch.rs

1//! `patch` — an edit, not a rewrite.
2//!
3//! `write_file` replaces a whole file, which is fine for a file the agent is creating and a bad
4//! idea for one it is changing: the model has to reproduce every untouched line from memory, so
5//! a 200-line file with a one-line change costs 200 lines of output and carries 200 chances to
6//! drop something. `patch` takes the text to replace and the text to put there instead, and
7//! writes back only if it found exactly one place that matches.
8//!
9//! Two rules make it safe to hand a model:
10//!
11//! - **Ambiguity is an error, not a guess.** If the old text appears twice the call fails and
12//!   says where. `replace_all` is the caller saying it meant every one; nothing does that
13//!   implicitly.
14//! - **The file is written only when a match was found.** A patch that cannot find its text
15//!   leaves the file exactly as it was, so there is no half-applied edit to recover from.
16//!
17//! The one relaxation: when the text is not found verbatim it is looked for line by line with
18//! indentation and trailing spaces ignored, because a model re-indenting a block it quoted from
19//! a read is the commonest near miss. The text that lands in the file is the caller's own, and
20//! the result says the match was relaxed — a wrong-but-similar edit should be visible, not
21//! silent.
22//!
23//! [`hits`] and [`splice`] are `pub(crate)` because `skill_manage patch` is the same operation
24//! over a skill's file: one matcher, so the two tools cannot end up forgiving different things.
25
26use crate::tools::{replace_file, str_arg, Tool, ToolError, WriteFile};
27use async_trait::async_trait;
28use serde_json::{json, Value};
29
30/// Files larger than this are refused. A patch reads the whole file to find its text, and a
31/// multi-megabyte file is a sign the caller wanted something else.
32pub(crate) const MAX_BYTES: usize = 4 * 1024 * 1024;
33
34/// Lines of the file to show on either side of an edit.
35const CONTEXT: usize = 2;
36
37/// How many separate edits a `replace_all` reports in full before summarising the rest.
38const MAX_HUNKS: usize = 3;
39
40pub struct Patch {
41    /// The `write_file` path rules: workspace-confined, plus the scripts directory.
42    files: WriteFile,
43}
44
45impl Patch {
46    pub fn new(files: WriteFile) -> Self {
47        Self { files }
48    }
49}
50
51/// One place the old text was found.
52pub(crate) struct Hit {
53    pub(crate) start: usize,
54    pub(crate) end: usize,
55    /// 1-based line the match starts on.
56    pub(crate) line: usize,
57    /// Found by comparing trimmed lines rather than bytes.
58    pub(crate) relaxed: bool,
59}
60
61/// How many lines a piece of text occupies, counting a trailing partial line.
62pub(crate) fn line_count(text: &str) -> usize {
63    if text.is_empty() {
64        0
65    } else {
66        text.split_inclusive('\n').count()
67    }
68}
69
70/// Every byte-exact occurrence of `needle`.
71fn exact_occurrences(hay: &str, needle: &str) -> Vec<Hit> {
72    hay.match_indices(needle)
73        .map(|(start, _)| Hit {
74            start,
75            end: start + needle.len(),
76            line: hay[..start].matches('\n').count() + 1,
77            relaxed: false,
78        })
79        .collect()
80}
81
82/// Every occurrence where the lines match once indentation and trailing spaces are ignored.
83///
84/// The span is cut to the needle's own shape: a needle that does not end in a newline does not
85/// swallow the file's newline either, so a relaxed match can neither join nor split lines.
86fn relaxed_occurrences(hay: &str, needle: &str) -> Vec<Hit> {
87    let lines: Vec<&str> = hay.split_inclusive('\n').collect();
88    let wanted: Vec<&str> = needle.split_inclusive('\n').collect();
89    if wanted.is_empty() || lines.len() < wanted.len() {
90        return Vec::new();
91    }
92    // Byte offset of the start of every line, plus one past the end.
93    let mut starts = Vec::with_capacity(lines.len() + 1);
94    let mut at = 0;
95    for line in &lines {
96        starts.push(at);
97        at += line.len();
98    }
99    starts.push(at);
100
101    let mut hits = Vec::new();
102    for i in 0..=(lines.len() - wanted.len()) {
103        if !lines[i..i + wanted.len()]
104            .iter()
105            .zip(&wanted)
106            .all(|(a, b)| a.trim() == b.trim())
107        {
108            continue;
109        }
110        let start = starts[i];
111        // `#367`: two candidate offsets can overlap — a needle of repeated lines matches again
112        // *inside* the match before it (`x\nx\n` in `x\nx\nx\n` hits at 0 and at the second line).
113        // `splice` walks the hits with a single cursor, so an overlapping start is a slice with its
114        // ends the wrong way round: `before[8..4]`, a panic out of the tool call and into the turn.
115        // Leftmost-first, the way `str::matches` is: a match that begins inside the previous one is
116        // not a second match.
117        if hits.last().is_some_and(|last: &Hit| start < last.end) {
118            continue;
119        }
120        let mut end = starts[i + wanted.len()];
121        if !needle.ends_with('\n') && end > start && hay.as_bytes()[end - 1] == b'\n' {
122            end -= 1;
123        }
124        hits.push(Hit {
125            start,
126            end,
127            line: i + 1,
128            relaxed: true,
129        });
130    }
131    hits
132}
133
134/// Where `needle` is in `hay`: exact matches first, the indentation-blind search only when there
135/// are none. Two callers, one answer — `patch` and `skill_manage patch`.
136pub(crate) fn hits(hay: &str, needle: &str) -> Vec<Hit> {
137    let exact = exact_occurrences(hay, needle);
138    if exact.is_empty() {
139        relaxed_occurrences(hay, needle)
140    } else {
141        exact
142    }
143}
144
145/// Apply `hits` in order, one cursor walk rather than N rewrites — every offset is in terms of
146/// the original text, so nothing needs re-finding.
147pub(crate) fn splice(before: &str, hits: &[Hit], replacement: &str) -> String {
148    let mut out = String::with_capacity(before.len() + replacement.len() * hits.len());
149    let mut cursor = 0;
150    for hit in hits {
151        debug_assert!(
152            hit.start >= cursor,
153            "an edit at {} begins inside the one before it (cursor {}) — `#367`",
154            hit.start,
155            cursor
156        );
157        out.push_str(&before[cursor..hit.start]);
158        out.push_str(replacement);
159        cursor = hit.end;
160    }
161    out.push_str(&before[cursor..]);
162    out
163}
164
165fn with_newline(line: &str) -> String {
166    if line.ends_with('\n') {
167        line.to_string()
168    } else {
169        format!("{line}\n")
170    }
171}
172
173/// One unified hunk per edit: the lines a person would look at to see that it landed.
174///
175/// Not a general diff — the edit is known, so there is nothing to compute. A match that starts
176/// or ends mid-line shows that partial line as the `-`/`+` line rather than pretending to be a
177/// whole-line change.
178fn render_diff(before: &str, hits: &[Hit], replacement: &str) -> String {
179    let lines: Vec<&str> = before.split_inclusive('\n').collect();
180    let shown = hits.len().min(MAX_HUNKS);
181    let mut out = String::new();
182
183    for hit in &hits[..shown] {
184        let old = &before[hit.start..hit.end];
185        let old_n = line_count(old).max(1);
186        let new_n = line_count(replacement);
187        let head = (hit.line - 1).saturating_sub(CONTEXT);
188        let tail = (hit.line - 1 + old_n + CONTEXT).min(lines.len());
189
190        out.push_str(&format!(
191            "@@ -{},{} +{},{} @@\n",
192            head + 1,
193            tail - head,
194            head + 1,
195            (tail - head) - old_n + new_n
196        ));
197        for line in &lines[head..hit.line - 1] {
198            out.push(' ');
199            out.push_str(&with_newline(line));
200        }
201        for line in old.split_inclusive('\n') {
202            out.push('-');
203            out.push_str(&with_newline(line));
204        }
205        for line in replacement.split_inclusive('\n') {
206            out.push('+');
207            out.push_str(&with_newline(line));
208        }
209        for line in &lines[(hit.line - 1 + old_n).min(lines.len())..tail] {
210            out.push(' ');
211            out.push_str(&with_newline(line));
212        }
213    }
214    if hits.len() > shown {
215        out.push_str(&format!("… {} more edit(s)\n", hits.len() - shown));
216    }
217    out
218}
219
220#[async_trait]
221impl Tool for Patch {
222    fn name(&self) -> &str {
223        "patch"
224    }
225
226    fn description(&self) -> &str {
227        "Replace one piece of a text file in place. `old_string` must occur exactly once — pass \
228         enough of the surrounding lines to be unique — or set `replace_all`. Returns a small \
229         unified diff. Indentation and trailing spaces are forgiven when nothing matches \
230         verbatim, and the result says so when that happens. The file must already exist: use \
231         `write_file` to create one."
232    }
233
234    fn parameters(&self) -> Value {
235        json!({"type":"object","properties":{
236            "path":{"type":"string","description":"Path relative to the workspace, or an absolute path inside the scripts directory"},
237            "old_string":{"type":"string","description":"The text to replace, copied exactly. Long enough to be unique."},
238            "new_string":{"type":"string","description":"What to put there instead. Empty deletes the text."},
239            "replace_all":{"type":"boolean","description":"Replace every occurrence instead of requiring exactly one. Default false."}
240        },"required":["path","old_string","new_string"]})
241    }
242
243    fn describe_call(&self, args: &Value) -> String {
244        let path = args["path"].as_str().unwrap_or("?");
245        let old = args["old_string"].as_str().unwrap_or("");
246        let new = args["new_string"].as_str().unwrap_or("");
247        format!(
248            "patch {path}: {} line(s) → {} line(s){}",
249            line_count(old).max(1),
250            line_count(new),
251            if args["replace_all"].as_bool().unwrap_or(false) {
252                ", every occurrence"
253            } else {
254                ""
255            }
256        )
257    }
258
259    async fn call(&self, args: Value) -> Result<String, ToolError> {
260        let path_arg = str_arg(&args, "path")?;
261        let old = str_arg(&args, "old_string")?;
262        let new = str_arg(&args, "new_string")?;
263        let replace_all = args["replace_all"].as_bool().unwrap_or(false);
264
265        if old.is_empty() {
266            return Err(ToolError::InvalidArgs(
267                "`old_string` is empty; there is nothing to find".into(),
268            ));
269        }
270        if old == new {
271            return Err(ToolError::InvalidArgs(
272                "`old_string` and `new_string` are the same; the file would not change".into(),
273            ));
274        }
275
276        let path = self.files.resolve(path_arg)?;
277        let bytes = tokio::fs::read(&path).await.map_err(|e| match e.kind() {
278            std::io::ErrorKind::NotFound => ToolError::Failed(format!(
279                "{}: no such file. `patch` edits a file that exists; use `write_file` to create one",
280                path.display()
281            )),
282            _ => ToolError::Failed(format!("{}: {e}", path.display())),
283        })?;
284        if bytes.len() > MAX_BYTES {
285            return Err(ToolError::Failed(format!(
286                "{}: {} bytes, over the {MAX_BYTES}-byte limit for `patch`",
287                path.display(),
288                bytes.len()
289            )));
290        }
291        let before = String::from_utf8(bytes)
292            .map_err(|_| ToolError::Failed(format!("{}: not valid UTF-8", path.display())))?;
293
294        let found = hits(&before, old);
295        if found.is_empty() {
296            // The commonest failure is the right block with a wrong first line, so point at
297            // where that first line does appear.
298            let first = old.lines().next().unwrap_or("").trim().to_string();
299            let near: Vec<String> = before
300                .lines()
301                .enumerate()
302                .filter(|(_, line)| !first.is_empty() && line.trim() == first)
303                .map(|(i, _)| (i + 1).to_string())
304                .take(5)
305                .collect();
306            let hint = if near.is_empty() {
307                String::new()
308            } else {
309                format!(
310                    " Its first line is at line {} — the rest of `old_string` differs from what \
311                     is there.",
312                    near.join(", ")
313                )
314            };
315            return Err(ToolError::Failed(format!(
316                "`old_string` not found in {}. Read the file and copy the text exactly.{hint}",
317                path.display()
318            )));
319        }
320        if found.len() > 1 && !replace_all {
321            let where_: Vec<String> = found.iter().map(|h| h.line.to_string()).collect();
322            return Err(ToolError::Failed(format!(
323                "`old_string` appears {} times in {} (lines {}). Include more of the surrounding \
324                 text to say which one, or pass `replace_all` to change all of them.",
325                found.len(),
326                path.display(),
327                where_.join(", ")
328            )));
329        }
330
331        let after = splice(&before, &found, new);
332        replace_file(&path, &after)?;
333
334        let relaxed = found.iter().any(|h| h.relaxed);
335        Ok(format!(
336            "patched {} — {} edit(s), {} line(s) → {} line(s) each{}.\n{}",
337            path.display(),
338            found.len(),
339            line_count(old).max(1),
340            line_count(new),
341            if relaxed {
342                ", matched ignoring indentation and trailing spaces"
343            } else {
344                ""
345            },
346            render_diff(&before, &found, new)
347        ))
348    }
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    fn tool(dir: &std::path::Path) -> Patch {
356        Patch::new(WriteFile::new(dir.to_path_buf(), Some(dir.join("scripts"))))
357    }
358
359    async fn write(dir: &std::path::Path, name: &str, text: &str) -> std::path::PathBuf {
360        let path = dir.join(name);
361        tokio::fs::write(&path, text).await.unwrap();
362        path
363    }
364
365    async fn contents(dir: &std::path::Path, name: &str) -> String {
366        tokio::fs::read_to_string(dir.join(name)).await.unwrap()
367    }
368
369    #[tokio::test]
370    async fn a_unique_patch_replaces_just_that_text() {
371        let dir = tempfile::tempdir().unwrap();
372        write(dir.path(), "a.txt", "one\ntwo\nthree\n").await;
373        let out = tool(dir.path())
374            .call(json!({"path": "a.txt", "old_string": "two", "new_string": "2"}))
375            .await
376            .unwrap();
377        assert!(out.contains("1 edit"), "{out}");
378        assert_eq!(contents(dir.path(), "a.txt").await, "one\n2\nthree\n");
379    }
380
381    #[tokio::test]
382    async fn an_ambiguous_patch_changes_nothing_and_names_the_lines() {
383        let dir = tempfile::tempdir().unwrap();
384        let before = "x = 1\ny = 2\nx = 1\n";
385        write(dir.path(), "a.txt", before).await;
386        let err = tool(dir.path())
387            .call(json!({"path": "a.txt", "old_string": "x = 1", "new_string": "x = 9"}))
388            .await
389            .unwrap_err();
390        assert!(err.to_string().contains("appears 2 times"), "{err}");
391        assert!(err.to_string().contains("lines 1, 3"), "{err}");
392        assert_eq!(
393            contents(dir.path(), "a.txt").await,
394            before,
395            "an ambiguous patch is not a guess"
396        );
397    }
398
399    #[tokio::test]
400    async fn replace_all_changes_every_occurrence() {
401        let dir = tempfile::tempdir().unwrap();
402        write(dir.path(), "a.txt", "x = 1\ny = 2\nx = 1\n").await;
403        let out = tool(dir.path())
404            .call(
405                json!({"path": "a.txt", "old_string": "x = 1", "new_string": "x = 9",
406                         "replace_all": true}),
407            )
408            .await
409            .unwrap();
410        assert!(out.contains("2 edit(s)"), "{out}");
411        assert_eq!(contents(dir.path(), "a.txt").await, "x = 9\ny = 2\nx = 9\n");
412    }
413
414    /// `#367`: a needle of repeated lines matches at offsets that overlap each other, and
415    /// `replace_all` spliced them with one cursor — `before[8..4]`, which is a panic out of a tool
416    /// call and into the turn. The scan is leftmost-first now, the way `str::matches` is.
417    #[tokio::test]
418    async fn replace_all_does_not_slice_inside_its_own_last_match() {
419        let dir = tempfile::tempdir().unwrap();
420        write(dir.path(), "a.txt", "  x\n  x\n  x\n").await;
421        let out = tool(dir.path())
422            .call(
423                json!({"path": "a.txt", "old_string": "x\nx\n", "new_string": "y\n",
424                         "replace_all": true}),
425            )
426            .await
427            .expect("a repeated needle is a match, not a panic");
428        assert!(out.contains("1 edit(s)"), "{out}");
429        assert_eq!(
430            contents(dir.path(), "a.txt").await,
431            "y\n  x\n",
432            "the two lines it matched, and the third left alone"
433        );
434    }
435
436    #[tokio::test]
437    async fn text_that_is_not_there_is_an_error_and_leaves_the_file_alone() {
438        let dir = tempfile::tempdir().unwrap();
439        let before = "fn main() {\n    println!(\"hi\");\n}\n";
440        write(dir.path(), "a.txt", before).await;
441        let err = tool(dir.path())
442            .call(json!({"path": "a.txt", "old_string": "println!(\"bye\")", "new_string": "x"}))
443            .await
444            .unwrap_err();
445        assert!(err.to_string().contains("not found"), "{err}");
446        assert!(
447            !err.to_string().contains("Its first line"),
448            "no hint when the first line is not there either: {err}"
449        );
450        assert_eq!(contents(dir.path(), "a.txt").await, before);
451    }
452
453    #[tokio::test]
454    async fn a_near_miss_points_at_the_line_its_first_line_is_on() {
455        let dir = tempfile::tempdir().unwrap();
456        write(dir.path(), "a.txt", "a\nb\nc\n").await;
457        let err = tool(dir.path())
458            .call(json!({"path": "a.txt", "old_string": "b\nc\nzzz", "new_string": "x"}))
459            .await
460            .unwrap_err();
461        assert!(err.to_string().contains("first line is at line 2"), "{err}");
462    }
463
464    #[tokio::test]
465    async fn different_indentation_is_forgiven_and_the_result_says_so() {
466        let dir = tempfile::tempdir().unwrap();
467        write(dir.path(), "a.txt", "fn f() {\n    let x = 1;\n}\n").await;
468        // A tab where the file has four spaces: not a substring, so this is the relaxed path.
469        let out = tool(dir.path())
470            .call(json!({"path": "a.txt",
471                         "old_string": "\tlet x = 1;\n}",
472                         "new_string": "    let x = 2;\n}"}))
473            .await
474            .unwrap();
475        assert!(out.contains("ignoring indentation"), "{out}");
476        assert_eq!(
477            contents(dir.path(), "a.txt").await,
478            "fn f() {\n    let x = 2;\n}\n"
479        );
480    }
481
482    #[tokio::test]
483    async fn a_relaxed_match_does_not_swallow_the_line_ending() {
484        // The needle has no trailing newline, so the file's must survive: a relaxed match that
485        // took it would join two lines.
486        let dir = tempfile::tempdir().unwrap();
487        write(dir.path(), "a.txt", "first\nsecond\n").await;
488        tool(dir.path())
489            .call(json!({"path": "a.txt", "old_string": "  second  ", "new_string": "SECOND"}))
490            .await
491            .unwrap();
492        assert_eq!(contents(dir.path(), "a.txt").await, "first\nSECOND\n");
493    }
494
495    #[tokio::test]
496    async fn an_empty_new_string_deletes_the_text() {
497        let dir = tempfile::tempdir().unwrap();
498        write(dir.path(), "a.txt", "keep\ndrop\nkeep2\n").await;
499        tool(dir.path())
500            .call(json!({"path": "a.txt", "old_string": "drop\n", "new_string": ""}))
501            .await
502            .unwrap();
503        assert_eq!(contents(dir.path(), "a.txt").await, "keep\nkeep2\n");
504    }
505
506    #[tokio::test]
507    async fn a_missing_file_says_to_use_write_file() {
508        let dir = tempfile::tempdir().unwrap();
509        let err = tool(dir.path())
510            .call(json!({"path": "nope.txt", "old_string": "a", "new_string": "b"}))
511            .await
512            .unwrap_err();
513        assert!(err.to_string().contains("write_file"), "{err}");
514    }
515
516    #[tokio::test]
517    async fn a_patch_cannot_reach_outside_the_workspace() {
518        let dir = tempfile::tempdir().unwrap();
519        let err = tool(dir.path())
520            .call(json!({"path": "../../etc/passwd", "old_string": "a", "new_string": "b"}))
521            .await
522            .unwrap_err();
523        assert!(err.to_string().contains("outside the workspace"), "{err}");
524    }
525
526    #[tokio::test]
527    async fn a_patch_to_a_script_in_the_scripts_directory_is_allowed() {
528        let dir = tempfile::tempdir().unwrap();
529        tokio::fs::create_dir_all(dir.path().join("scripts"))
530            .await
531            .unwrap();
532        write(&dir.path().join("scripts"), "run.sh", "echo one\n").await;
533        let path = dir.path().join("scripts/run.sh");
534        tool(dir.path())
535            .call(json!({"path": path.to_str().unwrap(), "old_string": "one", "new_string": "two"}))
536            .await
537            .unwrap();
538        assert_eq!(
539            contents(&dir.path().join("scripts"), "run.sh").await,
540            "echo two\n"
541        );
542    }
543
544    #[tokio::test]
545    async fn an_empty_or_unchanged_edit_is_refused_before_the_file_is_read() {
546        let dir = tempfile::tempdir().unwrap();
547        let t = tool(dir.path());
548        let empty = t
549            .call(json!({"path": "a.txt", "old_string": "", "new_string": "x"}))
550            .await
551            .unwrap_err();
552        assert!(empty.to_string().contains("nothing to find"), "{empty}");
553        let same = t
554            .call(json!({"path": "a.txt", "old_string": "x", "new_string": "x"}))
555            .await
556            .unwrap_err();
557        assert!(same.to_string().contains("would not change"), "{same}");
558    }
559
560    #[test]
561    fn the_diff_shows_the_old_line_under_a_minus_and_the_new_under_a_plus() {
562        let before = "a\nb\nc\nd\n";
563        let found = hits(before, "c\n");
564        let diff = render_diff(before, &found, "C\n");
565        assert!(diff.contains("@@ -1,4 +1,4 @@"), "{diff}");
566        assert!(diff.contains("-c\n"), "{diff}");
567        assert!(diff.contains("+C\n"), "{diff}");
568        assert!(diff.contains(" b\n"), "{diff}");
569        assert!(diff.contains(" d\n"), "{diff}");
570    }
571
572    #[test]
573    fn an_edit_in_the_middle_of_a_line_is_shown_as_that_partial_line() {
574        let before = "let x = 1;\n";
575        let found = hits(before, "1");
576        let diff = render_diff(before, &found, "2");
577        assert!(diff.contains("-1\n"), "{diff}");
578        assert!(diff.contains("+2\n"), "{diff}");
579        // The untouched rest of the line is not invented as context.
580        assert!(!diff.contains("let x"), "{diff}");
581    }
582}