eclipse-core 0.13.2

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! `patch` — an edit, not a rewrite.
//!
//! `write_file` replaces a whole file, which is fine for a file the agent is creating and a bad
//! idea for one it is changing: the model has to reproduce every untouched line from memory, so
//! a 200-line file with a one-line change costs 200 lines of output and carries 200 chances to
//! drop something. `patch` takes the text to replace and the text to put there instead, and
//! writes back only if it found exactly one place that matches.
//!
//! Two rules make it safe to hand a model:
//!
//! - **Ambiguity is an error, not a guess.** If the old text appears twice the call fails and
//!   says where. `replace_all` is the caller saying it meant every one; nothing does that
//!   implicitly.
//! - **The file is written only when a match was found.** A patch that cannot find its text
//!   leaves the file exactly as it was, so there is no half-applied edit to recover from.
//!
//! The one relaxation: when the text is not found verbatim it is looked for line by line with
//! indentation and trailing spaces ignored, because a model re-indenting a block it quoted from
//! a read is the commonest near miss. The text that lands in the file is the caller's own, and
//! the result says the match was relaxed — a wrong-but-similar edit should be visible, not
//! silent.
//!
//! [`hits`] and [`splice`] are `pub(crate)` because `skill_manage patch` is the same operation
//! over a skill's file: one matcher, so the two tools cannot end up forgiving different things.

use crate::tools::{replace_file, str_arg, Tool, ToolError, WriteFile};
use async_trait::async_trait;
use serde_json::{json, Value};

/// Files larger than this are refused. A patch reads the whole file to find its text, and a
/// multi-megabyte file is a sign the caller wanted something else.
pub(crate) const MAX_BYTES: usize = 4 * 1024 * 1024;

/// Lines of the file to show on either side of an edit.
const CONTEXT: usize = 2;

/// How many separate edits a `replace_all` reports in full before summarising the rest.
const MAX_HUNKS: usize = 3;

pub struct Patch {
    /// The `write_file` path rules: workspace-confined, plus the scripts directory.
    files: WriteFile,
}

impl Patch {
    pub fn new(files: WriteFile) -> Self {
        Self { files }
    }
}

/// One place the old text was found.
pub(crate) struct Hit {
    pub(crate) start: usize,
    pub(crate) end: usize,
    /// 1-based line the match starts on.
    pub(crate) line: usize,
    /// Found by comparing trimmed lines rather than bytes.
    pub(crate) relaxed: bool,
}

/// How many lines a piece of text occupies, counting a trailing partial line.
pub(crate) fn line_count(text: &str) -> usize {
    if text.is_empty() {
        0
    } else {
        text.split_inclusive('\n').count()
    }
}

/// Every byte-exact occurrence of `needle`.
fn exact_occurrences(hay: &str, needle: &str) -> Vec<Hit> {
    hay.match_indices(needle)
        .map(|(start, _)| Hit {
            start,
            end: start + needle.len(),
            line: hay[..start].matches('\n').count() + 1,
            relaxed: false,
        })
        .collect()
}

/// Every occurrence where the lines match once indentation and trailing spaces are ignored.
///
/// The span is cut to the needle's own shape: a needle that does not end in a newline does not
/// swallow the file's newline either, so a relaxed match can neither join nor split lines.
fn relaxed_occurrences(hay: &str, needle: &str) -> Vec<Hit> {
    let lines: Vec<&str> = hay.split_inclusive('\n').collect();
    let wanted: Vec<&str> = needle.split_inclusive('\n').collect();
    if wanted.is_empty() || lines.len() < wanted.len() {
        return Vec::new();
    }
    // Byte offset of the start of every line, plus one past the end.
    let mut starts = Vec::with_capacity(lines.len() + 1);
    let mut at = 0;
    for line in &lines {
        starts.push(at);
        at += line.len();
    }
    starts.push(at);

    let mut hits = Vec::new();
    for i in 0..=(lines.len() - wanted.len()) {
        if !lines[i..i + wanted.len()]
            .iter()
            .zip(&wanted)
            .all(|(a, b)| a.trim() == b.trim())
        {
            continue;
        }
        let start = starts[i];
        // `#367`: two candidate offsets can overlap — a needle of repeated lines matches again
        // *inside* the match before it (`x\nx\n` in `x\nx\nx\n` hits at 0 and at the second line).
        // `splice` walks the hits with a single cursor, so an overlapping start is a slice with its
        // ends the wrong way round: `before[8..4]`, a panic out of the tool call and into the turn.
        // Leftmost-first, the way `str::matches` is: a match that begins inside the previous one is
        // not a second match.
        if hits.last().is_some_and(|last: &Hit| start < last.end) {
            continue;
        }
        let mut end = starts[i + wanted.len()];
        if !needle.ends_with('\n') && end > start && hay.as_bytes()[end - 1] == b'\n' {
            end -= 1;
        }
        hits.push(Hit {
            start,
            end,
            line: i + 1,
            relaxed: true,
        });
    }
    hits
}

/// Where `needle` is in `hay`: exact matches first, the indentation-blind search only when there
/// are none. Two callers, one answer — `patch` and `skill_manage patch`.
pub(crate) fn hits(hay: &str, needle: &str) -> Vec<Hit> {
    let exact = exact_occurrences(hay, needle);
    if exact.is_empty() {
        relaxed_occurrences(hay, needle)
    } else {
        exact
    }
}

/// Apply `hits` in order, one cursor walk rather than N rewrites — every offset is in terms of
/// the original text, so nothing needs re-finding.
pub(crate) fn splice(before: &str, hits: &[Hit], replacement: &str) -> String {
    let mut out = String::with_capacity(before.len() + replacement.len() * hits.len());
    let mut cursor = 0;
    for hit in hits {
        debug_assert!(
            hit.start >= cursor,
            "an edit at {} begins inside the one before it (cursor {}) — `#367`",
            hit.start,
            cursor
        );
        out.push_str(&before[cursor..hit.start]);
        out.push_str(replacement);
        cursor = hit.end;
    }
    out.push_str(&before[cursor..]);
    out
}

fn with_newline(line: &str) -> String {
    if line.ends_with('\n') {
        line.to_string()
    } else {
        format!("{line}\n")
    }
}

/// One unified hunk per edit: the lines a person would look at to see that it landed.
///
/// Not a general diff — the edit is known, so there is nothing to compute. A match that starts
/// or ends mid-line shows that partial line as the `-`/`+` line rather than pretending to be a
/// whole-line change.
fn render_diff(before: &str, hits: &[Hit], replacement: &str) -> String {
    let lines: Vec<&str> = before.split_inclusive('\n').collect();
    let shown = hits.len().min(MAX_HUNKS);
    let mut out = String::new();

    for hit in &hits[..shown] {
        let old = &before[hit.start..hit.end];
        let old_n = line_count(old).max(1);
        let new_n = line_count(replacement);
        let head = (hit.line - 1).saturating_sub(CONTEXT);
        let tail = (hit.line - 1 + old_n + CONTEXT).min(lines.len());

        out.push_str(&format!(
            "@@ -{},{} +{},{} @@\n",
            head + 1,
            tail - head,
            head + 1,
            (tail - head) - old_n + new_n
        ));
        for line in &lines[head..hit.line - 1] {
            out.push(' ');
            out.push_str(&with_newline(line));
        }
        for line in old.split_inclusive('\n') {
            out.push('-');
            out.push_str(&with_newline(line));
        }
        for line in replacement.split_inclusive('\n') {
            out.push('+');
            out.push_str(&with_newline(line));
        }
        for line in &lines[(hit.line - 1 + old_n).min(lines.len())..tail] {
            out.push(' ');
            out.push_str(&with_newline(line));
        }
    }
    if hits.len() > shown {
        out.push_str(&format!("… {} more edit(s)\n", hits.len() - shown));
    }
    out
}

#[async_trait]
impl Tool for Patch {
    fn name(&self) -> &str {
        "patch"
    }

    fn description(&self) -> &str {
        "Replace one piece of a text file in place. `old_string` must occur exactly once — pass \
         enough of the surrounding lines to be unique — or set `replace_all`. Returns a small \
         unified diff. Indentation and trailing spaces are forgiven when nothing matches \
         verbatim, and the result says so when that happens. The file must already exist: use \
         `write_file` to create one."
    }

    fn parameters(&self) -> Value {
        json!({"type":"object","properties":{
            "path":{"type":"string","description":"Path relative to the workspace, or an absolute path inside the scripts directory"},
            "old_string":{"type":"string","description":"The text to replace, copied exactly. Long enough to be unique."},
            "new_string":{"type":"string","description":"What to put there instead. Empty deletes the text."},
            "replace_all":{"type":"boolean","description":"Replace every occurrence instead of requiring exactly one. Default false."}
        },"required":["path","old_string","new_string"]})
    }

    fn describe_call(&self, args: &Value) -> String {
        let path = args["path"].as_str().unwrap_or("?");
        let old = args["old_string"].as_str().unwrap_or("");
        let new = args["new_string"].as_str().unwrap_or("");
        format!(
            "patch {path}: {} line(s) → {} line(s){}",
            line_count(old).max(1),
            line_count(new),
            if args["replace_all"].as_bool().unwrap_or(false) {
                ", every occurrence"
            } else {
                ""
            }
        )
    }

    async fn call(&self, args: Value) -> Result<String, ToolError> {
        let path_arg = str_arg(&args, "path")?;
        let old = str_arg(&args, "old_string")?;
        let new = str_arg(&args, "new_string")?;
        let replace_all = args["replace_all"].as_bool().unwrap_or(false);

        if old.is_empty() {
            return Err(ToolError::InvalidArgs(
                "`old_string` is empty; there is nothing to find".into(),
            ));
        }
        if old == new {
            return Err(ToolError::InvalidArgs(
                "`old_string` and `new_string` are the same; the file would not change".into(),
            ));
        }

        let path = self.files.resolve(path_arg)?;
        let bytes = tokio::fs::read(&path).await.map_err(|e| match e.kind() {
            std::io::ErrorKind::NotFound => ToolError::Failed(format!(
                "{}: no such file. `patch` edits a file that exists; use `write_file` to create one",
                path.display()
            )),
            _ => ToolError::Failed(format!("{}: {e}", path.display())),
        })?;
        if bytes.len() > MAX_BYTES {
            return Err(ToolError::Failed(format!(
                "{}: {} bytes, over the {MAX_BYTES}-byte limit for `patch`",
                path.display(),
                bytes.len()
            )));
        }
        let before = String::from_utf8(bytes)
            .map_err(|_| ToolError::Failed(format!("{}: not valid UTF-8", path.display())))?;

        let found = hits(&before, old);
        if found.is_empty() {
            // The commonest failure is the right block with a wrong first line, so point at
            // where that first line does appear.
            let first = old.lines().next().unwrap_or("").trim().to_string();
            let near: Vec<String> = before
                .lines()
                .enumerate()
                .filter(|(_, line)| !first.is_empty() && line.trim() == first)
                .map(|(i, _)| (i + 1).to_string())
                .take(5)
                .collect();
            let hint = if near.is_empty() {
                String::new()
            } else {
                format!(
                    " Its first line is at line {} — the rest of `old_string` differs from what \
                     is there.",
                    near.join(", ")
                )
            };
            return Err(ToolError::Failed(format!(
                "`old_string` not found in {}. Read the file and copy the text exactly.{hint}",
                path.display()
            )));
        }
        if found.len() > 1 && !replace_all {
            let where_: Vec<String> = found.iter().map(|h| h.line.to_string()).collect();
            return Err(ToolError::Failed(format!(
                "`old_string` appears {} times in {} (lines {}). Include more of the surrounding \
                 text to say which one, or pass `replace_all` to change all of them.",
                found.len(),
                path.display(),
                where_.join(", ")
            )));
        }

        let after = splice(&before, &found, new);
        replace_file(&path, &after)?;

        let relaxed = found.iter().any(|h| h.relaxed);
        Ok(format!(
            "patched {} — {} edit(s), {} line(s) → {} line(s) each{}.\n{}",
            path.display(),
            found.len(),
            line_count(old).max(1),
            line_count(new),
            if relaxed {
                ", matched ignoring indentation and trailing spaces"
            } else {
                ""
            },
            render_diff(&before, &found, new)
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tool(dir: &std::path::Path) -> Patch {
        Patch::new(WriteFile::new(dir.to_path_buf(), Some(dir.join("scripts"))))
    }

    async fn write(dir: &std::path::Path, name: &str, text: &str) -> std::path::PathBuf {
        let path = dir.join(name);
        tokio::fs::write(&path, text).await.unwrap();
        path
    }

    async fn contents(dir: &std::path::Path, name: &str) -> String {
        tokio::fs::read_to_string(dir.join(name)).await.unwrap()
    }

    #[tokio::test]
    async fn a_unique_patch_replaces_just_that_text() {
        let dir = tempfile::tempdir().unwrap();
        write(dir.path(), "a.txt", "one\ntwo\nthree\n").await;
        let out = tool(dir.path())
            .call(json!({"path": "a.txt", "old_string": "two", "new_string": "2"}))
            .await
            .unwrap();
        assert!(out.contains("1 edit"), "{out}");
        assert_eq!(contents(dir.path(), "a.txt").await, "one\n2\nthree\n");
    }

    #[tokio::test]
    async fn an_ambiguous_patch_changes_nothing_and_names_the_lines() {
        let dir = tempfile::tempdir().unwrap();
        let before = "x = 1\ny = 2\nx = 1\n";
        write(dir.path(), "a.txt", before).await;
        let err = tool(dir.path())
            .call(json!({"path": "a.txt", "old_string": "x = 1", "new_string": "x = 9"}))
            .await
            .unwrap_err();
        assert!(err.to_string().contains("appears 2 times"), "{err}");
        assert!(err.to_string().contains("lines 1, 3"), "{err}");
        assert_eq!(
            contents(dir.path(), "a.txt").await,
            before,
            "an ambiguous patch is not a guess"
        );
    }

    #[tokio::test]
    async fn replace_all_changes_every_occurrence() {
        let dir = tempfile::tempdir().unwrap();
        write(dir.path(), "a.txt", "x = 1\ny = 2\nx = 1\n").await;
        let out = tool(dir.path())
            .call(
                json!({"path": "a.txt", "old_string": "x = 1", "new_string": "x = 9",
                         "replace_all": true}),
            )
            .await
            .unwrap();
        assert!(out.contains("2 edit(s)"), "{out}");
        assert_eq!(contents(dir.path(), "a.txt").await, "x = 9\ny = 2\nx = 9\n");
    }

    /// `#367`: a needle of repeated lines matches at offsets that overlap each other, and
    /// `replace_all` spliced them with one cursor — `before[8..4]`, which is a panic out of a tool
    /// call and into the turn. The scan is leftmost-first now, the way `str::matches` is.
    #[tokio::test]
    async fn replace_all_does_not_slice_inside_its_own_last_match() {
        let dir = tempfile::tempdir().unwrap();
        write(dir.path(), "a.txt", "  x\n  x\n  x\n").await;
        let out = tool(dir.path())
            .call(
                json!({"path": "a.txt", "old_string": "x\nx\n", "new_string": "y\n",
                         "replace_all": true}),
            )
            .await
            .expect("a repeated needle is a match, not a panic");
        assert!(out.contains("1 edit(s)"), "{out}");
        assert_eq!(
            contents(dir.path(), "a.txt").await,
            "y\n  x\n",
            "the two lines it matched, and the third left alone"
        );
    }

    #[tokio::test]
    async fn text_that_is_not_there_is_an_error_and_leaves_the_file_alone() {
        let dir = tempfile::tempdir().unwrap();
        let before = "fn main() {\n    println!(\"hi\");\n}\n";
        write(dir.path(), "a.txt", before).await;
        let err = tool(dir.path())
            .call(json!({"path": "a.txt", "old_string": "println!(\"bye\")", "new_string": "x"}))
            .await
            .unwrap_err();
        assert!(err.to_string().contains("not found"), "{err}");
        assert!(
            !err.to_string().contains("Its first line"),
            "no hint when the first line is not there either: {err}"
        );
        assert_eq!(contents(dir.path(), "a.txt").await, before);
    }

    #[tokio::test]
    async fn a_near_miss_points_at_the_line_its_first_line_is_on() {
        let dir = tempfile::tempdir().unwrap();
        write(dir.path(), "a.txt", "a\nb\nc\n").await;
        let err = tool(dir.path())
            .call(json!({"path": "a.txt", "old_string": "b\nc\nzzz", "new_string": "x"}))
            .await
            .unwrap_err();
        assert!(err.to_string().contains("first line is at line 2"), "{err}");
    }

    #[tokio::test]
    async fn different_indentation_is_forgiven_and_the_result_says_so() {
        let dir = tempfile::tempdir().unwrap();
        write(dir.path(), "a.txt", "fn f() {\n    let x = 1;\n}\n").await;
        // A tab where the file has four spaces: not a substring, so this is the relaxed path.
        let out = tool(dir.path())
            .call(json!({"path": "a.txt",
                         "old_string": "\tlet x = 1;\n}",
                         "new_string": "    let x = 2;\n}"}))
            .await
            .unwrap();
        assert!(out.contains("ignoring indentation"), "{out}");
        assert_eq!(
            contents(dir.path(), "a.txt").await,
            "fn f() {\n    let x = 2;\n}\n"
        );
    }

    #[tokio::test]
    async fn a_relaxed_match_does_not_swallow_the_line_ending() {
        // The needle has no trailing newline, so the file's must survive: a relaxed match that
        // took it would join two lines.
        let dir = tempfile::tempdir().unwrap();
        write(dir.path(), "a.txt", "first\nsecond\n").await;
        tool(dir.path())
            .call(json!({"path": "a.txt", "old_string": "  second  ", "new_string": "SECOND"}))
            .await
            .unwrap();
        assert_eq!(contents(dir.path(), "a.txt").await, "first\nSECOND\n");
    }

    #[tokio::test]
    async fn an_empty_new_string_deletes_the_text() {
        let dir = tempfile::tempdir().unwrap();
        write(dir.path(), "a.txt", "keep\ndrop\nkeep2\n").await;
        tool(dir.path())
            .call(json!({"path": "a.txt", "old_string": "drop\n", "new_string": ""}))
            .await
            .unwrap();
        assert_eq!(contents(dir.path(), "a.txt").await, "keep\nkeep2\n");
    }

    #[tokio::test]
    async fn a_missing_file_says_to_use_write_file() {
        let dir = tempfile::tempdir().unwrap();
        let err = tool(dir.path())
            .call(json!({"path": "nope.txt", "old_string": "a", "new_string": "b"}))
            .await
            .unwrap_err();
        assert!(err.to_string().contains("write_file"), "{err}");
    }

    #[tokio::test]
    async fn a_patch_cannot_reach_outside_the_workspace() {
        let dir = tempfile::tempdir().unwrap();
        let err = tool(dir.path())
            .call(json!({"path": "../../etc/passwd", "old_string": "a", "new_string": "b"}))
            .await
            .unwrap_err();
        assert!(err.to_string().contains("outside the workspace"), "{err}");
    }

    #[tokio::test]
    async fn a_patch_to_a_script_in_the_scripts_directory_is_allowed() {
        let dir = tempfile::tempdir().unwrap();
        tokio::fs::create_dir_all(dir.path().join("scripts"))
            .await
            .unwrap();
        write(&dir.path().join("scripts"), "run.sh", "echo one\n").await;
        let path = dir.path().join("scripts/run.sh");
        tool(dir.path())
            .call(json!({"path": path.to_str().unwrap(), "old_string": "one", "new_string": "two"}))
            .await
            .unwrap();
        assert_eq!(
            contents(&dir.path().join("scripts"), "run.sh").await,
            "echo two\n"
        );
    }

    #[tokio::test]
    async fn an_empty_or_unchanged_edit_is_refused_before_the_file_is_read() {
        let dir = tempfile::tempdir().unwrap();
        let t = tool(dir.path());
        let empty = t
            .call(json!({"path": "a.txt", "old_string": "", "new_string": "x"}))
            .await
            .unwrap_err();
        assert!(empty.to_string().contains("nothing to find"), "{empty}");
        let same = t
            .call(json!({"path": "a.txt", "old_string": "x", "new_string": "x"}))
            .await
            .unwrap_err();
        assert!(same.to_string().contains("would not change"), "{same}");
    }

    #[test]
    fn the_diff_shows_the_old_line_under_a_minus_and_the_new_under_a_plus() {
        let before = "a\nb\nc\nd\n";
        let found = hits(before, "c\n");
        let diff = render_diff(before, &found, "C\n");
        assert!(diff.contains("@@ -1,4 +1,4 @@"), "{diff}");
        assert!(diff.contains("-c\n"), "{diff}");
        assert!(diff.contains("+C\n"), "{diff}");
        assert!(diff.contains(" b\n"), "{diff}");
        assert!(diff.contains(" d\n"), "{diff}");
    }

    #[test]
    fn an_edit_in_the_middle_of_a_line_is_shown_as_that_partial_line() {
        let before = "let x = 1;\n";
        let found = hits(before, "1");
        let diff = render_diff(before, &found, "2");
        assert!(diff.contains("-1\n"), "{diff}");
        assert!(diff.contains("+2\n"), "{diff}");
        // The untouched rest of the line is not invented as context.
        assert!(!diff.contains("let x"), "{diff}");
    }
}