imp-core 0.1.1

Agent engine for imp: loop, tools, sessions, hooks, context, and SDK
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
use std::path::Path;

use async_trait::async_trait;
use imp_llm::truncate_chars_with_suffix;
use serde_json::json;

use super::fuzzy;
use super::{generate_diff, suggest_similar_files, Tool, ToolContext, ToolOutput};
use crate::error::Result;

pub struct EditTool;

#[async_trait]
impl Tool for EditTool {
    fn name(&self) -> &str {
        "edit"
    }
    fn label(&self) -> &str {
        "Edit File"
    }
    fn description(&self) -> &str {
        "Canonical edit tool. Edit a file with exact find/replace, anchored range replacement, or a validated multi-edit transaction via edits[]."
    }
    fn parameters(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "path": { "type": "string", "description": "Path for single-file exact/anchored edits, or default path for transaction edits. Per-edit path may override this inside edits[]." },
                "oldText": { "type": "string", "description": "Text to replace for exact/fuzzy single-edit mode" },
                "newText": { "type": "string", "description": "Replacement text for exact/fuzzy single-edit mode" },
                "dryRun": {
                    "type": "boolean",
                    "description": "Return the diff and metadata without writing the file"
                },
                "expectedOccurrences": {
                    "type": "integer",
                    "description": "Require this many exact oldText matches before editing; useful with 1 to prevent ambiguous replacements"
                },
                "replaceAll": {
                    "type": "boolean",
                    "description": "Replace all exact oldText matches instead of only the first match"
                },
                "anchorStart": {
                    "type": "string",
                    "description": "Start anchor emitted by read with anchors=true for anchored range replacement"
                },
                "anchorEnd": {
                    "type": "string",
                    "description": "Optional end anchor emitted by read with anchors=true. Defaults to anchorStart."
                },
                "replacement": {
                    "type": "string",
                    "description": "Replacement text for anchored edit mode"
                },
                "edits": {
                    "type": "array",
                    "description": "Validated transaction edits handled by the canonical edit tool. Each edit supports oldText, newText, and optional path for multi-file transactions.",
                    "items": {
                        "type": "object",
                        "properties": {
                            "path": { "type": "string", "description": "Optional per-edit path for multi-file transactions" },
                            "oldText": { "type": "string" },
                            "newText": { "type": "string" }
                        },
                        "required": ["oldText", "newText"]
                    }
                }
            },
            "required": []
        })
    }
    fn is_readonly(&self) -> bool {
        false
    }

    async fn execute(
        &self,
        call_id: &str,
        params: serde_json::Value,
        ctx: ToolContext,
    ) -> Result<ToolOutput> {
        // Multi-edit mode: if `edits` array is present, delegate to MultiEditTool
        if params.get("edits").is_some_and(|v| v.is_array()) {
            return super::multi_edit::MultiEditTool
                .execute(call_id, params, ctx)
                .await;
        }

        let raw_path = params["path"].as_str().unwrap_or("");
        let old_text = params["oldText"].as_str().unwrap_or("");
        let new_text = params["newText"].as_str().unwrap_or("");
        let dry_run = params["dryRun"].as_bool().unwrap_or(false);
        let replace_all = params["replaceAll"].as_bool().unwrap_or(false);
        let expected_occurrences = params
            .get("expectedOccurrences")
            .and_then(|v| v.as_u64())
            .map(|v| v as usize);

        if raw_path.is_empty() {
            return Ok(ToolOutput::error("Missing required parameter: path"));
        }

        let path = super::resolve_path(&ctx.cwd, raw_path);

        if params.get("anchorStart").and_then(|v| v.as_str()).is_some() {
            return execute_anchor_edit(&path, raw_path, &params, ctx).await;
        }

        if old_text.is_empty() {
            return Ok(ToolOutput::error("Missing required parameter: oldText"));
        }

        if !path.exists() {
            let suggestions = suggest_similar_files(&ctx.cwd, raw_path);
            let mut msg = format!("File not found: {}", path.display());
            if !suggestions.is_empty() {
                msg.push_str("\n\nDid you mean:");
                for s in &suggestions {
                    msg.push_str(&format!("\n  {s}"));
                }
            }
            return Ok(ToolOutput::error(msg));
        }

        // Check for unread or stale file — warn but don't block.
        let tracker_warning = {
            let tracker = ctx.file_tracker.lock().ok();
            match tracker {
                Some(t) if !t.was_read(&path) => Some(format!(
                    "Warning: editing {} without reading it first. Consider reading to verify current content.",
                    path.display()
                )),
                Some(t) if t.is_stale(&path) => Some(format!(
                    "Warning: {} was modified externally since last read. Re-read to verify current content.",
                    path.display()
                )),
                _ => None,
            }
        };

        let raw_content = tokio::fs::read_to_string(&path).await?;

        // Normalize to LF for internal processing
        let content = raw_content.replace("\r\n", "\n");
        let has_crlf = raw_content.contains("\r\n");
        let old_normalized = old_text.replace("\r\n", "\n");
        let new_normalized = new_text.replace("\r\n", "\n");

        let exact_occurrences = count_occurrences(&content, &old_normalized);
        if let Some(expected) = expected_occurrences {
            if exact_occurrences != expected {
                return Ok(ToolOutput::error(format!(
                    "Expected {expected} exact occurrence(s) of oldText in {raw_path}, found {exact_occurrences}. No changes made."
                )));
            }
        }

        let (new_content, was_fuzzy, replacements) = if replace_all {
            if exact_occurrences == 0 {
                return match apply_edit(&content, &old_normalized, &new_normalized) {
                    Ok((_, true)) => Ok(ToolOutput::error(
                        "replaceAll requires exact matches and does not use fuzzy matching. Found 0 exact matches, but a fuzzy match exists. No changes made.",
                    )),
                    Ok(_) => unreachable!("apply_edit cannot exact-match when exact_occurrences is 0"),
                    Err(output) => Ok(output),
                };
            }
            (
                content.replace(&old_normalized, &new_normalized),
                false,
                exact_occurrences,
            )
        } else {
            match apply_edit(&content, &old_normalized, &new_normalized) {
                Ok((new_content, was_fuzzy)) => (new_content, was_fuzzy, 1),
                Err(output) => return Ok(output),
            }
        };

        let diff = generate_diff(raw_path, &content, &new_content);

        // Restore original line endings if needed
        let final_content = if has_crlf {
            new_content.replace('\n', "\r\n")
        } else {
            new_content
        };

        if !dry_run {
            ctx.checkpoint_state.snapshot_paths(
                std::slice::from_ref(&path),
                Some(format!("edit {}", path.display())),
            )?;
            tokio::fs::write(&path, &final_content).await?;
        }

        let mut msg = diff;
        if dry_run {
            msg.push_str("\n(dry run: no changes written)");
        }
        if was_fuzzy {
            msg.push_str(
                "\n(matched using fuzzy matching: trailing whitespace/unicode normalized)",
            );
        }
        if let Some(warning) = tracker_warning {
            msg.push('\n');
            msg.push_str(&warning);
        }

        Ok(ToolOutput {
            content: vec![imp_llm::ContentBlock::Text { text: msg }],
            details: json!({
                "path": path.display().to_string(),
                "fuzzy_match": was_fuzzy,
                "dry_run": dry_run,
                "replace_all": replace_all,
                "exact_occurrences": exact_occurrences,
                "replacements": replacements,
            }),
            is_error: false,
        })
    }
}

async fn execute_anchor_edit(
    path: &Path,
    raw_path: &str,
    params: &serde_json::Value,
    ctx: ToolContext,
) -> Result<ToolOutput> {
    let Some(anchor_start_id) = params["anchorStart"].as_str() else {
        return Ok(ToolOutput::error("Missing required parameter: anchorStart"));
    };
    let anchor_end_id = params["anchorEnd"].as_str().unwrap_or(anchor_start_id);
    let Some(replacement) = params["replacement"].as_str() else {
        return Ok(ToolOutput::error(
            "Missing required parameter: replacement for anchored edit mode",
        ));
    };
    let dry_run = params["dryRun"].as_bool().unwrap_or(false);

    if !path.exists() {
        let suggestions = suggest_similar_files(&ctx.cwd, raw_path);
        let mut msg = format!("File not found: {}", path.display());
        if !suggestions.is_empty() {
            msg.push_str("\n\nDid you mean:");
            for s in &suggestions {
                msg.push_str(&format!("\n  {s}"));
            }
        }
        return Ok(ToolOutput::error(msg));
    }

    let Some(start_anchor) = ctx.anchor_store.get(path, anchor_start_id) else {
        return Ok(ToolOutput::error(format!(
            "Anchor not found or expired for {raw_path}: {anchor_start_id}. Re-read with anchors=true before editing."
        )));
    };
    let Some(end_anchor) = ctx.anchor_store.get(path, anchor_end_id) else {
        return Ok(ToolOutput::error(format!(
            "Anchor not found or expired for {raw_path}: {anchor_end_id}. Re-read with anchors=true before editing."
        )));
    };
    if start_anchor.line > end_anchor.line {
        return Ok(ToolOutput::error(
            "anchorStart must refer to a line before or equal to anchorEnd",
        ));
    }

    let raw_content = tokio::fs::read_to_string(path).await?;
    let content = raw_content.replace("\r\n", "\n");
    let has_crlf = raw_content.contains("\r\n");
    let lines = content.lines().collect::<Vec<_>>();
    let start_idx = start_anchor.line.saturating_sub(1);
    let end_idx = end_anchor.line.saturating_sub(1);
    if start_idx >= lines.len() || end_idx >= lines.len() {
        return Ok(ToolOutput::error(
            "Anchor line is outside the current file. Re-read with anchors=true before editing.",
        ));
    }
    if super::stable_hash(lines[start_idx]) != start_anchor.content_hash {
        return Ok(ToolOutput::error(format!(
            "Stale anchor at line {} in {raw_path}. Re-read with anchors=true before editing.",
            start_anchor.line
        )));
    }
    if super::stable_hash(lines[end_idx]) != end_anchor.content_hash {
        return Ok(ToolOutput::error(format!(
            "Stale anchor at line {} in {raw_path}. Re-read with anchors=true before editing.",
            end_anchor.line
        )));
    }

    let mut replacement_normalized = replacement.replace("\r\n", "\n");
    let had_trailing_newline = content.ends_with('\n');
    let mut new_lines = Vec::with_capacity(lines.len() + replacement_normalized.lines().count());
    new_lines.extend_from_slice(&lines[..start_idx]);
    if replacement_normalized.ends_with('\n') {
        replacement_normalized.pop();
    }
    if !replacement_normalized.is_empty() {
        new_lines.extend(replacement_normalized.lines());
    }
    new_lines.extend_from_slice(&lines[end_idx + 1..]);
    let mut new_content = new_lines.join("\n");
    if had_trailing_newline {
        new_content.push('\n');
    }

    let diff = generate_diff(raw_path, &content, &new_content);
    let final_content = if has_crlf {
        new_content.replace('\n', "\r\n")
    } else {
        new_content.clone()
    };

    if !dry_run {
        ctx.checkpoint_state.snapshot_paths(
            std::slice::from_ref(&path.to_path_buf()),
            Some(format!("anchored edit {}", path.display())),
        )?;
        tokio::fs::write(path, &final_content).await?;
        if let Ok(mut tracker) = ctx.file_tracker.lock() {
            tracker.record_read(path);
        }
    }

    let refreshed_lines = new_content.lines().collect::<Vec<_>>();
    let refreshed =
        ctx.anchor_store
            .record_lines(path, super::stable_hash(&new_content), 1, &refreshed_lines);
    let mut msg = diff;
    if dry_run {
        msg.push_str("\n(dry run: no changes written)");
    }
    msg.push_str("\n(anchored edit: anchors validated before replacement)");

    Ok(ToolOutput {
        content: vec![imp_llm::ContentBlock::Text { text: msg }],
        details: json!({
            "path": path.display().to_string(),
            "dry_run": dry_run,
            "anchored": true,
            "start_line": start_anchor.line,
            "end_line": end_anchor.line,
            "refreshed_anchors": refreshed.iter().map(|anchor| json!({
                "line": anchor.line,
                "anchor": anchor.id,
                "content_hash": format!("{:016x}", anchor.content_hash),
            })).collect::<Vec<_>>(),
        }),
        is_error: false,
    })
}

fn count_occurrences(content: &str, needle: &str) -> usize {
    if needle.is_empty() {
        return 0;
    }
    content.match_indices(needle).count()
}

/// Apply a single edit, returning the new content and whether fuzzy matching was used.
/// Extracted so multi_edit can reuse it.
pub(crate) fn apply_edit(
    content: &str,
    old_text: &str,
    new_text: &str,
) -> std::result::Result<(String, bool), ToolOutput> {
    // Try exact match first
    if let Some(pos) = content.find(old_text) {
        let mut result = String::with_capacity(content.len());
        result.push_str(&content[..pos]);
        result.push_str(new_text);
        result.push_str(&content[pos + old_text.len()..]);
        return Ok((result, false));
    }

    // Try fuzzy match
    if let Some(m) = fuzzy::fuzzy_find(content, old_text) {
        let mut result = String::with_capacity(content.len());
        result.push_str(&content[..m.start]);
        result.push_str(new_text);
        result.push_str(&content[m.end..]);
        return Ok((result, true));
    }

    // No match — build helpful error
    let preview = truncate_chars_with_suffix(content, 200, "");
    let msg = format!(
        "Could not find the specified text to replace.\n\
         First 200 chars of file:\n{preview}"
    );
    Err(ToolOutput::error(msg))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::ToolContext;
    use std::sync::Arc;

    fn test_ctx(dir: &std::path::Path) -> ToolContext {
        let (tx, _rx) = tokio::sync::mpsc::channel(16);
        let (cmd_tx, _cmd_rx) = tokio::sync::mpsc::channel(16);
        ToolContext {
            cwd: dir.to_path_buf(),
            cancelled: Arc::new(std::sync::atomic::AtomicBool::new(false)),
            update_tx: tx,
            command_tx: cmd_tx,
            ui: Arc::new(crate::ui::NullInterface),
            file_cache: Arc::new(crate::tools::FileCache::new()),
            checkpoint_state: Arc::new(crate::tools::CheckpointState::new()),
            file_tracker: Arc::new(std::sync::Mutex::new(crate::tools::FileTracker::new())),
            anchor_store: Arc::new(crate::tools::AnchorStore::new()),
            lua_tool_loader: None,
            mode: crate::config::AgentMode::Full,
            read_max_lines: 500,
            turn_mana_review: Arc::new(std::sync::Mutex::new(
                crate::mana_review::TurnManaReviewAccumulator::default(),
            )),
            config: Arc::new(crate::config::Config::default()),
        }
    }

    #[tokio::test]
    async fn edit_exact_match() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.rs");
        std::fs::write(&file, "fn main() {\n    println!(\"hello\");\n}\n").unwrap();

        let tool = EditTool;
        let result = tool
            .execute(
                "c1",
                json!({
                    "path": "test.rs",
                    "oldText": "println!(\"hello\")",
                    "newText": "println!(\"world\")"
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        let written = std::fs::read_to_string(&file).unwrap();
        assert!(written.contains("world"));
        assert!(!written.contains("hello"));
    }

    #[tokio::test]
    async fn edit_dry_run_returns_diff_without_writing() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("dry.txt");
        std::fs::write(&file, "alpha\n").unwrap();

        let tool = EditTool;
        let ctx = test_ctx(dir.path());
        let checkpoint_state = ctx.checkpoint_state.clone();
        let result = tool
            .execute(
                "c-dry",
                json!({
                    "path": "dry.txt",
                    "oldText": "alpha",
                    "newText": "beta",
                    "dryRun": true
                }),
                ctx,
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "alpha\n");
        assert!(checkpoint_state.checkpoints().is_empty());
        assert_eq!(result.details["dry_run"], true);
        let text = result.text_content().unwrap();
        assert!(text.contains("beta"));
        assert!(text.contains("dry run"));
    }

    #[tokio::test]
    async fn edit_expected_occurrences_mismatch_does_not_write() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("expected-mismatch.txt");
        std::fs::write(&file, "foo foo\n").unwrap();

        let tool = EditTool;
        let result = tool
            .execute(
                "c-expected-mismatch",
                json!({
                    "path": "expected-mismatch.txt",
                    "oldText": "foo",
                    "newText": "bar",
                    "expectedOccurrences": 1
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(result.is_error);
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "foo foo\n");
        assert!(result.text_content().unwrap().contains("found 2"));
    }

    #[tokio::test]
    async fn edit_expected_occurrences_success_writes() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("expected-success.txt");
        std::fs::write(&file, "foo\n").unwrap();

        let tool = EditTool;
        let result = tool
            .execute(
                "c-expected-success",
                json!({
                    "path": "expected-success.txt",
                    "oldText": "foo",
                    "newText": "bar",
                    "expectedOccurrences": 1
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "bar\n");
        assert_eq!(result.details["exact_occurrences"], 1);
        assert_eq!(result.details["replacements"], 1);
    }

    #[tokio::test]
    async fn edit_replace_all_replaces_exact_matches() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("replace-all.txt");
        std::fs::write(&file, "foo bar foo baz foo\n").unwrap();

        let tool = EditTool;
        let result = tool
            .execute(
                "c-replace-all",
                json!({
                    "path": "replace-all.txt",
                    "oldText": "foo",
                    "newText": "zap",
                    "replaceAll": true,
                    "expectedOccurrences": 3
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        assert_eq!(
            std::fs::read_to_string(&file).unwrap(),
            "zap bar zap baz zap\n"
        );
        assert_eq!(result.details["replace_all"], true);
        assert_eq!(result.details["replacements"], 3);
    }

    #[tokio::test]
    async fn edit_creates_checkpoint_snapshot() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("checkpoint.txt");
        std::fs::write(&file, "alpha\n").unwrap();

        let tool = EditTool;
        let ctx = test_ctx(dir.path());
        let checkpoint_state = ctx.checkpoint_state.clone();

        let result = tool
            .execute(
                "c-checkpoint",
                json!({
                    "path": "checkpoint.txt",
                    "oldText": "alpha",
                    "newText": "beta"
                }),
                ctx,
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        assert_eq!(checkpoint_state.original(&file).as_deref(), Some("alpha\n"));
        assert_eq!(checkpoint_state.checkpoints().len(), 1);
    }

    #[tokio::test]
    async fn edit_fuzzy_trailing_whitespace() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("ws.txt");
        // File has trailing spaces on lines
        std::fs::write(&file, "hello   \nworld   \n").unwrap();

        let tool = EditTool;
        let result = tool
            .execute(
                "c2",
                json!({
                    "path": "ws.txt",
                    "oldText": "hello\nworld",
                    "newText": "goodbye\nuniverse"
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(!result.is_error, "Expected success but got error");
        let written = std::fs::read_to_string(&file).unwrap();
        assert!(written.contains("goodbye"));
    }

    #[tokio::test]
    async fn edit_fuzzy_unicode_quotes() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("uni.txt");
        // File has smart quotes
        std::fs::write(&file, "he said \u{201C}hello\u{201D}\n").unwrap();

        let tool = EditTool;
        let result = tool
            .execute(
                "c3",
                json!({
                    "path": "uni.txt",
                    "oldText": "he said \"hello\"",
                    "newText": "she said \"bye\""
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(!result.is_error, "Expected success but got error");
        let written = std::fs::read_to_string(&file).unwrap();
        assert!(written.contains("bye"));
    }

    #[tokio::test]
    async fn edit_crlf_preserved() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("crlf.txt");
        std::fs::write(&file, "line1\r\nline2\r\nline3\r\n").unwrap();

        let tool = EditTool;
        let result = tool
            .execute(
                "c5",
                json!({
                    "path": "crlf.txt",
                    "oldText": "line2",
                    "newText": "replaced"
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        let written = std::fs::read_to_string(&file).unwrap();
        assert!(written.contains("replaced"));
        // CRLF line endings should be preserved
        assert!(written.contains("\r\n"));
        assert!(!written.contains("line2"));
    }

    #[tokio::test]
    async fn edit_replaces_first_occurrence_only() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("multi.txt");
        std::fs::write(&file, "foo bar foo baz foo\n").unwrap();

        let tool = EditTool;
        let result = tool
            .execute(
                "c6",
                json!({
                    "path": "multi.txt",
                    "oldText": "foo",
                    "newText": "REPLACED"
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        let written = std::fs::read_to_string(&file).unwrap();
        // Should replace only the first occurrence
        assert_eq!(written, "REPLACED bar foo baz foo\n");
    }

    #[tokio::test]
    async fn edit_empty_old_text_error() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("empty.txt");
        std::fs::write(&file, "some content\n").unwrap();

        let tool = EditTool;
        let result = tool
            .execute(
                "c7",
                json!({
                    "path": "empty.txt",
                    "oldText": "",
                    "newText": "replacement"
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(result.is_error);
        let text = result
            .content
            .iter()
            .find_map(|b| match b {
                imp_llm::ContentBlock::Text { text } => Some(text.as_str()),
                _ => None,
            })
            .unwrap();
        assert!(text.contains("oldText"));
    }

    #[tokio::test]
    async fn edit_nonexistent_file_error() {
        let dir = tempfile::tempdir().unwrap();

        let tool = EditTool;
        let result = tool
            .execute(
                "c8",
                json!({
                    "path": "does_not_exist.txt",
                    "oldText": "hello",
                    "newText": "world"
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(result.is_error);
        let text = result
            .content
            .iter()
            .find_map(|b| match b {
                imp_llm::ContentBlock::Text { text } => Some(text.as_str()),
                _ => None,
            })
            .unwrap();
        assert!(text.contains("File not found"));
    }

    #[tokio::test]
    async fn edit_missing_path_error() {
        let dir = tempfile::tempdir().unwrap();

        let tool = EditTool;
        let result = tool
            .execute(
                "c9",
                json!({
                    "oldText": "hello",
                    "newText": "world"
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(result.is_error);
        let text = result
            .content
            .iter()
            .find_map(|b| match b {
                imp_llm::ContentBlock::Text { text } => Some(text.as_str()),
                _ => None,
            })
            .unwrap();
        assert!(text.contains("path"));
    }

    #[tokio::test]
    async fn edit_warns_on_unread_file() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("unread.txt");
        std::fs::write(&file, "original content here\n").unwrap();

        // Use a fresh tracker (file never read)
        let tool = EditTool;
        let result = tool
            .execute(
                "c10",
                json!({
                    "path": "unread.txt",
                    "oldText": "original content",
                    "newText": "changed content"
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(
            !result.is_error,
            "edit should succeed even without prior read"
        );
        let text = result
            .content
            .iter()
            .find_map(|b| match b {
                imp_llm::ContentBlock::Text { text } => Some(text.as_str()),
                _ => None,
            })
            .unwrap();
        assert!(
            text.contains("Warning"),
            "expected unread-file warning in output, got: {text}"
        );
    }

    #[tokio::test]
    async fn anchored_edit_replaces_validated_range_and_checkpoints() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("anchored.txt");
        std::fs::write(&file, "alpha\nbeta\ngamma\n").unwrap();
        let ctx = test_ctx(dir.path());
        let lines = ["beta"];
        let anchors = ctx.anchor_store.record_lines(
            &file,
            super::super::stable_hash("alpha\nbeta\ngamma\n"),
            2,
            &lines,
        );

        let result = EditTool
            .execute(
                "c-anchor",
                json!({
                    "path": "anchored.txt",
                    "anchorStart": anchors[0].id,
                    "replacement": "BETA",
                }),
                ctx.clone(),
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        assert_eq!(
            std::fs::read_to_string(&file).unwrap(),
            "alpha\nBETA\ngamma\n"
        );
        assert_eq!(
            ctx.checkpoint_state.original(&file).as_deref(),
            Some("alpha\nbeta\ngamma\n")
        );
        assert_eq!(result.details["anchored"], true);
    }

    #[tokio::test]
    async fn anchored_edit_rejects_stale_anchor_without_writing() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("stale.txt");
        std::fs::write(&file, "alpha\nbeta\ngamma\n").unwrap();
        let ctx = test_ctx(dir.path());
        let lines = ["beta"];
        let anchors = ctx.anchor_store.record_lines(
            &file,
            super::super::stable_hash("alpha\nbeta\ngamma\n"),
            2,
            &lines,
        );
        std::fs::write(&file, "alpha\nchanged\ngamma\n").unwrap();

        let result = EditTool
            .execute(
                "c-anchor-stale",
                json!({
                    "path": "stale.txt",
                    "anchorStart": anchors[0].id,
                    "replacement": "BETA",
                }),
                ctx,
            )
            .await
            .unwrap();

        assert!(result.is_error);
        assert!(result.text_content().unwrap().contains("Stale anchor"));
        assert_eq!(
            std::fs::read_to_string(&file).unwrap(),
            "alpha\nchanged\ngamma\n"
        );
    }

    #[tokio::test]
    async fn anchored_edit_dry_run_does_not_write() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("dry-anchor.txt");
        std::fs::write(&file, "alpha\nbeta\n").unwrap();
        let ctx = test_ctx(dir.path());
        let lines = ["beta"];
        let anchors = ctx.anchor_store.record_lines(
            &file,
            super::super::stable_hash("alpha\nbeta\n"),
            2,
            &lines,
        );

        let result = EditTool
            .execute(
                "c-anchor-dry",
                json!({
                    "path": "dry-anchor.txt",
                    "anchorStart": anchors[0].id,
                    "replacement": "BETA",
                    "dryRun": true,
                }),
                ctx.clone(),
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "alpha\nbeta\n");
        assert!(ctx.checkpoint_state.checkpoints().is_empty());
        assert!(result.text_content().unwrap().contains("dry run"));
    }

    #[tokio::test]
    async fn edit_with_edits_uses_transaction_path() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("transaction.txt");
        std::fs::write(&file, "alpha\nbeta\n").unwrap();

        let result = EditTool
            .execute(
                "c-transaction",
                json!({
                    "path": "transaction.txt",
                    "edits": [
                        {"oldText": "alpha", "newText": "ALPHA"},
                        {"oldText": "beta", "newText": "BETA"}
                    ]
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "ALPHA\nBETA\n");
        assert_eq!(result.details["transaction"], true);
        assert_eq!(result.details["edit_count"], 2);
    }

    #[tokio::test]
    async fn edit_no_match_error() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("nope.txt");
        std::fs::write(&file, "some content here\n").unwrap();

        let tool = EditTool;
        let result = tool
            .execute(
                "c4",
                json!({
                    "path": "nope.txt",
                    "oldText": "this text does not exist",
                    "newText": "replacement"
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(result.is_error);
        let text = result
            .content
            .iter()
            .find_map(|b| match b {
                imp_llm::ContentBlock::Text { text } => Some(text.as_str()),
                _ => None,
            })
            .unwrap();
        assert!(text.contains("Could not find"));
    }
}