rab-agent 0.1.0

rab is a lightweight, extensible, Rust-based coding agent.
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
use crate::agent::extension::{AgentTool, Cancel, Extension, ToolOutput};
use crate::agent::extension::{ToolRenderContext, ToolRenderer};
use crate::tui::Theme;
use anyhow::Context;
use async_trait::async_trait;
use std::borrow::Cow;
use tokio::sync::mpsc::UnboundedSender;

pub struct EditExtension {
    cwd: std::path::PathBuf,
}

impl EditExtension {
    pub fn new(cwd: std::path::PathBuf) -> Self {
        Self { cwd }
    }
}

impl Extension for EditExtension {
    fn name(&self) -> Cow<'static, str> {
        "edit".into()
    }

    fn tools(&self) -> Vec<Box<dyn AgentTool>> {
        vec![Box::new(EditTool {
            cwd: self.cwd.clone(),
        })]
    }
}

struct EditTool {
    cwd: std::path::PathBuf,
}

#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct Edit {
    old_text: String,
    new_text: String,
}

// ── BOM handling ──────────────────────────────────────────────────

/// Strip UTF-8 BOM if present. Returns (bom, content_without_bom).
fn strip_bom(content: &str) -> (&str, &str) {
    if content.starts_with('\u{FEFF}') {
        ("\u{FEFF}", &content['\u{FEFF}'.len_utf8()..])
    } else {
        ("", content)
    }
}

// ── Line ending handling ─────────────────────────────────────────

fn detect_line_ending(content: &str) -> &'static str {
    if content.contains("\r\n") {
        "\r\n"
    } else {
        "\n"
    }
}

fn normalize_to_lf(content: &str) -> String {
    content.replace("\r\n", "\n")
}

fn restore_line_endings(content: &str, ending: &str) -> String {
    if ending == "\r\n" {
        content.replace('\n', "\r\n")
    } else {
        content.to_string()
    }
}

// ── Fuzzy matching ───────────────────────────────────────────────

/// Normalize text for fuzzy matching:
/// - Strip trailing whitespace from each line
/// - Normalize Unicode smart quotes → ASCII quotes
/// - Normalize Unicode dashes/hyphens → ASCII hyphen
/// - Normalize special Unicode spaces → regular space
fn normalize_for_fuzzy_match(text: &str) -> String {
    // First pass: strip trailing whitespace per line
    let mut intermediate = String::with_capacity(text.len());
    for line in text.lines() {
        if !intermediate.is_empty() {
            intermediate.push('\n');
        }
        intermediate.push_str(line.trim_end());
    }
    // Handle trailing newline: lines() strips final newline, re-add if present
    if text.ends_with('\n') {
        intermediate.push('\n');
    }

    // Second pass: normalize Unicode characters to ASCII equivalents
    let mut result = String::with_capacity(intermediate.len());
    for ch in intermediate.chars() {
        match ch {
            '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}' => result.push('\''),
            '\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{201F}' => result.push('"'),
            '\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' | '\u{2014}' | '\u{2015}'
            | '\u{2212}' => {
                result.push('-');
            }
            '\u{00A0}' | '\u{2002}' | '\u{2003}' | '\u{2004}' | '\u{2005}' | '\u{2006}'
            | '\u{2007}' | '\u{2008}' | '\u{2009}' | '\u{200A}' | '\u{202F}' | '\u{205F}'
            | '\u{3000}' => {
                result.push(' ');
            }
            other => result.push(other),
        }
    }

    result
}

// ── Input normalization ──────────────────────────────────────────

/// Normalize tool arguments: handle `edits` as JSON string, legacy `oldText`/`newText`.
fn prepare_edit_arguments(args: &serde_json::Value) -> Result<(String, Vec<Edit>), String> {
    let path = args["path"]
        .as_str()
        .ok_or_else(|| "Missing 'path' argument".to_string())?;

    let edits = if let Some(edits_val) = args.get("edits") {
        if let Some(s) = edits_val.as_str() {
            // Some models send edits as a JSON string instead of an array
            serde_json::from_str::<Vec<Edit>>(s)
                .map_err(|e| format!("Invalid edits JSON string: {}", e))?
        } else {
            serde_json::from_value::<Vec<Edit>>(edits_val.clone())
                .map_err(|e| format!("Invalid edits array: {}", e))?
        }
    } else if let (Some(old), Some(new)) = (args.get("oldText"), args.get("newText")) {
        // Legacy: oldText + newText at top level
        let old_text = old
            .as_str()
            .ok_or_else(|| "Invalid 'oldText' argument: expected string".to_string())?;
        let new_text = new
            .as_str()
            .ok_or_else(|| "Invalid 'newText' argument: expected string".to_string())?;
        vec![Edit {
            old_text: old_text.to_string(),
            new_text: new_text.to_string(),
        }]
    } else {
        return Err("Missing 'edits' array (or 'oldText'/'newText' for legacy format)".to_string());
    };

    if edits.is_empty() {
        return Err("At least one edit is required".to_string());
    }

    Ok((path.to_string(), edits))
}

// ── Diff computation ─────────────────────────────────────────────

/// Compute a simple unified diff between original and modified content.
fn compute_diff(original: &str, modified: &str, path: &str) -> String {
    let orig_lines: Vec<&str> = original.lines().collect();
    let mod_lines: Vec<&str> = modified.lines().collect();

    let mut diff = String::new();
    diff.push_str("--- a/");
    diff.push_str(path);
    diff.push('\n');
    diff.push_str("+++ b/");
    diff.push_str(path);
    diff.push('\n');

    let mut i = 0;
    let mut j = 0;
    let mut hunk: Vec<(char, &str)> = Vec::new();
    let mut hunk_start_orig = 0;
    let mut hunk_start_mod = 0;

    while i < orig_lines.len() || j < mod_lines.len() {
        let same = i < orig_lines.len() && j < mod_lines.len() && orig_lines[i] == mod_lines[j];

        if same {
            if !hunk.is_empty() && hunk.len() >= 3 {
                // Emit context line within hunk
                hunk.push((' ', orig_lines[i]));
            } else {
                // Flush current hunk
                if !hunk.is_empty() {
                    flush_hunk(&mut diff, &mut hunk, hunk_start_orig, hunk_start_mod);
                }
                hunk_start_orig = i + 1;
                hunk_start_mod = j + 1;
            }
            i += 1;
            j += 1;
        } else {
            if hunk.is_empty() {
                hunk_start_orig = i;
                hunk_start_mod = j;
            }
            if i < orig_lines.len() {
                hunk.push(('-', orig_lines[i]));
                i += 1;
            }
            if j < mod_lines.len() {
                hunk.push(('+', mod_lines[j]));
                j += 1;
            }
        }
    }

    if !hunk.is_empty() {
        flush_hunk(&mut diff, &mut hunk, hunk_start_orig, hunk_start_mod);
    }

    diff
}

fn flush_hunk(
    diff: &mut String,
    hunk: &mut Vec<(char, &str)>,
    orig_start: usize,
    mod_start: usize,
) {
    let orig_count = hunk.iter().filter(|(c, _)| *c == '-' || *c == ' ').count();
    let mod_count = hunk.iter().filter(|(c, _)| *c == '+' || *c == ' ').count();
    use std::fmt::Write;
    let _ = writeln!(
        diff,
        "@@ -{},{} +{},{} @@",
        orig_start + 1,
        orig_count,
        mod_start + 1,
        mod_count
    );
    for (c, line) in hunk.drain(..) {
        let _ = writeln!(diff, "{}{}", c, line);
    }
}

// ── AgentTool implementation ─────────────────────────────────────

#[async_trait]
impl AgentTool for EditTool {
    fn name(&self) -> &str {
        "edit"
    }

    fn description(&self) -> &str {
        "Edit a single file using exact text replacement. Every edits[].oldText must match a \
         unique, non-overlapping region of the original file. If two changes affect the same \
         block or nearby lines, merge them into one edit instead of emitting overlapping edits. \
         Do not include large unchanged regions just to connect distant changes."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "required": ["path", "edits"],
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path to the file to edit (relative or absolute)"
                },
                "edits": {
                    "type": "array",
                    "description": "One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.",
                    "items": {
                        "type": "object",
                        "required": ["oldText", "newText"],
                        "properties": {
                            "oldText": {
                                "type": "string",
                                "description": "Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."
                            },
                            "newText": {
                                "type": "string",
                                "description": "Replacement text for this targeted edit."
                            }
                        }
                    }
                }
            }
        })
    }

    fn prompt_guidelines(&self) -> Vec<String> {
        vec![
            "Use edit for precise changes (edits[].oldText must match exactly)".into(),
            "When changing multiple separate locations in one file, use one edit call with multiple entries in edits[] instead of multiple edit calls".into(),
            "Each edits[].oldText is matched against the original file, not after earlier edits are applied. Do not emit overlapping or nested edits. Merge nearby changes into one edit.".into(),
            "Keep edits[].oldText as small as possible while still being unique in the file. Do not pad with large unchanged regions.".into(),
        ]
    }

    fn label(&self) -> &str {
        "Make precise file edits with exact text replacement, including multiple disjoint edits in one call"
    }

    fn renderer(&self) -> Option<Box<dyn ToolRenderer>> {
        Some(Box::new(EditRenderer))
    }

    async fn execute(
        &self,
        tool_call_id: String,
        args: serde_json::Value,
        cancel: Cancel,
        _on_update: Option<UnboundedSender<ToolOutput>>,
    ) -> anyhow::Result<ToolOutput> {
        let _ = tool_call_id;
        let (path_str, edits) =
            prepare_edit_arguments(&args).map_err(|e| anyhow::anyhow!("{}", e))?;

        cancel.check()?;

        let cwd = self.cwd.clone();
        let path_for_queue = path_str.clone();
        let cwd_for_closure = cwd.clone();

        // Wrap the entire read-edit-write in a per-file mutation queue so
        // concurrent edits to the same file are serialized (pi-style).
        let output = crate::builtin::file_mutation_queue::with_file_mutation_queue(
            &path_for_queue,
            &cwd,
            || async move {
                let abs_path = {
                    let p = std::path::Path::new(&path_str);
                    if p.is_absolute() {
                        p.to_path_buf()
                    } else {
                        cwd_for_closure.join(p)
                    }
                };

                // Read file
                let raw_content = std::fs::read_to_string(&abs_path)
                    .with_context(|| format!("Failed to read {}", abs_path.display()))?;

                // ── 1. BOM handling ──
                let (bom, content) = strip_bom(&raw_content);

                // ── 2. Line ending handling ──
                let original_ending = detect_line_ending(content);
                let normalized = normalize_to_lf(content);

                // ── 3. Work in fuzzy-normalized space ──
                let work_content = normalize_for_fuzzy_match(&normalized);

                // ── 4. Validate and find each edit ──
                let mut matched_indices: Vec<(usize, usize)> = Vec::new();

                for (i, edit) in edits.iter().enumerate() {
                    if edit.old_text.is_empty() {
                        return if edits.len() == 1 {
                            Err(anyhow::anyhow!("oldText must not be empty in {}.", path_str))
                        } else {
                            Err(anyhow::anyhow!(
                                "edits[{}].oldText must not be empty in {}.",
                                i,
                                path_str
                            ))
                        };
                    }

                    let fuzzy_old = normalize_for_fuzzy_match(&edit.old_text);
                    let count = work_content.matches(&fuzzy_old).count();

                    if count == 0 {
                        return if edits.len() == 1 {
                            Err(anyhow::anyhow!(
                                "Could not find the exact text in {}. \
                                 The old text must match exactly including all whitespace and newlines.",
                                path_str
                            ))
                        } else {
                            Err(anyhow::anyhow!(
                                "Could not find edits[{}] in {}. \
                                 The oldText must match exactly including all whitespace and newlines.",
                                i,
                                path_str
                            ))
                        };
                    }

                    if count > 1 {
                        return if edits.len() == 1 {
                            Err(anyhow::anyhow!(
                                "Found {} occurrences of the text in {}. \
                                 The text must be unique. Please provide more context to make it unique.",
                                count,
                                path_str
                            ))
                        } else {
                            Err(anyhow::anyhow!(
                                "Found {} occurrences of edits[{}] in {}. \
                                 Each oldText must be unique. Please provide more context to make it unique.",
                                count,
                                i,
                                path_str
                            ))
                        };
                    }

                    let pos = work_content.find(&fuzzy_old).unwrap();
                    matched_indices.push((pos, pos + fuzzy_old.len()));
                }

                // ── 5. Check for overlapping edits ──
                for (idx_i, &(pos_i, end_i)) in matched_indices.iter().enumerate() {
                    for (idx_j, &(pos_j, end_j)) in matched_indices.iter().enumerate().skip(idx_i + 1) {
                        if pos_i < end_j && pos_j < end_i {
                            return Err(anyhow::anyhow!(
                                "edits[{}] and edits[{}] overlap. Merge them into one edit.",
                                idx_i,
                                idx_j
                            ));
                        }
                    }
                }

                // ── 6. Apply edits (sorted left-to-right) ──
                let mut sorted: Vec<(usize, usize, &Edit)> = matched_indices
                    .into_iter()
                    .zip(edits.iter())
                    .map(|((start, end), edit)| (start, end, edit))
                    .collect();
                sorted.sort_by_key(|(pos, _, _)| *pos);

                let mut modified = String::new();
                let mut cursor = 0;
                for (start, end, edit) in &sorted {
                    modified.push_str(&work_content[cursor..*start]);
                    modified.push_str(&edit.new_text);
                    cursor = *end;
                }
                modified.push_str(&work_content[cursor..]);

                // ── 7. Compute diff ──
                let diff = compute_diff(&normalized, &modified, &path_str);

                // ── 8. Write back with original line endings and BOM ──
                let final_content =
                    bom.to_string() + &restore_line_endings(&modified, original_ending);
                std::fs::write(&abs_path, &final_content)
                    .with_context(|| format!("Failed to write {}", abs_path.display()))?;

                // ── 9. Return result ──
                let noun = if edits.len() == 1 { "block" } else { "blocks" };
                Ok(format!(
                    "Successfully replaced {} {} in {}.\n```diff\n{}```",
                    edits.len(),
                    noun,
                    path_str,
                    diff.trim_end()
                ))
            },
        )
        .await?;

        Ok(ToolOutput::ok(output))
    }
}

/// Tool renderer for the `edit` tool.
/// Uses `renderShell: "self"` — renders its own framing without colored box.
/// Shows a preview of what will change in the call header.
struct EditRenderer;

impl ToolRenderer for EditRenderer {
    fn render_self(&self) -> bool {
        true
    }

    fn render_call(
        &self,
        args: &serde_json::Value,
        width: usize,
        theme: &dyn Theme,
        ctx: &ToolRenderContext,
    ) -> Vec<String> {
        let path = args
            .get("file_path")
            .or_else(|| args.get("path"))
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let short = if let Ok(home) = std::env::var("HOME") {
            path.replacen(&home, "~", 1)
        } else {
            path.to_string()
        };
        let path_disp = if short.is_empty() {
            String::new()
        } else {
            theme.fg("accent", &short)
        };

        let mut lines = vec![format!(
            "{} {}",
            theme.fg("toolTitle", &theme.bold("edit")),
            path_disp
        )];

        // Show edit preview when collapsed (compact summary of changes)
        if !ctx.expanded
            && let Some(edits) = args.get("edits")
        {
            let edits_arr = if let Some(arr) = edits.as_array() {
                arr.as_slice()
            } else {
                static EMPTY: [serde_json::Value; 0] = [];
                &EMPTY // Can't parse here, skip preview
            };

            for edit in edits_arr.iter().take(3) {
                if let (Some(old), new) = (edit.get("oldText"), edit.get("newText"))
                    && let (Some(old_str), Some(new_str)) =
                        (old.as_str(), new.and_then(|v| v.as_str()))
                {
                    let preview = format_edit_preview(old_str, new_str, width, theme);
                    lines.extend(preview);
                }
            }

            if edits_arr.len() > 3 {
                lines.push(theme.fg(
                    "muted",
                    &format!("... and {} more edits", edits_arr.len() - 3),
                ));
            }
        }

        lines
    }

    fn render_result(
        &self,
        content: &str,
        _width: usize,
        theme: &dyn Theme,
        _ctx: &ToolRenderContext,
    ) -> Vec<String> {
        // Extract diff from ```diff ... ``` block in the result
        if let Some(start) = content.find("```diff\n") {
            let after = &content[start + 8..];
            if let Some(end) = after.find("```") {
                let diff_text = &after[..end];
                let has_diff = diff_text
                    .lines()
                    .any(|l| l.starts_with('-') || l.starts_with('+') || l.starts_with(' '));
                if has_diff {
                    let rendered = crate::tui::components::diff::render_diff(diff_text);
                    return rendered;
                }
            }
        }
        // Fallback: show content as-is
        if content.is_empty() {
            return vec![];
        }
        vec![theme.fg("toolOutput", content)]
    }
}

/// Format a compact preview of a single edit operation.
/// Shows first N chars of oldText → first N chars of newText as separate lines.
fn format_edit_preview(old: &str, new: &str, _width: usize, theme: &dyn Theme) -> Vec<String> {
    let max_preview = 30;
    let old_first_line = old.lines().next().unwrap_or("");
    let new_first_line = new.lines().next().unwrap_or("");

    let old_preview = truncate_simple(old_first_line, max_preview);
    let new_preview = truncate_simple(new_first_line, max_preview);

    let old_styled = theme.fg("toolDiffRemoved", &format!("-{}", old_preview));
    let new_styled = theme.fg("toolDiffAdded", &format!("+{}", new_preview));
    vec![format!("  {}", old_styled), format!("  {}", new_styled)]
}

/// Truncate a string to max_chars, adding "..." if truncated.
fn truncate_simple(s: &str, max_chars: usize) -> String {
    if s.len() <= max_chars {
        s.to_string()
    } else if max_chars > 3 {
        format!("{}...", &s[..max_chars - 3])
    } else {
        s[..max_chars].to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::extension::Cancel;

    fn tmp_dir() -> std::path::PathBuf {
        let d = std::env::temp_dir().join(format!("rab-edit-test-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    fn make_tool() -> (EditTool, std::path::PathBuf) {
        let tmp = tmp_dir();
        let tool = EditTool { cwd: tmp.clone() };
        (tool, tmp)
    }

    async fn exec_ok(tool: &EditTool, args: serde_json::Value) -> String {
        tool.execute("id".into(), args, Cancel::new(), None)
            .await
            .unwrap()
            .content
    }

    async fn exec_err(tool: &EditTool, args: serde_json::Value) -> String {
        tool.execute("id".into(), args, Cancel::new(), None)
            .await
            .unwrap_err()
            .to_string()
    }

    async fn is_err(tool: &EditTool, args: serde_json::Value) -> bool {
        tool.execute("id".into(), args, Cancel::new(), None)
            .await
            .is_err()
    }

    #[tokio::test]
    async fn single_edit_replaces_text() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("file.txt");
        std::fs::write(&path, "hello world\nfoo bar\n").unwrap();

        exec_ok(
            &tool,
            serde_json::json!({
                "path": path.to_str().unwrap(),
                "edits": [{"oldText": "foo bar", "newText": "baz qux"}]
            }),
        )
        .await;

        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "hello world\nbaz qux\n"
        );
    }

    #[tokio::test]
    async fn multiple_edits_replaces_all() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("file.txt");
        std::fs::write(&path, "aaa\nbbb\nccc\n").unwrap();

        exec_ok(
            &tool,
            serde_json::json!({
                "path": path.to_str().unwrap(),
                "edits": [
                    {"oldText": "aaa", "newText": "111"},
                    {"oldText": "ccc", "newText": "333"}
                ]
            }),
        )
        .await;

        assert_eq!(std::fs::read_to_string(&path).unwrap(), "111\nbbb\n333\n");
    }

    #[tokio::test]
    async fn non_unique_oldtext_errors() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("file.txt");
        std::fs::write(&path, "dup\ndup\n").unwrap();

        assert!(
            is_err(
                &tool,
                serde_json::json!({
                    "path": path.to_str().unwrap(),
                    "edits": [{"oldText": "dup", "newText": "x"}]
                }),
            )
            .await
        );
    }

    #[tokio::test]
    async fn missing_oldtext_errors() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("file.txt");
        std::fs::write(&path, "content\n").unwrap();

        let err = exec_err(
            &tool,
            serde_json::json!({
                "path": path.to_str().unwrap(),
                "edits": [{"oldText": "not found", "newText": "x"}]
            }),
        )
        .await;
        assert!(err.contains("Could not find"));
    }

    #[tokio::test]
    async fn overlapping_edits_error() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("file.txt");
        std::fs::write(&path, "abcdef\n").unwrap();

        assert!(
            is_err(
                &tool,
                serde_json::json!({
                    "path": path.to_str().unwrap(),
                    "edits": [
                        {"oldText": "abc", "newText": "1"},
                        {"oldText": "bcd", "newText": "2"}
                    ]
                }),
            )
            .await
        );
    }

    #[tokio::test]
    async fn empty_edits_errors() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("file.txt");
        std::fs::write(&path, "content\n").unwrap();

        assert!(
            is_err(
                &tool,
                serde_json::json!({"path": path.to_str().unwrap(), "edits": []}),
            )
            .await
        );
    }

    // ── BOM handling ─────────────────────────────────────────

    #[tokio::test]
    async fn handles_bom() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("bom.txt");
        std::fs::write(&path, "\u{FEFF}hello world\n").unwrap();

        exec_ok(
            &tool,
            serde_json::json!({
                "path": path.to_str().unwrap(),
                "edits": [{"oldText": "hello world", "newText": "goodbye"}]
            }),
        )
        .await;

        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.starts_with('\u{FEFF}'));
        assert!(content.contains("goodbye"));
    }

    #[tokio::test]
    async fn preserves_bom_when_no_edit_at_start() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("bom2.txt");
        std::fs::write(&path, "\u{FEFF}line1\nline2\n").unwrap();

        exec_ok(
            &tool,
            serde_json::json!({
                "path": path.to_str().unwrap(),
                "edits": [{"oldText": "line2", "newText": "modified"}]
            }),
        )
        .await;

        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.starts_with('\u{FEFF}'));
        assert!(content.contains("modified"));
    }

    // ── CRLF handling ────────────────────────────────────────

    #[tokio::test]
    async fn preserves_crlf() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("crlf.txt");
        std::fs::write(&path, "hello\r\nworld\r\n").unwrap();

        exec_ok(
            &tool,
            serde_json::json!({
                "path": path.to_str().unwrap(),
                "edits": [{"oldText": "world", "newText": "universe"}]
            }),
        )
        .await;

        let content = std::fs::read_to_string(&path).unwrap();
        assert_eq!(content, "hello\r\nuniverse\r\n");
    }

    #[tokio::test]
    async fn handles_mixed_line_endings() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("mixed.txt");
        std::fs::write(&path, "line1\r\nline2\nline3\n").unwrap();

        exec_ok(
            &tool,
            serde_json::json!({
                "path": path.to_str().unwrap(),
                "edits": [{"oldText": "line2", "newText": "modified"}]
            }),
        )
        .await;

        let content = std::fs::read_to_string(&path).unwrap();
        assert_eq!(content, "line1\r\nmodified\r\nline3\r\n");
    }

    #[tokio::test]
    async fn lf_only_stays_lf() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("lf.txt");
        std::fs::write(&path, "hello\nworld\n").unwrap();

        exec_ok(
            &tool,
            serde_json::json!({
                "path": path.to_str().unwrap(),
                "edits": [{"oldText": "world", "newText": "universe"}]
            }),
        )
        .await;

        let content = std::fs::read_to_string(&path).unwrap();
        assert_eq!(content, "hello\nuniverse\n");
    }

    // ── Fuzzy matching ───────────────────────────────────────

    #[tokio::test]
    async fn fuzzy_match_trailing_whitespace() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("trailing.txt");
        std::fs::write(&path, "hello world  \nnext line\n").unwrap();

        exec_ok(
            &tool,
            serde_json::json!({
                "path": path.to_str().unwrap(),
                "edits": [{"oldText": "hello world", "newText": "hi there"}]
            }),
        )
        .await;

        let content = std::fs::read_to_string(&path).unwrap();
        assert_eq!(content, "hi there\nnext line\n");
    }

    #[tokio::test]
    async fn fuzzy_match_smart_quotes() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("quotes.txt");
        std::fs::write(&path, "he said \u{201C}hello\u{201D}\n").unwrap();

        exec_ok(
            &tool,
            serde_json::json!({
                "path": path.to_str().unwrap(),
                "edits": [{"oldText": "he said \"hello\"", "newText": "she said \"hi\""}]
            }),
        )
        .await;

        let content = std::fs::read_to_string(&path).unwrap();
        assert_eq!(content, "she said \"hi\"\n");
    }

    #[tokio::test]
    async fn fuzzy_match_dashes() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("dashes.txt");
        std::fs::write(&path, "foo \u{2014} bar\n").unwrap();

        exec_ok(
            &tool,
            serde_json::json!({
                "path": path.to_str().unwrap(),
                "edits": [{"oldText": "foo - bar", "newText": "baz"}]
            }),
        )
        .await;

        let content = std::fs::read_to_string(&path).unwrap();
        assert_eq!(content, "baz\n");
    }

    // ── Input normalization ──────────────────────────────────

    #[tokio::test]
    async fn legacy_oldtext_newtext() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("legacy.txt");
        std::fs::write(&path, "hello world\n").unwrap();

        exec_ok(
            &tool,
            serde_json::json!({
                "path": path.to_str().unwrap(),
                "oldText": "hello world",
                "newText": "goodbye"
            }),
        )
        .await;

        assert_eq!(std::fs::read_to_string(&path).unwrap(), "goodbye\n");
    }

    #[tokio::test]
    async fn edits_as_json_string() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("jsonstr.txt");
        std::fs::write(&path, "aaa\nbbb\n").unwrap();

        exec_ok(
            &tool,
            serde_json::json!({
                "path": path.to_str().unwrap(),
                "edits": r#"[{"oldText": "bbb", "newText": "xxx"}]"#
            }),
        )
        .await;

        assert_eq!(std::fs::read_to_string(&path).unwrap(), "aaa\nxxx\n");
    }

    // ── Diff output ──────────────────────────────────────────

    #[tokio::test]
    async fn result_contains_diff() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("diff_test.txt");
        std::fs::write(&path, "aaa\nbbb\nccc\n").unwrap();

        let result = exec_ok(
            &tool,
            serde_json::json!({
                "path": path.to_str().unwrap(),
                "edits": [{"oldText": "bbb", "newText": "xxx"}]
            }),
        )
        .await;

        assert!(result.contains("```diff"));
        assert!(result.contains("-bbb"));
        assert!(result.contains("+xxx"));
        assert!(result.contains("Successfully replaced 1 block"));
    }

    // ── Empty oldText ────────────────────────────────────────

    #[tokio::test]
    async fn empty_oldtext_errors() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("empty.txt");
        std::fs::write(&path, "content\n").unwrap();

        let err = exec_err(
            &tool,
            serde_json::json!({
                "path": path.to_str().unwrap(),
                "edits": [{"oldText": "", "newText": "x"}]
            }),
        )
        .await;
        assert!(err.contains("empty"));
    }

    // ── Relative paths ───────────────────────────────────────

    #[tokio::test]
    async fn relative_path_resolves_to_cwd() {
        let (tool, tmp) = make_tool();
        let path = tmp.join("relative.txt");
        std::fs::write(&path, "hello\n").unwrap();

        exec_ok(
            &tool,
            serde_json::json!({
                "path": "relative.txt",
                "edits": [{"oldText": "hello", "newText": "hi"}]
            }),
        )
        .await;

        assert_eq!(std::fs::read_to_string(&path).unwrap(), "hi\n");
    }
}

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

    #[test]
    fn test_strip_trailing_whitespace() {
        assert_eq!(
            normalize_for_fuzzy_match("hello   \nworld  "),
            "hello\nworld"
        );
    }

    #[test]
    fn test_smart_quotes() {
        assert_eq!(
            normalize_for_fuzzy_match("\u{2018}hello\u{2019} \u{201C}world\u{201D}"),
            "'hello' \"world\""
        );
    }

    #[test]
    fn test_dashes() {
        assert_eq!(normalize_for_fuzzy_match("a\u{2014}b"), "a-b");
        assert_eq!(normalize_for_fuzzy_match("a\u{2013}b"), "a-b");
    }

    #[test]
    fn test_nbsp() {
        assert_eq!(normalize_for_fuzzy_match("a\u{00A0}b"), "a b");
    }

    #[test]
    fn test_preserves_trailing_newline() {
        assert_eq!(normalize_for_fuzzy_match("hello\n"), "hello\n");
        assert_eq!(
            normalize_for_fuzzy_match("hello\nworld\n"),
            "hello\nworld\n"
        );
    }
}

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

    #[test]
    fn test_simple_diff() {
        let orig = "aaa\nbbb\nccc\n";
        let modified = "aaa\nxxx\nccc\n";
        let diff = compute_diff(orig, modified, "test.txt");
        assert!(diff.contains("--- a/test.txt"));
        assert!(diff.contains("+++ b/test.txt"));
        assert!(diff.contains("-bbb"));
        assert!(diff.contains("+xxx"));
    }

    #[test]
    fn test_no_changes() {
        let text = "hello\nworld\n";
        let diff = compute_diff(text, text, "f.txt");
        assert!(diff.contains("--- a/f.txt"));
        assert!(diff.contains("+++ b/f.txt"));
        assert!(!diff.contains("@@"));
    }

    #[test]
    fn test_multiple_hunks() {
        let orig = "a\nb\nc\nd\ne\nf\ng\nh\n";
        let modified = "a\nX\nc\nd\ne\nY\ng\nh\n";
        let diff = compute_diff(orig, modified, "f.txt");
        assert!(diff.contains("-b"));
        assert!(diff.contains("+X"));
        assert!(diff.contains("-f"));
        assert!(diff.contains("+Y"));
    }
}