scope-engine 0.2.0

Semantic Code Operation & Propagation Engine
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
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use crate::analyzer::Analyzer;
pub use crate::api::{
    AppliedStructuredEditFile, AppliedStructuredEditOperation, AppliedStructuredEditSummary,
};
use crate::api::{EditOp, PropagationResult, PropagationSource, StructuredEdit};
use crate::treesitter::TreeSitterAnalyzer;
use sha2::{Digest, Sha256};
use std::sync::Mutex;

#[derive(Debug, Clone)]
struct PlannedEdit {
    start_line: usize,
    old_count: usize,
    replacement: Vec<String>,
    primary_symbol_name: Option<String>,
}

struct PreparedFileEdits {
    display_path: String,
    full_path: PathBuf,
    existed: bool,
    original: String,
    new_content: String,
    planned: Vec<PlannedEdit>,
}

struct PreparedStructuredEdits {
    files: Vec<PreparedFileEdits>,
}

pub fn line_hash(line_content: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(line_content.as_bytes());
    let result = hasher.finalize();
    format!("{:02x}", result[0])
}

fn parse_start_anchor(anchor: &str) -> Result<(usize, String), String> {
    let (line_str, hash_str) = anchor
        .split_once('#')
        .ok_or_else(|| format!("invalid start anchor (expected line#hash): {anchor}"))?;
    let line = line_str
        .parse::<usize>()
        .map_err(|_| format!("invalid line number in anchor: {anchor}"))?;
    if line == 0 {
        return Err(format!("line number must be >= 1 in anchor: {anchor}"));
    }
    Ok((line, hash_str.to_string()))
}

fn verify_line(content: &str, line_num: usize, expected_hash: &str) -> Result<(), String> {
    let lines: Vec<&str> = content.lines().collect();
    if line_num > lines.len() {
        return Err(format!(
            "line {line_num} out of bounds (file has {} lines)",
            lines.len()
        ));
    }
    let actual = lines[line_num - 1];
    let actual_hash = line_hash(actual);
    if actual_hash != expected_hash {
        return Err(format!(
            "line {line_num} hash mismatch: expected {expected_hash}, got {actual_hash} — file may have changed; re-read before editing"
        ));
    }
    Ok(())
}

fn apply_planned_edits_to_content(
    original: &str,
    edits: &[PlannedEdit],
    file_display: &str,
) -> Result<String, String> {
    let mut sorted: Vec<&PlannedEdit> = edits.iter().collect();
    sorted.sort_by_key(|edit| edit.start_line);
    for pair in sorted.windows(2) {
        let prev_end = pair[0].start_line + pair[0].old_count;
        if pair[1].start_line < prev_end {
            return Err(format!(
                "overlapping edits in {}: edit at line {} overlaps previous edit ending at line {}",
                file_display, pair[1].start_line, prev_end
            ));
        }
    }

    let mut lines = original.lines().map(str::to_string).collect::<Vec<_>>();
    for edit in sorted.iter().rev() {
        let start_idx = edit.start_line.saturating_sub(1);
        let end_idx = start_idx + edit.old_count;
        if start_idx > lines.len() || end_idx > lines.len() {
            return Err(format!(
                "edit exceeds file bounds in {}: lines {}-{} but file has {} lines",
                file_display,
                edit.start_line,
                edit.start_line + edit.old_count,
                lines.len()
            ));
        }
        lines.splice(start_idx..end_idx, edit.replacement.clone());
    }

    if lines.is_empty() {
        Ok(String::new())
    } else {
        Ok(lines.join("\n") + "\n")
    }
}

struct PropagationCollectionContext<'a> {
    full_path: &'a Path,
    original: &'a str,
    new_content: &'a str,
    project_root: &'a Path,
    lsp_analyzer: &'a Mutex<Option<Box<dyn Analyzer + Send>>>,
    analyzer: &'a TreeSitterAnalyzer,
}

fn collect_propagation_results(
    context: PropagationCollectionContext<'_>,
    edits: &[PlannedEdit],
) -> Vec<PropagationResult> {
    let PropagationCollectionContext {
        full_path,
        original,
        new_content,
        project_root,
        lsp_analyzer,
        analyzer,
    } = context;

    let mut results: Vec<PropagationResult> = Vec::new();
    let mut seen: HashSet<String> = HashSet::new();
    let mut modified_symbol_names = HashSet::new();

    for edit in edits {
        if let Some(ref name) = edit.primary_symbol_name {
            modified_symbol_names.insert(name.clone());
        }
        if let Some(sel) = analyzer.find_containing_symbol(full_path, edit.start_line, project_root)
            && let Ok(parsed) = crate::selector::parse_selector(&sel)
            && let Some(name) = parsed.name()
        {
            modified_symbol_names.insert(name.to_string());
        }
    }

    for sym_name in &modified_symbol_names {
        let mut lsp_refs: Vec<PropagationResult> = Vec::new();
        if let Ok(lsp_guard) = lsp_analyzer.lock()
            && let Some(ref lsp) = *lsp_guard
        {
            let (line, character) =
                find_symbol_position(new_content, sym_name).unwrap_or_else(|| {
                    let hint_line = edits.first().map(|edit| edit.start_line).unwrap_or(1);
                    (hint_line, 0)
                });
            lsp_refs = lsp.find_references_for_symbol(full_path, line, character, project_root);
        }
        if lsp_refs.is_empty() {
            let rel = normalize_for_comparison(full_path)
                .strip_prefix(normalize_for_comparison(project_root))
                .ok()
                .map(|p| p.to_string_lossy().to_string())
                .unwrap_or_else(|| full_path.to_string_lossy().to_string());
            let selector = format!("{}::{}", rel, sym_name);
            if seen.insert(selector.clone()) {
                let first_line = edits.first().map(|edit| edit.start_line).unwrap_or(1);
                let file_snippet = original
                    .lines()
                    .skip(first_line.saturating_sub(3))
                    .take(7)
                    .collect::<Vec<_>>()
                    .join("\n");
                let project_files = std::fs::read_dir(project_root)
                    .ok()
                    .map(|entries| {
                        entries
                            .filter_map(|e| e.ok())
                            .filter(|e| {
                                e.path().is_dir()
                                    && e.path().file_name().is_some_and(|n| n == "src")
                            })
                            .filter_map(|e| std::fs::read_dir(e.path()).ok())
                            .flat_map(|entries| {
                                let normalized_root = normalize_for_comparison(project_root);
                                entries.filter_map(|e| e.ok()).filter_map(move |e| {
                                    normalize_for_comparison(&e.path())
                                        .strip_prefix(&normalized_root)
                                        .ok()
                                        .map(|p| p.to_string_lossy().to_string())
                                })
                            })
                            .collect()
                    })
                    .unwrap_or_default();

                results.push(PropagationResult {
                    selector,
                    reason: format!(
                        "symbol \"{}\" was modified; no LSP available to find references",
                        sym_name
                    ),
                    source: PropagationSource::OpenEnded,
                    lsp_references: None,
                    diff_summary: Some("hash-based edit".to_string()),
                    file_snippet: Some(file_snippet),
                    project_files: Some(project_files),
                });
            }
        } else {
            for r in lsp_refs {
                if seen.insert(r.selector.clone()) {
                    results.push(r);
                }
            }
        }
    }

    results
}

fn find_symbol_position(content: &str, symbol_name: &str) -> Option<(usize, usize)> {
    content.lines().enumerate().find_map(|(line_idx, line)| {
        line.find(symbol_name)
            .map(|character| (line_idx + 1, character))
    })
}

fn normalized_edit_content(content: Option<&crate::api::EditContent>) -> Option<Vec<String>> {
    content.map(|c| c.clone().into_lines())
}

pub fn edit_code_apply(
    edits: &[StructuredEdit],
    project_root: &Path,
    lsp_analyzer: &Mutex<Option<Box<dyn Analyzer + Send>>>,
) -> Result<(Vec<PropagationResult>, AppliedStructuredEditSummary), String> {
    let analyzer = TreeSitterAnalyzer::new();
    let prepared = prepare_structured_edits(edits, project_root, &analyzer, true)?;
    let applied_summary = applied_summary_from_prepared(&prepared);
    write_prepared_structured_edits(&prepared, Some(lsp_analyzer))?;

    let mut results = Vec::new();
    for file in &prepared.files {
        results.extend(collect_propagation_results(
            PropagationCollectionContext {
                full_path: &file.full_path,
                original: &file.original,
                new_content: &file.new_content,
                project_root,
                lsp_analyzer,
                analyzer: &analyzer,
            },
            &file.planned,
        ));
    }

    Ok((results, applied_summary))
}

pub fn edit_file_apply(
    edits: &[StructuredEdit],
    project_root: &Path,
) -> Result<AppliedStructuredEditSummary, String> {
    let analyzer = TreeSitterAnalyzer::new();
    let prepared = prepare_structured_edits(edits, project_root, &analyzer, false)?;
    write_prepared_structured_edits(&prepared, None)?;
    Ok(applied_summary_from_prepared(&prepared))
}

fn prepare_structured_edits(
    edits: &[StructuredEdit],
    project_root: &Path,
    analyzer: &TreeSitterAnalyzer,
    validate_parse: bool,
) -> Result<PreparedStructuredEdits, String> {
    if edits.is_empty() {
        return Err("edits array is empty".to_string());
    }

    struct EditGroup<'a> {
        display_path: String,
        edits: Vec<&'a StructuredEdit>,
    }

    let mut edits_by_file: HashMap<PathBuf, EditGroup<'_>> = HashMap::new();
    for edit in edits {
        let full_path = if std::path::Path::new(&edit.path).is_absolute() {
            PathBuf::from(&edit.path)
        } else {
            project_root.join(&edit.path)
        };
        let display_path = display_path_for_edit(project_root, &full_path);
        edits_by_file
            .entry(full_path)
            .and_modify(|group| group.edits.push(edit))
            .or_insert_with(|| EditGroup {
                display_path,
                edits: vec![edit],
            });
    }

    let mut prepared_files = Vec::new();

    for (full_path, group) in edits_by_file {
        let existed = full_path.exists();
        let original = if existed {
            std::fs::read_to_string(&full_path)
                .map_err(|e| format!("cannot read {}: {e}", full_path.display()))?
        } else {
            // New file creation: only line-1 operations are valid (no
            // existing content to anchor against).  Replace at line 1 is
            // accepted and treated equivalently to Append.
            for e in &group.edits {
                let start_valid = match &e.start {
                    Some(start) => start == "1#" || start.starts_with("1#"),
                    None => true,
                };
                if !start_valid {
                    return Err(format!(
                        "cannot create new file {}: start anchor must be `1#`",
                        full_path.display()
                    ));
                }
            }
            String::new()
        };

        let mut planned: Vec<PlannedEdit> = Vec::new();

        for edit in group.edits {
            // Resolve op: default to Append for new files, required for existing
            let op = match edit.op.clone() {
                Some(op) if original.is_empty() && op == EditOp::Replace => EditOp::Append,
                Some(op) => op,
                None if original.is_empty() => EditOp::Append,
                None => {
                    return Err(format!(
                        "op is required for editing existing file {}",
                        edit.path
                    ));
                }
            };

            // Resolve start anchor: default to "1#" for new files, required for existing
            let start = match &edit.start {
                Some(s) => s.clone(),
                None if original.is_empty() => "1#".to_string(),
                None => {
                    return Err(format!(
                        "start anchor is required for editing existing file {}",
                        edit.path
                    ));
                }
            };

            let (start_line, start_hash) = parse_start_anchor(&start)?;

            if !original.is_empty() {
                verify_line(&original, start_line, &start_hash)?;
            }

            let mut primary_symbol_name = None;
            if validate_parse
                && !original.is_empty()
                && let Some(sel) =
                    analyzer.find_containing_symbol(&full_path, start_line, project_root)
                && let Ok(parsed) = crate::selector::parse_selector(&sel)
            {
                primary_symbol_name = parsed.name().map(str::to_string);
            }

            match op {
                EditOp::Replace => {
                    let (end_line, end_hash) = match &edit.end {
                        Some(end_anchor) => parse_start_anchor(end_anchor)?,
                        None => {
                            return Err(format!("replace requires `end` anchor for {}", edit.path));
                        }
                    };
                    if end_line < start_line {
                        return Err(format!(
                            "replace end line {} is before start line {} in {}",
                            end_line, start_line, edit.path
                        ));
                    }
                    if !original.is_empty() {
                        verify_line(&original, end_line, &end_hash)?;
                    }
                    let old_count = end_line - start_line + 1;
                    let replacement =
                        normalized_edit_content(edit.content.as_ref()).unwrap_or_default();
                    planned.push(PlannedEdit {
                        start_line,
                        old_count,
                        replacement,
                        primary_symbol_name,
                    });
                }
                EditOp::Append => {
                    let replacement =
                        normalized_edit_content(edit.content.as_ref()).unwrap_or_default();
                    let insert_line = if original.is_empty() {
                        1
                    } else {
                        start_line + 1
                    };
                    planned.push(PlannedEdit {
                        start_line: insert_line,
                        old_count: 0,
                        replacement,
                        primary_symbol_name,
                    });
                }
                EditOp::Prepend => {
                    let replacement =
                        normalized_edit_content(edit.content.as_ref()).unwrap_or_default();
                    let insert_line = if original.is_empty() { 1 } else { start_line };
                    planned.push(PlannedEdit {
                        start_line: insert_line,
                        old_count: 0,
                        replacement,
                        primary_symbol_name,
                    });
                }
            }
        }

        let new_content =
            apply_planned_edits_to_content(&original, &planned, &full_path.to_string_lossy())?;

        let ext = full_path.extension().and_then(|e| e.to_str()).unwrap_or("");
        if validate_parse
            && !ext.is_empty()
            && !new_content.is_empty()
            && let Some(diagnostic) = analyzer.parse_error_diagnostic(ext, &new_content)
        {
            return Err(format!(
                "edit rejected: tree-sitter cannot parse the result for {}\n{}",
                full_path.display(),
                diagnostic.message()
            ));
        }

        prepared_files.push(PreparedFileEdits {
            display_path: group.display_path,
            full_path,
            existed,
            original,
            new_content,
            planned,
        });
    }

    Ok(PreparedStructuredEdits {
        files: prepared_files,
    })
}

fn write_prepared_structured_edits(
    prepared: &PreparedStructuredEdits,
    lsp_analyzer: Option<&Mutex<Option<Box<dyn Analyzer + Send>>>>,
) -> Result<(), String> {
    for file in &prepared.files {
        if let Some(parent) = file.full_path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                format!(
                    "cannot create parent dirs for {}: {e}",
                    file.full_path.display()
                )
            })?;
        }
        std::fs::write(&file.full_path, &file.new_content)
            .map_err(|e| format!("cannot write {}: {e}", file.full_path.display()))?;
        if let Some(lsp_analyzer) = lsp_analyzer
            && let Ok(lsp_guard) = lsp_analyzer.lock()
            && let Some(ref lsp) = *lsp_guard
        {
            lsp.notify_did_change(&file.full_path, 1, &file.new_content);
        }
    }
    Ok(())
}

fn applied_summary_from_prepared(
    prepared: &PreparedStructuredEdits,
) -> AppliedStructuredEditSummary {
    let files = prepared
        .files
        .iter()
        .map(|file| {
            let added_lines = file.planned.iter().map(|edit| edit.replacement.len()).sum();
            let removed_lines = file.planned.iter().map(|edit| edit.old_count).sum();
            AppliedStructuredEditFile {
                path: file.display_path.clone(),
                operation: if file.existed {
                    AppliedStructuredEditOperation::Update
                } else {
                    AppliedStructuredEditOperation::Add
                },
                added_lines,
                removed_lines,
                original_content: file.original.clone(),
                new_content: file.new_content.clone(),
            }
        })
        .collect();
    AppliedStructuredEditSummary { files }
}

fn display_path_for_edit(project_root: &Path, full_path: &Path) -> String {
    let normalized_root = normalize_for_comparison(project_root);
    let normalized_path = normalize_for_comparison(full_path);
    if let Ok(relative) = normalized_path.strip_prefix(&normalized_root) {
        let relative = relative.to_string_lossy().replace('\\', "/");
        if !relative.is_empty() {
            return relative;
        }
    }
    full_path.to_string_lossy().replace('\\', "/")
}

fn normalize_for_comparison(p: &Path) -> PathBuf {
    let s = p.to_string_lossy();
    if let Some(rest) = s.strip_prefix(r"\\?\") {
        PathBuf::from(rest)
    } else {
        p.to_path_buf()
    }
}

#[cfg(test)]
mod e2e_tests {
    use super::*;
    use crate::api;
    use std::io::Write;
    use std::path::PathBuf;

    fn setup_temp_rust_project() -> tempfile::TempDir {
        tempfile::tempdir().unwrap()
    }

    fn write_rust_file(dir: &Path, filename: &str, content: &str) -> (PathBuf, Vec<String>) {
        let src_dir = dir.join("src");
        std::fs::create_dir_all(&src_dir).unwrap();
        let path = src_dir.join(filename);
        let mut f = std::fs::File::create(&path).unwrap();
        f.write_all(content.as_bytes()).unwrap();

        let hashes: Vec<String> = content
            .lines()
            .enumerate()
            .map(|(i, line)| format!("{}#{}", i + 1, line_hash(line)))
            .collect();

        (path, hashes)
    }

    #[test]
    fn replace_with_hashes() {
        let dir = setup_temp_rust_project();
        let rust_code = "pub fn hello() {\n    println!(\"hello\");\n}\n\npub fn world() {\n    println!(\"world\");\n}\n";
        let (_, hashes) = write_rust_file(dir.path(), "lib.rs", rust_code);

        let edits = vec![api::StructuredEdit {
            path: "src/lib.rs".to_string(),
            op: Some(api::EditOp::Replace),
            start: Some(hashes[0].clone()),
            end: Some(hashes[2].clone()),
            content: Some(api::EditContent::Lines(vec![
                "pub fn hello() {".to_string(),
                "    println!(\"hello world\");".to_string(),
                "}".to_string(),
            ])),
        }];
        let lsp: Mutex<Option<Box<dyn Analyzer + Send>>> = Mutex::new(None);
        let (propagation, applied_summary) = edit_code_apply(&edits, dir.path(), &lsp).unwrap();
        assert!(!propagation.is_empty(), "Should have propagation results");
        assert_eq!(applied_summary.files.len(), 1);
        assert_eq!(applied_summary.files[0].path, "src/lib.rs");
        assert_eq!(applied_summary.files[0].added_lines, 3);
        assert_eq!(applied_summary.files[0].removed_lines, 3);
        assert!(
            applied_summary.files[0]
                .original_content
                .contains("\"hello\"")
        );
        assert!(applied_summary.files[0].new_content.contains("hello world"));

        let modified = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
        assert!(modified.contains("hello world"));
        assert!(!modified.contains("\"hello\""));
    }

    #[test]
    fn append_and_replace_delete() {
        let dir = setup_temp_rust_project();
        let rust_code = "pub fn keep() {\n    println!(\"keep\");\n}\n\npub fn remove_me() {\n    println!(\"remove\");\n}\n";
        let (_, hashes) = write_rust_file(dir.path(), "lib.rs", rust_code);
        // Line 1: "pub fn keep() {" -> hashes[0]
        // Line 5: "pub fn remove_me() {" -> hashes[4]
        // Line 7: "}" -> hashes[6]

        let edits = vec![
            api::StructuredEdit {
                path: "src/lib.rs".to_string(),
                op: Some(api::EditOp::Append),
                start: Some(hashes[0].clone()),
                end: None,
                content: Some(api::EditContent::Lines(vec![
                    "pub fn added() {".to_string(),
                    "    println!(\"added\");".to_string(),
                    "}".to_string(),
                    "".to_string(),
                ])),
            },
            api::StructuredEdit {
                path: "src/lib.rs".to_string(),
                op: Some(api::EditOp::Replace),
                start: Some(hashes[4].clone()),
                end: Some(hashes[6].clone()),
                content: None, // delete
            },
        ];
        let lsp: Mutex<Option<Box<dyn Analyzer + Send>>> = Mutex::new(None);
        let (_propagation, applied_summary) = edit_code_apply(&edits, dir.path(), &lsp).unwrap();
        assert_eq!(applied_summary.files.len(), 1);
        assert_eq!(applied_summary.files[0].added_lines, 4);
        assert_eq!(applied_summary.files[0].removed_lines, 3);

        let modified = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
        assert!(modified.contains("pub fn added()"));
        assert!(modified.contains("pub fn keep()"));
        assert!(!modified.contains("remove_me"));
    }

    #[test]
    fn creates_new_file() {
        let dir = setup_temp_rust_project();
        std::fs::create_dir_all(dir.path().join("src")).unwrap();

        let edits = vec![api::StructuredEdit {
            path: "src/new_file.rs".to_string(),
            op: Some(api::EditOp::Append),
            start: Some("1#00".to_string()),
            end: None,
            content: Some(api::EditContent::Lines(vec![
                "pub fn created() {".to_string(),
                "    println!(\"created\");".to_string(),
                "}".to_string(),
            ])),
        }];
        let lsp: Mutex<Option<Box<dyn Analyzer + Send>>> = Mutex::new(None);
        let result = edit_code_apply(&edits, dir.path(), &lsp);
        assert!(
            result.is_ok(),
            "new file creation should succeed: {result:?}"
        );
        let (_propagation, applied_summary) = result.unwrap();
        assert_eq!(applied_summary.files.len(), 1);
        assert_eq!(
            applied_summary.files[0].operation,
            AppliedStructuredEditOperation::Add
        );
        assert_eq!(applied_summary.files[0].added_lines, 3);
        assert_eq!(applied_summary.files[0].removed_lines, 0);

        let created = std::fs::read_to_string(dir.path().join("src/new_file.rs")).unwrap();
        assert!(created.contains("pub fn created()"));
    }

    #[test]
    fn hash_mismatch_rejects_edit() {
        let dir = setup_temp_rust_project();
        let rust_code = "pub fn hello() {\n    println!(\"hello\");\n}\n";
        write_rust_file(dir.path(), "lib.rs", rust_code);

        let edits = vec![api::StructuredEdit {
            path: "src/lib.rs".to_string(),
            op: Some(api::EditOp::Replace),
            start: Some("1#ff".to_string()), // wrong hash
            end: Some("3#ff".to_string()),   // wrong hash
            content: Some(api::EditContent::Text(
                "pub fn hello() {\n    println!(\"goodbye\");\n}\n".to_string(),
            )),
        }];
        let lsp: Mutex<Option<Box<dyn Analyzer + Send>>> = Mutex::new(None);
        let err = edit_code_apply(&edits, dir.path(), &lsp).unwrap_err();
        assert!(
            err.contains("hash mismatch"),
            "expected hash mismatch, got: {err}"
        );

        let unchanged = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
        assert_eq!(unchanged, rust_code);
    }

    #[test]
    fn parse_rejection_reports_tree_sitter_error_location() {
        let dir = setup_temp_rust_project();
        let rust_code = "pub fn hello() {\n    println!(\"hello\");\n}\n";
        let (_, hashes) = write_rust_file(dir.path(), "lib.rs", rust_code);

        let edits = vec![api::StructuredEdit {
            path: "src/lib.rs".to_string(),
            op: Some(api::EditOp::Replace),
            start: Some(hashes[0].clone()),
            end: Some(hashes[2].clone()),
            content: Some(api::EditContent::Lines(vec![
                "pub fn hello() {".to_string(),
                "    println!(\"hello\");".to_string(),
            ])),
        }];
        let lsp: Mutex<Option<Box<dyn Analyzer + Send>>> = Mutex::new(None);
        let err = edit_code_apply(&edits, dir.path(), &lsp).unwrap_err();

        assert!(err.contains("tree-sitter cannot parse the result"));
        assert!(err.contains("src\\lib.rs") || err.contains("src/lib.rs"));
        assert!(err.contains("first parse error:"));
        assert!(err.contains("L"));
        assert!(err.contains("C"));
        assert!(err.contains("println!"));
        assert!(err.contains('^'));

        let unchanged = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
        assert_eq!(unchanged, rust_code);
    }

    #[test]
    fn rejects_empty_edits() {
        let dir = setup_temp_rust_project();
        let lsp: Mutex<Option<Box<dyn Analyzer + Send>>> = Mutex::new(None);
        let err = edit_code_apply(&[], dir.path(), &lsp).unwrap_err();
        assert!(err.contains("empty"));
    }

    #[test]
    fn replace_requires_end() {
        let dir = setup_temp_rust_project();
        let rust_code = "pub fn hello() {\n    println!(\"hello\");\n}\n";
        let (_, hashes) = write_rust_file(dir.path(), "lib.rs", rust_code);

        let edits = vec![api::StructuredEdit {
            path: "src/lib.rs".to_string(),
            op: Some(api::EditOp::Replace),
            start: Some(hashes[0].clone()),
            end: None, // missing end
            content: Some(api::EditContent::Text("replaced".to_string())),
        }];
        let lsp: Mutex<Option<Box<dyn Analyzer + Send>>> = Mutex::new(None);
        let err = edit_code_apply(&edits, dir.path(), &lsp).unwrap_err();
        assert!(err.contains("requires `end`"));
    }
}