newt-tools 0.8.0

Newt-Agent file/code tool surface — read, edit, search, apply-patch
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
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
//! Unified-diff parser and applier.
//!
//! Parses `--- a/…` / `+++ b/…` headers and `@@ -X,Y +X,Y @@` hunk headers,
//! then applies context/add/remove lines to produce the patched file.
//! Writes atomically via temp-file-then-rename.

use std::path::Path;

// ── Data model ──────────────────────────────────────────────────────────────

#[derive(Debug)]
struct FilePatch {
    path: String,
    hunks: Vec<Hunk>,
}

#[derive(Debug)]
struct Hunk {
    old_start: usize,
    lines: Vec<DiffLine>,
}

#[derive(Debug, Clone)]
enum DiffLine {
    Context(String),
    Add(String),
    Remove(String),
}

// ── Pluggable applier backends ───────────────────────────────────────────────

/// A patch-application backend.
///
/// The default is [`FuzzyApplier`] — the in-house unified-diff parser with
/// `git apply -C`-style fuzzy hunk location (tolerant of the off-by-N line
/// numbers and whitespace drift weak local models emit, while still
/// rejecting genuinely-wrong and ambiguous hunks). It is the backend the
/// worker-agent bake-off validated, so it stays the default.
///
/// Alternative backends select at runtime via `NEWT_PATCH_APPLIER`:
///
/// - `fuzzy` (default) — [`FuzzyApplier`].
/// - `diffy` — [`DiffyApplier`], the strict pure-Rust `diffy` crate.
///   Requires the `applier-diffy` cargo feature; without it,
///   `NEWT_PATCH_APPLIER=diffy` warns and falls back to fuzzy.
///
/// Future backends are just more `impl PatchApplier`: a `gix` (gitoxide)
/// applier once `gix-apply` publishes, or a content-addressed
/// applier. The seam exists so the choice of *how* a patch is applied is a
/// swappable instrument, not baked into every call site.
pub trait PatchApplier: Send + Sync {
    /// Validate and apply `diff` rooted at `root`. All-or-nothing: a
    /// multi-file diff either applies fully or leaves the tree untouched.
    fn apply(&self, root: &Path, diff: &str) -> anyhow::Result<()>;
    /// Short stable name for logs/diagnostics (`"fuzzy"`, `"diffy"`).
    fn name(&self) -> &'static str;
}

/// The default in-house fuzzy applier (see [`PatchApplier`]).
pub struct FuzzyApplier;

impl PatchApplier for FuzzyApplier {
    fn apply(&self, root: &Path, diff: &str) -> anyhow::Result<()> {
        fuzzy_apply_patch(root, diff)
    }
    fn name(&self) -> &'static str {
        "fuzzy"
    }
}

/// Strict `diffy`-backed applier. Only compiled with the `applier-diffy`
/// feature; selectable at runtime via `NEWT_PATCH_APPLIER=diffy`.
#[cfg(feature = "applier-diffy")]
pub struct DiffyApplier;

#[cfg(feature = "applier-diffy")]
impl PatchApplier for DiffyApplier {
    fn apply(&self, root: &Path, diff: &str) -> anyhow::Result<()> {
        diffy_apply_patch(root, diff)
    }
    fn name(&self) -> &'static str {
        "diffy"
    }
}

/// Select the applier backend from the `NEWT_PATCH_APPLIER` env var,
/// defaulting to [`FuzzyApplier`].
pub fn applier_from_env() -> Box<dyn PatchApplier> {
    match std::env::var("NEWT_PATCH_APPLIER").ok().as_deref() {
        Some("diffy") => diffy_applier(),
        Some("fuzzy") | None => Box::new(FuzzyApplier),
        Some(other) => {
            tracing::warn!(applier = %other, "unknown NEWT_PATCH_APPLIER; using fuzzy");
            Box::new(FuzzyApplier)
        }
    }
}

#[cfg(feature = "applier-diffy")]
fn diffy_applier() -> Box<dyn PatchApplier> {
    Box::new(DiffyApplier)
}

#[cfg(not(feature = "applier-diffy"))]
fn diffy_applier() -> Box<dyn PatchApplier> {
    tracing::warn!(
        "NEWT_PATCH_APPLIER=diffy requested but the `applier-diffy` feature is \
         not compiled in; falling back to the fuzzy applier"
    );
    Box::new(FuzzyApplier)
}

// ── Public API ──────────────────────────────────────────────────────────────

/// Apply a unified diff to files under `root` using the
/// [`applier_from_env`]-selected backend (fuzzy by default).
///
/// Each file referenced in the diff is resolved relative to `root`.
/// New files are created if they don't exist. Writes are atomic
/// (write to `.newt-tmp`, then rename).
///
/// # Errors
///
/// - Malformed diff (missing headers, bad hunk header syntax).
/// - Context mismatch (the file doesn't match what the diff expects).
/// - I/O errors on read/write.
pub fn apply_patch(root: &Path, diff: &str) -> anyhow::Result<()> {
    applier_from_env().apply(root, diff)
}

/// Reject a candidate write target that would escape the workspace root.
///
/// The model (or a repo-supplied diff) controls the destination path, so a
/// `..` (`ParentDir`), an absolute root (`RootDir`), or a Windows drive
/// (`Prefix`) component would make the subsequent `root.join(rel)` land
/// **outside** the fence — a `Scope::All` `fs_write` caveat does not stop it,
/// and the `exec` caveat never sees the resulting cron / `authorized_keys` /
/// git-hook drop-in (step-4.1, deviation `acp-worker-fs-scope`, issue #522).
/// Checked by COMPONENTS, not `is_absolute()`: on Windows `/etc/passwd` is
/// root-relative and `is_absolute()` is `false`, so a component check is the
/// only guard correct on every platform. Ports the proven crew boundary
/// (`newt-cli/src/crew.rs::is_safe_worktree_path`) to the shared write
/// primitives so both the whole-files and unified-diff paths are contained at
/// their one shared owner.
fn is_workspace_contained(rel: &Path) -> bool {
    use std::path::Component;
    rel.components()
        .all(|c| matches!(c, Component::Normal(_) | Component::CurDir))
}

/// Uniform refusal for an escaping write target — shared wording so both
/// primitives fail the same way and callers can classify it as a capability
/// denial.
fn escape_error(rel: &Path) -> anyhow::Error {
    anyhow::anyhow!(
        "refusing to write '{}': path escapes the workspace (absolute or `..` component)",
        rel.display()
    )
}

/// Object-bound atomic write of `content` to `rel` beneath `workspace` — the one
/// owner of the applier backends' write step. On Linux the target is resolved
/// through the workspace root fd (`openat2 RESOLVE_BENEATH`), so a symlink *under*
/// the workspace cannot redirect the write outside it — closing the residual the
/// lexical [`is_workspace_contained`] leaves open (#522). Missing parents are
/// created; a sibling temp is written then renamed (partial-write safety). The
/// non-Linux fallback keeps the lexical-gate + `std::fs` temp-then-rename path.
#[cfg(target_os = "linux")]
fn write_contained(workspace: &Path, rel: &str, content: &[u8]) -> anyhow::Result<()> {
    use newt_core::fs_cap::WorkspaceDir;
    use std::io::Write;
    let rel_path = Path::new(rel);
    let dir = WorkspaceDir::open_root(workspace)?;
    if let Some(parent) = rel_path.parent() {
        if !parent.as_os_str().is_empty() {
            dir.create_dir_all(parent)?;
        }
    }
    let tmp_rel = sibling_tmp(rel_path);
    {
        let mut f = dir.create(&tmp_rel)?;
        f.write_all(content)?;
    }
    dir.rename(&tmp_rel, rel_path)?;
    Ok(())
}

#[cfg(not(target_os = "linux"))]
fn write_contained(workspace: &Path, rel: &str, content: &[u8]) -> anyhow::Result<()> {
    let abs = workspace.join(rel);
    if let Some(parent) = abs.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let tmp = abs.with_extension("newt-tmp");
    std::fs::write(&tmp, content)?;
    std::fs::rename(&tmp, &abs)?;
    Ok(())
}

/// Object-bound read of `rel`'s current contents beneath `workspace` for a
/// patch/whole-file apply — `None` if the file does not exist (a fresh create).
/// A symlink-escape path is refused (not silently read from outside). Linux-only
/// object-binding; non-Linux keeps `std::fs`.
#[cfg(target_os = "linux")]
fn read_contained_opt(workspace: &Path, rel: &str) -> anyhow::Result<Option<String>> {
    use newt_core::fs_cap::WorkspaceDir;
    use std::io::Read;
    let dir = WorkspaceDir::open_root(workspace)?;
    match dir.open(Path::new(rel)) {
        Ok(mut f) => {
            let mut s = String::new();
            f.read_to_string(&mut s)?;
            Ok(Some(s))
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(e.into()),
    }
}

#[cfg(not(target_os = "linux"))]
fn read_contained_opt(workspace: &Path, rel: &str) -> anyhow::Result<Option<String>> {
    let abs = workspace.join(rel);
    if abs.exists() {
        Ok(Some(std::fs::read_to_string(&abs)?))
    } else {
        Ok(None)
    }
}

/// A sibling temp path in the *same* parent as `rel` (so the atomic rename stays
/// within one contained directory): `<parent>/<name>.newt-tmp`.
#[cfg(target_os = "linux")]
fn sibling_tmp(rel: &Path) -> std::path::PathBuf {
    let mut name = rel
        .file_name()
        .unwrap_or_else(|| std::ffi::OsStr::new("newt"))
        .to_os_string();
    name.push(".newt-tmp");
    match rel.parent() {
        Some(p) if !p.as_os_str().is_empty() => p.join(name),
        _ => std::path::PathBuf::from(name),
    }
}

/// The in-house fuzzy applier implementation (the default backend).
fn fuzzy_apply_patch(root: &Path, diff: &str) -> anyhow::Result<()> {
    let patches = parse_unified_diff(diff)?;

    if patches.is_empty() {
        anyhow::bail!("no file patches found in diff");
    }

    // Validate all patches first so we don't partially apply.
    let mut results: Vec<(String, String)> = Vec::new();

    for patch in &patches {
        if !is_workspace_contained(Path::new(&patch.path)) {
            return Err(escape_error(Path::new(&patch.path)));
        }
        // Object-bound read of the original (a symlink-escape path is refused,
        // not read from outside); absent file → fresh create.
        let original = read_contained_opt(root, &patch.path)?.unwrap_or_default();
        let result = apply_hunks(&original, &patch.hunks)?;
        results.push((patch.path.clone(), result));
    }

    // All patches validated — now write atomically, object-bound.
    for (rel, content) in &results {
        write_contained(root, rel, content.as_bytes())?;
    }

    Ok(())
}

/// Convenience wrapper: apply a patch scoped to a single file's parent.
pub fn edit(path: &Path, patch: &str) -> anyhow::Result<()> {
    let root = path.parent().unwrap_or(Path::new("."));
    apply_patch(root, patch)
}

/// Write a set of whole files into `workspace` atomically.
///
/// For each `(relative_path, contents)` entry: create parent
/// directories as needed, write to `<file>.newt-coder-tmp`, then
/// rename into place. Returns the list of relative paths actually
/// written so the caller can log them and (after writing) capture
/// the diff via `git diff`.
///
/// This is the multi-file landing pad for the newt-coder plugin's
/// `Emission::WholeFiles` shape. Kept here (rather than inline in
/// newt-coder) so any other caller that produces a set of whole
/// files (test harnesses, future strategies) can share the atomic
/// write semantics.
///
/// # Errors
///
/// - `create_dir_all` failure on a parent directory.
/// - `write` failure on the temp file.
/// - `rename` failure when moving temp -> final.
pub fn apply_whole_files<P, M, S, T>(workspace: P, files: M) -> anyhow::Result<Vec<String>>
where
    P: AsRef<Path>,
    M: IntoIterator<Item = (S, T)>,
    S: Into<String>,
    T: AsRef<str>,
{
    let workspace = workspace.as_ref();
    let mut written = Vec::new();
    for (rel, contents) in files {
        let rel = rel.into();
        // Contain the attacker-controlled path BEFORE the join (step-4.1); the
        // object-bound write (step-52.7) then also refuses a symlink escape.
        if !is_workspace_contained(Path::new(&rel)) {
            return Err(escape_error(Path::new(&rel)));
        }
        write_contained(workspace, &rel, contents.as_ref().as_bytes())?;
        written.push(rel);
    }
    Ok(written)
}

// ── Strict `diffy` backend (feature = "applier-diffy") ───────────────────────

/// Strict applier built on the `diffy` crate. Splits a (possibly
/// multi-file) unified diff into per-file sections and applies each with
/// `diffy::apply`. Validates every file before writing (atomic
/// temp-then-rename), matching the fuzzy applier's all-or-nothing
/// semantics. Unlike the fuzzy backend, `diffy` is strict about hunk
/// headers/context — the point of offering it as an option.
#[cfg(feature = "applier-diffy")]
fn diffy_apply_patch(root: &Path, diff: &str) -> anyhow::Result<()> {
    let sections = split_file_sections(diff);
    if sections.is_empty() {
        anyhow::bail!("no file patches found in diff");
    }

    let mut results: Vec<(String, String)> = Vec::new();
    for section in &sections {
        let patch = diffy::Patch::from_str(section)
            .map_err(|e| anyhow::anyhow!("diffy parse error: {e}"))?;
        let plus = section
            .lines()
            .find(|l| l.starts_with("+++ "))
            .ok_or_else(|| anyhow::anyhow!("diff section missing +++ header"))?;
        let rel = extract_path(plus)?;
        if !is_workspace_contained(Path::new(&rel)) {
            return Err(escape_error(Path::new(&rel)));
        }
        // Object-bound read (symlink-escape refused); absent file → fresh create.
        let original = read_contained_opt(root, &rel)?.unwrap_or_default();
        let patched = diffy::apply(&original, &patch)
            .map_err(|e| anyhow::anyhow!("diffy rejected patch for {rel}: {e}"))?;
        results.push((rel, patched));
    }

    for (rel, content) in &results {
        write_contained(root, rel, content.as_bytes())?;
    }
    Ok(())
}

/// Split a unified diff into per-file sections, each beginning at a
/// `--- ` header line. Any preamble before the first `--- ` (a
/// `diff --git` line, prose) is dropped.
#[cfg(feature = "applier-diffy")]
fn split_file_sections(diff: &str) -> Vec<String> {
    let mut sections: Vec<String> = Vec::new();
    let mut cur: Option<String> = None;
    for line in diff.lines() {
        if line.starts_with("--- ") {
            if let Some(prev) = cur.take() {
                sections.push(prev);
            }
            cur = Some(String::new());
        }
        if let Some(buf) = cur.as_mut() {
            buf.push_str(line);
            buf.push('\n');
        }
    }
    if let Some(last) = cur {
        sections.push(last);
    }
    sections
}

// ── Diff parser ─────────────────────────────────────────────────────────────

fn parse_unified_diff(diff: &str) -> anyhow::Result<Vec<FilePatch>> {
    let lines: Vec<&str> = diff.lines().collect();
    let mut patches = Vec::new();
    let mut i = 0;

    while i < lines.len() {
        // Scan for --- / +++ header pair.
        if lines[i].starts_with("--- ") {
            if i + 1 >= lines.len() || !lines[i + 1].starts_with("+++ ") {
                anyhow::bail!("expected +++ header after --- at line {}", i + 1);
            }

            let path = extract_path(lines[i + 1])?;
            i += 2;

            let mut hunks = Vec::new();
            while i < lines.len() && lines[i].starts_with("@@ ") {
                let (hunk, consumed) = parse_hunk(&lines[i..])?;
                hunks.push(hunk);
                i += consumed;
            }

            if hunks.is_empty() {
                anyhow::bail!("file patch for '{path}' has no hunks");
            }

            patches.push(FilePatch { path, hunks });
        } else {
            i += 1;
        }
    }

    Ok(patches)
}

/// Extract the file path from a `+++ b/path` or `+++ path` line.
fn extract_path(line: &str) -> anyhow::Result<String> {
    let rest = line
        .strip_prefix("+++ ")
        .ok_or_else(|| anyhow::anyhow!("invalid +++ line: {line}"))?;

    // Handle `+++ b/path` (git-style) and `+++ path` (plain).
    let path = rest.strip_prefix("b/").unwrap_or(rest);

    if path.is_empty() || path == "/dev/null" {
        anyhow::bail!("cannot determine target path from: {line}");
    }

    Ok(path.to_string())
}

/// Parse one hunk starting at `lines[0]` which must be `@@ … @@`.
/// Returns the parsed hunk and the number of lines consumed.
fn parse_hunk(lines: &[&str]) -> anyhow::Result<(Hunk, usize)> {
    let header = lines[0];
    let (old_start, _, _, _) = parse_hunk_header(header)?;

    let mut diff_lines = Vec::new();
    let mut i = 1;

    while i < lines.len() {
        let line = lines[i];

        if line.starts_with("@@ ") || line.starts_with("--- ") {
            break;
        }

        if let Some(rest) = line.strip_prefix(' ') {
            diff_lines.push(DiffLine::Context(rest.to_string()));
        } else if let Some(rest) = line.strip_prefix('+') {
            diff_lines.push(DiffLine::Add(rest.to_string()));
        } else if let Some(rest) = line.strip_prefix('-') {
            diff_lines.push(DiffLine::Remove(rest.to_string()));
        } else if line == "\\ No newline at end of file" {
            // Ignore this marker.
        } else {
            // Treat as context (handles empty context lines).
            diff_lines.push(DiffLine::Context(line.to_string()));
        }

        i += 1;
    }

    Ok((
        Hunk {
            old_start,
            lines: diff_lines,
        },
        i,
    ))
}

/// Parse `@@ -old_start,old_count +new_start,new_count @@` header.
fn parse_hunk_header(header: &str) -> anyhow::Result<(usize, usize, usize, usize)> {
    // Strip the leading @@ and trailing @@ (and anything after).
    let inner = header
        .strip_prefix("@@ ")
        .and_then(|s| s.split(" @@").next())
        .ok_or_else(|| anyhow::anyhow!("malformed hunk header: {header}"))?;

    let parts: Vec<&str> = inner.split_whitespace().collect();
    if parts.len() != 2 {
        anyhow::bail!("malformed hunk header: {header}");
    }

    let (old_start, old_count) = parse_range(parts[0].strip_prefix('-').unwrap_or(parts[0]))?;
    let (new_start, new_count) = parse_range(parts[1].strip_prefix('+').unwrap_or(parts[1]))?;

    Ok((old_start, old_count, new_start, new_count))
}

/// Parse `start,count` or just `start` (count defaults to 1).
fn parse_range(s: &str) -> anyhow::Result<(usize, usize)> {
    if let Some((start, count)) = s.split_once(',') {
        Ok((start.parse()?, count.parse()?))
    } else {
        Ok((s.parse()?, 1))
    }
}

// ── Hunk application ────────────────────────────────────────────────────────

/// How far (in lines) to search on either side of the hunk header's
/// hinted `old_start` when the hunk doesn't apply exactly there. Mirrors
/// the bounded window of `patch --fuzz` / `git apply -C`: weak local
/// models routinely emit hunks whose line numbers are off by a handful
/// of lines, but a hunk that doesn't match anywhere within this window
/// is genuinely wrong and must still be rejected.
const SEARCH_WINDOW: usize = 64;

/// Whitespace-tolerance level used when comparing a hunk's
/// context/remove lines against the file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FuzzLevel {
    /// Lines must match byte-for-byte.
    Exact,
    /// Lines match after stripping trailing whitespace from both sides.
    TrailingWs,
    /// Lines match after a full `trim()` (leading + trailing) of both.
    Trim,
}

/// Compare a hunk's expected line against the file's actual line under
/// the given fuzz level.
fn lines_match(expected: &str, actual: &str, level: FuzzLevel) -> bool {
    match level {
        FuzzLevel::Exact => expected == actual,
        FuzzLevel::TrailingWs => expected.trim_end() == actual.trim_end(),
        FuzzLevel::Trim => expected.trim() == actual.trim(),
    }
}

/// The "old side" lines a hunk consumes from the original file, in
/// order: every context (` `) and remove (`-`) line. Add (`+`) lines
/// contribute nothing to the old side. This is the run we search for.
fn hunk_old_side(hunk: &Hunk) -> Vec<&str> {
    hunk.lines
        .iter()
        .filter_map(|l| match l {
            DiffLine::Context(t) | DiffLine::Remove(t) => Some(t.as_str()),
            DiffLine::Add(_) => None,
        })
        .collect()
}

/// Does the hunk's old-side run match the file starting at `at` under
/// `level`? `at + old_side.len()` must be within bounds.
fn old_side_matches_at(old_side: &[&str], old_lines: &[&str], at: usize, level: FuzzLevel) -> bool {
    if at + old_side.len() > old_lines.len() {
        return false;
    }
    old_side
        .iter()
        .zip(&old_lines[at..at + old_side.len()])
        .all(|(exp, act)| lines_match(exp, act, level))
}

/// Locate where a hunk actually applies in `old_lines`.
///
/// Search strategy (mirrors `patch --fuzz` / `git apply -C`):
///
/// 1. Start from the header's hinted `old_start` (converted to 0-based),
///    clamped into the file. Walk offsets outward in the order
///    `0, +1, -1, +2, -2, …` up to ±[`SEARCH_WINDOW`] lines, clamped to
///    the file bounds. The **first** offset whose old-side run matches
///    exactly wins — an exact match at the hint is therefore always
///    preferred, preserving the previous behavior for clean diffs.
/// 2. If no offset matches exactly, retry the same outward walk with
///    trailing-whitespace tolerance, then with full `trim()` tolerance.
///    A whitespace-fuzzed match is only accepted when it is
///    **unambiguous**: exactly one position in the whole file matches at
///    that level. (At the `Exact` level we don't require uniqueness —
///    an exact run is its own justification, just like `patch`.)
///
/// Returns the 0-based start index and the fuzz level used, or `None` if
/// nothing matches even with whitespace tolerance within the window.
fn locate_hunk(hunk: &Hunk, old_lines: &[&str]) -> Option<(usize, FuzzLevel)> {
    let old_side = hunk_old_side(hunk);

    // A pure-insertion hunk (no context, no removes) carries no anchor;
    // it applies at its hinted position verbatim.
    if old_side.is_empty() {
        let hint = hunk.old_start.saturating_sub(1).min(old_lines.len());
        return Some((hint, FuzzLevel::Exact));
    }

    let hint = if hunk.old_start == 0 {
        0
    } else {
        (hunk.old_start - 1).min(old_lines.len())
    };

    // Candidate offsets, outward from the hint: 0, +1, -1, +2, -2, …
    let candidate_positions = || {
        std::iter::once(hint).chain((1..=SEARCH_WINDOW).flat_map(move |d| {
            let up = hint.checked_add(d);
            let down = hint.checked_sub(d);
            [up, down].into_iter().flatten()
        }))
    };

    // Pass 1: exact. First match wins (prefers the hint).
    for at in candidate_positions() {
        if old_side_matches_at(&old_side, old_lines, at, FuzzLevel::Exact) {
            return Some((at, FuzzLevel::Exact));
        }
    }

    // Passes 2 & 3: whitespace-tolerant, but only accept an *unambiguous*
    // match (exactly one position in the file matches at that level).
    for level in [FuzzLevel::TrailingWs, FuzzLevel::Trim] {
        let mut found: Option<usize> = None;
        let mut count = 0usize;
        // Scan the whole file (not just the window) to judge ambiguity,
        // but only *accept* a position that's also inside the window.
        for at in 0..=old_lines.len().saturating_sub(old_side.len()) {
            if old_side_matches_at(&old_side, old_lines, at, level) {
                count += 1;
                let within_window = at.abs_diff(hint) <= SEARCH_WINDOW;
                if within_window && found.is_none() {
                    found = Some(at);
                }
            }
        }
        if count == 1 {
            if let Some(at) = found {
                return Some((at, level));
            }
        }
    }

    None
}

fn apply_hunks(original: &str, hunks: &[Hunk]) -> anyhow::Result<String> {
    let old_lines: Vec<&str> = if original.is_empty() {
        Vec::new()
    } else {
        original.lines().collect()
    };

    let mut result = Vec::new();
    let mut old_idx: usize = 0; // 0-based index into old_lines

    for hunk in hunks {
        // Find where this hunk actually applies. We no longer trust the
        // header's `old_start` blindly — weak local models emit hunks
        // with slightly-off line numbers and fuzzy context. `locate_hunk`
        // searches outward from the hint and, failing an exact match,
        // retries with whitespace tolerance (accepting only unambiguous
        // matches). It returns `None` only when nothing matches even
        // fuzzily within the window — that is a genuine context mismatch.
        let (hunk_start, _fuzz) = locate_hunk(hunk, &old_lines).ok_or_else(|| {
            // Build a message that still contains "context mismatch" so
            // downstream code/tests that grep for it keep working, while
            // surfacing the first anchor line we failed to place.
            let first_anchor = hunk
                .lines
                .iter()
                .find_map(|l| match l {
                    DiffLine::Context(t) | DiffLine::Remove(t) => Some(t.clone()),
                    DiffLine::Add(_) => None,
                })
                .unwrap_or_default();
            anyhow::anyhow!(
                "context mismatch: hunk near line {} does not match the file \
                 (no location found within {} lines even with whitespace \
                 tolerance); first expected context/remove line was '{}'",
                hunk.old_start,
                SEARCH_WINDOW,
                first_anchor
            )
        })?;

        // `locate_hunk` clamps to file bounds, so this can't exceed len,
        // but guard defensively (and to keep the old error wording for
        // out-of-range starts on empty/short files).
        if hunk_start > old_lines.len() {
            anyhow::bail!(
                "hunk starts at line {} but file only has {} lines",
                hunk.old_start,
                old_lines.len()
            );
        }

        // The located start may be before or after where we currently
        // are; if a previous hunk already advanced past it we cannot
        // rewind (hunks must apply in order). Copy forward to the start.
        if hunk_start < old_idx {
            anyhow::bail!(
                "context mismatch: hunk near line {} resolves to line {} which \
                 overlaps an already-applied hunk",
                hunk.old_start,
                hunk_start + 1
            );
        }
        while old_idx < hunk_start {
            result.push(old_lines[old_idx].to_string());
            old_idx += 1;
        }

        // Apply hunk lines at the located position. Because `locate_hunk`
        // already verified the old-side run matches here (exactly or
        // fuzzily), we copy the *file's* line for context/remove anchors
        // rather than the hunk's text — so whitespace-fuzzed context does
        // not corrupt the surrounding lines.
        for diff_line in &hunk.lines {
            match diff_line {
                DiffLine::Context(_) => {
                    // Invariant from locate_hunk: in bounds and matching.
                    result.push(old_lines[old_idx].to_string());
                    old_idx += 1;
                }
                DiffLine::Remove(_) => {
                    // Invariant from locate_hunk: in bounds and matching.
                    old_idx += 1;
                }
                DiffLine::Add(text) => {
                    result.push(text.clone());
                }
            }
        }
    }

    // Copy remaining lines after the last hunk.
    while old_idx < old_lines.len() {
        result.push(old_lines[old_idx].to_string());
        old_idx += 1;
    }

    // Preserve trailing newline if original had one (or if it's a new file).
    let mut output = result.join("\n");
    if original.is_empty() || original.ends_with('\n') {
        output.push('\n');
    }

    Ok(output)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn single_file_add_line() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("hello.txt");
        fs::write(&file, "line1\nline2\nline3\n").unwrap();

        let diff = "\
--- a/hello.txt
+++ b/hello.txt
@@ -1,3 +1,4 @@
 line1
+inserted
 line2
 line3
";
        apply_patch(tmp.path(), diff).unwrap();
        let result = fs::read_to_string(&file).unwrap();
        assert_eq!(result, "line1\ninserted\nline2\nline3\n");
    }

    #[test]
    fn apply_whole_files_rejects_path_escape() {
        // step-4.1 / #522 / P4: the model-supplied relative path is
        // attacker-controlled. A `..` or absolute component must be refused
        // BEFORE the join, so no write lands outside the workspace fence
        // (out-of-band RCE via cron / authorized_keys / .git/hooks).
        let tmp = TempDir::new().unwrap();
        let ws = tmp.path().join("ws");
        fs::create_dir(&ws).unwrap();

        // `..` traversal escape → would land at tmp/escape.txt, a sibling OUTSIDE ws.
        let outside = tmp.path().join("escape.txt");
        let err = apply_whole_files(&ws, [("../escape.txt", "pwned")]).unwrap_err();
        assert!(
            err.to_string().contains("escapes the workspace"),
            "got: {err}"
        );
        assert!(
            !outside.exists(),
            "`..` escape must not write outside the workspace"
        );

        // Absolute-path escape — target a TEMP path so even the pre-fix (RED)
        // run can never touch a real system file. Checked by COMPONENT, not
        // is_absolute() (on Windows `/etc/x` is root-relative yet not absolute).
        let abs_target = tmp.path().join("abs-escape.txt");
        let abs_key = abs_target.to_string_lossy().into_owned();
        let err = apply_whole_files(&ws, [(abs_key.as_str(), "pwned")]).unwrap_err();
        assert!(
            err.to_string().contains("escapes the workspace"),
            "got: {err}"
        );
        assert!(!abs_target.exists(), "absolute path must not be written");

        // A legitimate in-workspace path still applies.
        let ok = apply_whole_files(&ws, [("sub/ok.rs", "fine")]).unwrap();
        assert_eq!(ok, vec!["sub/ok.rs".to_string()]);
        assert!(ws.join("sub/ok.rs").exists());
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn apply_whole_files_denies_symlink_escape_object_bound() {
        // step-52.7 (#522 CLOSURE): a symlink UNDER the workspace pointing outside
        // must not let the applier write through it — even though the lexical
        // `is_workspace_contained` admits the Normal-component path `link/evil.rs`.
        // Object-bound via openat2(RESOLVE_BENEATH); the outside file is untouched.
        // This is the escape `is_workspace_contained` cannot see (the #522 residual),
        // now closed. Verified red→green (neuter the resolve flags → the write lands
        // outside).
        let ws = TempDir::new().unwrap();
        let outside = TempDir::new().unwrap();
        std::fs::write(outside.path().join("evil.rs"), "original\n").unwrap();
        std::os::unix::fs::symlink(outside.path(), ws.path().join("link")).unwrap();

        let result = apply_whole_files(ws.path(), [("link/evil.rs".to_string(), "PWNED\n")]);
        assert!(
            result.is_err(),
            "a symlink-escape write must be refused: {result:?}"
        );
        assert_eq!(
            std::fs::read_to_string(outside.path().join("evil.rs")).unwrap(),
            "original\n",
            "the outside file must be UNCHANGED — the write never escaped"
        );
    }

    #[test]
    fn apply_patch_rejects_path_escape() {
        // Same containment for the legacy unified-diff path (fuzzy applier).
        let tmp = TempDir::new().unwrap();
        let ws = tmp.path().join("ws");
        fs::create_dir(&ws).unwrap();
        let outside = tmp.path().join("escape.txt");
        let diff = "\
--- a/../escape.txt
+++ b/../escape.txt
@@ -0,0 +1 @@
+pwned
";
        let err = apply_patch(&ws, diff).unwrap_err();
        assert!(
            err.to_string().contains("escapes the workspace"),
            "got: {err}"
        );
        assert!(
            !outside.exists(),
            "diff `..` escape must not write outside the workspace"
        );
    }

    #[test]
    fn is_workspace_contained_rejects_escapes() {
        // Pure component check — the load-bearing predicate, no fs.
        assert!(is_workspace_contained(Path::new("a/b.rs")));
        assert!(is_workspace_contained(Path::new("./a.rs")));
        assert!(is_workspace_contained(Path::new("sub/dir/file.txt")));
        assert!(!is_workspace_contained(Path::new("../a.rs")));
        assert!(!is_workspace_contained(Path::new("a/../../b")));
        assert!(!is_workspace_contained(Path::new("/etc/passwd")));
    }

    #[test]
    fn single_file_remove_line() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("hello.txt");
        fs::write(&file, "line1\nline2\nline3\n").unwrap();

        let diff = "\
--- a/hello.txt
+++ b/hello.txt
@@ -1,3 +1,2 @@
 line1
-line2
 line3
";
        apply_patch(tmp.path(), diff).unwrap();
        let result = fs::read_to_string(&file).unwrap();
        assert_eq!(result, "line1\nline3\n");
    }

    #[test]
    fn multi_hunk() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("code.rs");
        fs::write(&file, "a\nb\nc\nd\ne\nf\ng\n").unwrap();

        let diff = "\
--- a/code.rs
+++ b/code.rs
@@ -1,3 +1,3 @@
 a
-b
+B
 c
@@ -5,3 +5,3 @@
 e
-f
+F
 g
";
        apply_patch(tmp.path(), diff).unwrap();
        let result = fs::read_to_string(&file).unwrap();
        assert_eq!(result, "a\nB\nc\nd\ne\nF\ng\n");
    }

    #[test]
    fn new_file() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("new.txt");
        assert!(!file.exists());

        let diff = "\
--- /dev/null
+++ b/new.txt
@@ -0,0 +1,2 @@
+hello
+world
";
        apply_patch(tmp.path(), diff).unwrap();
        let result = fs::read_to_string(&file).unwrap();
        assert_eq!(result, "hello\nworld\n");
    }

    #[test]
    fn context_mismatch_rejected() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("hello.txt");
        fs::write(&file, "actual\nline2\n").unwrap();

        let diff = "\
--- a/hello.txt
+++ b/hello.txt
@@ -1,2 +1,2 @@
 expected
-line2
+replaced
";
        let err = apply_patch(tmp.path(), diff).unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("context mismatch"),
            "expected context mismatch error, got: {msg}"
        );
    }

    #[test]
    fn malformed_diff_rejected() {
        let tmp = TempDir::new().unwrap();
        let err = apply_patch(tmp.path(), "this is not a diff").unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("no file patches found"),
            "unexpected error: {msg}"
        );
    }

    #[test]
    fn atomic_write_verified() {
        let tmp = TempDir::new().unwrap();
        let file1 = tmp.path().join("ok.txt");
        let file2 = tmp.path().join("fail.txt");
        fs::write(&file1, "aaa\nbbb\n").unwrap();
        fs::write(&file2, "xxx\nyyy\n").unwrap();

        // First file patch is valid, second has a context mismatch.
        let diff = "\
--- a/ok.txt
+++ b/ok.txt
@@ -1,2 +1,2 @@
 aaa
-bbb
+ccc
--- a/fail.txt
+++ b/fail.txt
@@ -1,2 +1,2 @@
 WRONG_CONTEXT
-yyy
+zzz
";
        let err = apply_patch(tmp.path(), diff).unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("mismatch"), "expected mismatch error: {msg}");

        // Because we validate all patches before writing, the first file
        // should be unchanged.
        let content1 = fs::read_to_string(&file1).unwrap();
        assert_eq!(content1, "aaa\nbbb\n", "first file should be unchanged");

        let content2 = fs::read_to_string(&file2).unwrap();
        assert_eq!(content2, "xxx\nyyy\n", "second file should be unchanged");
    }

    #[test]
    fn edit_applies_patch() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("hello.txt");
        fs::write(&file, "line1\nline2\n").unwrap();

        let diff = "\
--- a/hello.txt
+++ b/hello.txt
@@ -1,2 +1,2 @@
 line1
-line2
+edited
";
        edit(&file, diff).unwrap();
        let result = fs::read_to_string(&file).unwrap();
        assert_eq!(result, "line1\nedited\n");
    }

    #[test]
    fn apply_whole_files_writes_single_file() {
        let tmp = TempDir::new().unwrap();
        let files = vec![("src/lib.rs".to_string(), "pub fn hello() {}\n".to_string())];
        let written = apply_whole_files(tmp.path(), files).unwrap();
        assert_eq!(written, vec!["src/lib.rs".to_string()]);
        let got = fs::read_to_string(tmp.path().join("src/lib.rs")).unwrap();
        assert_eq!(got, "pub fn hello() {}\n");
    }

    #[test]
    fn apply_whole_files_creates_parent_dirs() {
        let tmp = TempDir::new().unwrap();
        let files = vec![("a/b/c/d.rs".to_string(), "fn x() {}\n".to_string())];
        apply_whole_files(tmp.path(), files).unwrap();
        assert!(tmp.path().join("a/b/c/d.rs").exists());
    }

    #[test]
    fn apply_whole_files_overwrites_existing() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("src/lib.rs");
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        fs::write(&file, "OLD\n").unwrap();

        let files = vec![("src/lib.rs".to_string(), "NEW\n".to_string())];
        apply_whole_files(tmp.path(), files).unwrap();
        let got = fs::read_to_string(&file).unwrap();
        assert_eq!(got, "NEW\n");
    }

    #[test]
    fn apply_whole_files_no_tmp_residue() {
        // After a successful run, no `.newt-coder-tmp` files should
        // remain anywhere under the workspace.
        let tmp = TempDir::new().unwrap();
        let files = vec![
            ("a.rs".to_string(), "fn a() {}".to_string()),
            ("b.rs".to_string(), "fn b() {}".to_string()),
        ];
        apply_whole_files(tmp.path(), files).unwrap();

        for entry in fs::read_dir(tmp.path()).unwrap() {
            let entry = entry.unwrap();
            let name = entry.file_name().to_string_lossy().to_string();
            assert!(
                !name.ends_with(".newt-coder-tmp"),
                "leftover temp file: {name}"
            );
        }
    }

    #[test]
    fn apply_whole_files_accepts_str_slice_values() {
        // Ergonomics: callers should be able to pass &str without
        // .to_string()-ing every value.
        let tmp = TempDir::new().unwrap();
        let files: Vec<(&str, &str)> = vec![("hello.txt", "hi\n")];
        let written = apply_whole_files(tmp.path(), files).unwrap();
        assert_eq!(written, vec!["hello.txt".to_string()]);
        let got = fs::read_to_string(tmp.path().join("hello.txt")).unwrap();
        assert_eq!(got, "hi\n");
    }

    #[test]
    fn edit_error_propagated() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("hello.txt");
        fs::write(&file, "aaa\n").unwrap();

        let diff = "\
--- a/hello.txt
+++ b/hello.txt
@@ -1,1 +1,1 @@
 WRONG
";
        let err = edit(&file, diff).unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("mismatch"), "expected mismatch error: {msg}");
    }

    // ── Fuzzy hunk matching (weak-model tolerance) ──────────────────────────

    #[test]
    fn hunk_old_start_off_by_plus_two_still_applies() {
        // The model emitted a hunk whose header points at line 3 but the
        // anchored context actually lives at line 1 (off by +2). A strict
        // matcher would reject it; the fuzzy locator must find the real
        // position and apply there.
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("lib.rs");
        fs::write(&file, "alpha\nbeta\ngamma\ndelta\n").unwrap();

        let diff = "\
--- a/lib.rs
+++ b/lib.rs
@@ -3,2 +3,3 @@
 alpha
+INSERTED
 beta
";
        apply_patch(tmp.path(), diff).unwrap();
        let result = fs::read_to_string(&file).unwrap();
        assert_eq!(result, "alpha\nINSERTED\nbeta\ngamma\ndelta\n");
    }

    #[test]
    fn hunk_old_start_off_by_minus_two_still_applies() {
        // Symmetric case: header hints a later line than reality.
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("lib.rs");
        fs::write(&file, "a\nb\nc\nTARGET\nd\ne\n").unwrap();

        // Header says line 2, real anchor is line 4 -> offset -2 from hint.
        let diff = "\
--- a/lib.rs
+++ b/lib.rs
@@ -6,1 +6,2 @@
 TARGET
+AFTER
";
        apply_patch(tmp.path(), diff).unwrap();
        let result = fs::read_to_string(&file).unwrap();
        assert_eq!(result, "a\nb\nc\nTARGET\nAFTER\nd\ne\n");
    }

    #[test]
    fn hunk_with_trailing_whitespace_context_applies() {
        // The model's context line carries trailing whitespace the real
        // file lacks. Exact match fails; trailing-ws fuzz must rescue it,
        // and the surrounding file line must NOT be corrupted with the
        // model's stray whitespace.
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("lib.rs");
        fs::write(&file, "pub fn hello() {\n    body();\n}\n").unwrap();

        // Note the trailing spaces after the context lines below.
        let diff = "\
--- a/lib.rs
+++ b/lib.rs
@@ -1,3 +1,4 @@
 pub fn hello() {
+    setup();
     body();
 }
";
        apply_patch(tmp.path(), diff).unwrap();
        let result = fs::read_to_string(&file).unwrap();
        assert_eq!(
            result, "pub fn hello() {\n    setup();\n    body();\n}\n",
            "context must come from the file, not the fuzzed hunk text"
        );
    }

    #[test]
    fn hunk_with_leading_whitespace_diff_applies_via_trim() {
        // Indentation drift: the model's context lines are indented
        // differently than the file. Only full-trim fuzz can match.
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("lib.rs");
        fs::write(&file, "fn main() {\n    let x = 1;\n}\n").unwrap();

        let diff = "\
--- a/lib.rs
+++ b/lib.rs
@@ -1,3 +1,4 @@
 fn main() {
 let x = 1;
+    let y = 2;
 }
";
        apply_patch(tmp.path(), diff).unwrap();
        let result = fs::read_to_string(&file).unwrap();
        // The file's own indentation is preserved for the matched line.
        assert_eq!(result, "fn main() {\n    let x = 1;\n    let y = 2;\n}\n");
    }

    #[test]
    fn genuinely_non_matching_hunk_still_rejected() {
        // Safety property the ACP worker relies on: a hunk whose context
        // matches nothing in the file (even fuzzily) must be rejected.
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("lib.rs");
        fs::write(&file, "fn main() { println!(\"hello\"); }\n").unwrap();

        let diff = "\
--- a/lib.rs
+++ b/lib.rs
@@ -1,1 +1,1 @@
 fn TOTALLY_WRONG() {
-old
+new
";
        let err = apply_patch(tmp.path(), diff).unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("context mismatch"),
            "expected context mismatch error, got: {msg}"
        );
        // File must be untouched.
        assert_eq!(
            fs::read_to_string(&file).unwrap(),
            "fn main() { println!(\"hello\"); }\n"
        );
    }

    #[test]
    fn exact_match_preferred_over_later_fuzzy_match() {
        // When the hint lands on an exact match, that location wins even
        // if a whitespace-fuzzy match exists elsewhere. Guards against the
        // locator drifting to the wrong (but fuzzily-similar) block.
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("lib.rs");
        fs::write(&file, "marker\nmarker \nother\n").unwrap();

        // Exact "marker" is at line 1; a trailing-ws variant is at line 2.
        let diff = "\
--- a/lib.rs
+++ b/lib.rs
@@ -1,1 +1,2 @@
 marker
+ADDED
";
        apply_patch(tmp.path(), diff).unwrap();
        let result = fs::read_to_string(&file).unwrap();
        assert_eq!(result, "marker\nADDED\nmarker \nother\n");
    }

    #[test]
    fn ambiguous_whitespace_fuzz_is_rejected() {
        // If a whitespace-fuzzed anchor matches more than one place in the
        // file, we refuse rather than guess. (No exact match exists here:
        // the hunk context has a trailing space the file lines lack.)
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("lib.rs");
        fs::write(&file, "dup\nfiller\ndup\n").unwrap();

        // The context line carries a trailing space the file's "dup" lines
        // lack, so NO exact match exists. Both "dup" lines then match only
        // after whitespace trimming → two candidates → ambiguous → reject.
        // (The trailing space is kept explicit in the `" dup "` literal so a
        // formatter can't silently strip it.)
        let ctx = " dup "; // diff context marker + "dup" + trailing space
        let diff = format!("--- a/lib.rs\n+++ b/lib.rs\n@@ -1,1 +1,2 @@\n{ctx}\n+ADDED\n");
        let err = apply_patch(tmp.path(), &diff).unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("context mismatch"),
            "ambiguous fuzzy match must be rejected, got: {msg}"
        );
    }

    #[test]
    fn clean_diff_with_correct_line_numbers_unaffected() {
        // Regression guard: a perfectly-formed diff still applies at its
        // header position with no fuzz.
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("lib.rs");
        fs::write(&file, "one\ntwo\nthree\nfour\n").unwrap();

        let diff = "\
--- a/lib.rs
+++ b/lib.rs
@@ -2,2 +2,2 @@
 two
-three
+THREE
";
        apply_patch(tmp.path(), diff).unwrap();
        let result = fs::read_to_string(&file).unwrap();
        assert_eq!(result, "one\ntwo\nTHREE\nfour\n");
    }
}