recursive-agent 0.3.0

A minimal, orthogonal, self-improving coding agent kernel in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
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
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
//! `apply_patch`: apply a structured multi-file patch atomically.
//!
//! The patch format is the **V4A** flavour popularised by Anthropic and used
//! by OpenAI's Codex CLI: no line numbers, context lines locate the change
//! in the file. This is materially more robust than unified diff for
//! LLM-authored edits — models reliably mis-count line numbers, but they
//! reliably preserve a few lines of context.
//!
//! ```text
//! *** Begin Patch
//! *** Update File: src/foo.rs
//! @@ optional anchor
//!  context line (unchanged, must match the file exactly)
//! -line to remove (must match the file exactly)
//! +line to add
//!  context line
//! *** Add File: new/file.rs
//! +line one
//! +line two
//! *** Delete File: doomed/file.rs
//! *** End Patch
//! ```
//!
//! Reliability strategy:
//!   - **Strict matching.** Context+remove lines must match the live file
//!     exactly. No fuzzy matching.
//!   - **Single-match.** If a hunk's pattern appears 0 or >1 times in the
//!     file, the patch is rejected (the model can add an `@@ anchor` for
//!     disambiguation or include more context).
//!   - **Atomic.** All hunks are applied in memory first; only after every
//!     file's final state is computed do we touch the disk. A failure in
//!     hunk N rolls the whole patch back; nothing on disk changes.
//!   - **Sandboxed.** Every path goes through `resolve_within`.
//!   - **Useful errors.** The tool returns structured diagnostics (which
//!     file, which hunk, what was being matched) so the model can self-correct.

use async_trait::async_trait;
use serde_json::{json, Value};
use std::collections::HashSet;
use std::path::PathBuf;

use super::{resolve_within, Tool};
use crate::error::{Error, Result};
use crate::llm::ToolSpec;

const BEGIN: &str = "*** Begin Patch";
const END: &str = "*** End Patch";
const UPDATE: &str = "*** Update File: ";
const ADD: &str = "*** Add File: ";
const DELETE: &str = "*** Delete File: ";
const HUNK_SEP: &str = "@@";

/// Normalize a unified-diff-style hunk header to a V4A anchor.
///
/// Unified-diff headers look like `@@ -14,6 +14,28 @@ anchor text` or
/// `@@ -14 +14 @@ anchor text`. The line-number range is discarded; only
/// the trailing text after the second `@@` is returned as the anchor.
///
/// Returns `None` when the trailing text is empty or whitespace-only.
fn normalize_hunk_header(rest: &str) -> Option<String> {
    let trimmed = rest.trim();
    if trimmed.is_empty() {
        return None;
    }

    // Check for unified-diff pattern: `-N[,M] +N[,M] @@ [trailing]`
    // We scan manually (no regex crate).
    let bytes = trimmed.as_bytes();
    let len = bytes.len();
    let mut i = 0;

    // Skip leading whitespace.
    while i < len && bytes[i].is_ascii_whitespace() {
        i += 1;
    }

    // Must start with '-'.
    if i < len && bytes[i] == b'-' {
        i += 1;
        // Consume digits and optional comma+digits (the "old" range).
        let mut has_digits = false;
        while i < len && bytes[i].is_ascii_digit() {
            has_digits = true;
            i += 1;
        }
        if i < len && bytes[i] == b',' {
            i += 1;
            while i < len && bytes[i].is_ascii_digit() {
                has_digits = true;
                i += 1;
            }
        }
        if !has_digits {
            // Not a unified-diff header after all; return whole trimmed.
            return Some(trimmed.to_string());
        }

        // Skip whitespace.
        while i < len && bytes[i].is_ascii_whitespace() {
            i += 1;
        }

        // Must have '+'.
        if i < len && bytes[i] == b'+' {
            i += 1;
            // Consume digits and optional comma+digits (the "new" range).
            let mut has_digits2 = false;
            while i < len && bytes[i].is_ascii_digit() {
                has_digits2 = true;
                i += 1;
            }
            if i < len && bytes[i] == b',' {
                i += 1;
                while i < len && bytes[i].is_ascii_digit() {
                    has_digits2 = true;
                    i += 1;
                }
            }
            if !has_digits2 {
                return Some(trimmed.to_string());
            }

            // Skip whitespace.
            while i < len && bytes[i].is_ascii_whitespace() {
                i += 1;
            }

            // Must have '@@'.
            if i + 1 < len && bytes[i] == b'@' && bytes[i + 1] == b'@' {
                i += 2;
                // Skip whitespace after the second @@.
                while i < len && bytes[i].is_ascii_whitespace() {
                    i += 1;
                }
                let trailing = trimmed[i..].trim().to_string();
                if trailing.is_empty() {
                    return None;
                }
                return Some(trailing);
            }
        }
    }

    // Not a unified-diff header; return the whole trimmed string.
    Some(trimmed.to_string())
}

// ---- Tool ------------------------------------------------------------------

#[derive(Debug, Clone)]
pub struct ApplyPatch {
    pub root: PathBuf,
}

impl ApplyPatch {
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self { root: root.into() }
    }
}

#[async_trait]
impl Tool for ApplyPatch {
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "apply_patch".into(),
            description: concat!(
                "Apply a V4A-format patch atomically. Format:\n",
                "*** Begin Patch\n",
                "*** Update File: <path>\n",
                "[@@ optional_anchor_line]\n",
                " context_line\n",
                "-line_to_remove\n",
                "+line_to_add\n",
                " context_line\n",
                "*** Add File: <path>\n",
                "+line_one\n",
                "+line_two\n",
                "*** Delete File: <path>\n",
                "*** End Patch\n",
                "Context lines must match the file exactly. If a hunk's pattern ",
                "appears multiple times in the file, add an @@ anchor (some unique ",
                "line that appears earlier in the file) before the hunk. ",
                "Both `@@ <unique_line>` (V4A) and ",
                "`@@ -N,M +N,M @@ <unique_line>` (unified-diff style) headers are ",
                "accepted; the line-number range is ignored, only the anchor text ",
                "after the final `@@` is used to locate the hunk."
            )
            .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "patch": {"type": "string", "description": "The V4A patch text"},
                    "dry_run": {"type": "boolean", "description": "If true, validate and resolve the patch but do not write any files. Returns the same success/error message it would produce in a normal run.", "default": false}
                },
                "required": ["patch"]
            }),
        }
    }

    async fn execute(&self, args: Value) -> Result<String> {
        let input = args["patch"].as_str().ok_or_else(|| Error::BadToolArgs {
            name: "apply_patch".into(),
            message: "missing `patch`".into(),
        })?;
        let dry_run = args
            .get("dry_run")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let patch = parse_patch(input).map_err(|e| Error::Tool {
            name: "apply_patch".into(),
            message: e,
        })?;
        let writes = stage(&patch, &self.root).await.map_err(|e| Error::Tool {
            name: "apply_patch".into(),
            message: e,
        })?;
        if dry_run {
            let file_count = writes.len();
            let hunk_count: usize = patch
                .ops
                .iter()
                .map(|op| match op {
                    FileOp::Update { hunks, .. } => hunks.len(),
                    _ => 1,
                })
                .sum();
            let paths: Vec<&str> = writes.iter().map(|w| w.rel_path.as_str()).collect();
            return Ok(format!(
                "dry-run: would apply {} hunk(s) across {} file(s): {}",
                hunk_count,
                file_count,
                paths.join(", ")
            ));
        }
        commit(writes).await.map_err(|e| Error::Tool {
            name: "apply_patch".into(),
            message: e,
        })
    }
}

// ---- AST -------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum HunkLine {
    Context(String),
    Add(String),
    Remove(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Hunk {
    pub anchor: Option<String>,
    pub lines: Vec<HunkLine>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum FileOp {
    Update { path: String, hunks: Vec<Hunk> },
    Add { path: String, content: String },
    Delete { path: String },
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Patch {
    pub ops: Vec<FileOp>,
}

// ---- Parser ----------------------------------------------------------------

pub(crate) fn parse_patch(input: &str) -> std::result::Result<Patch, String> {
    let mut lines = input.lines().peekable();

    // Skip leading blank lines.
    while matches!(lines.peek(), Some(l) if l.trim().is_empty()) {
        lines.next();
    }

    let begin = lines.next().ok_or("empty patch")?;
    if begin.trim() != BEGIN {
        return Err(format!("first line must be `{BEGIN}`, got `{begin}`"));
    }

    let mut patch = Patch::default();
    let mut current_file: Option<FileOp> = None;

    loop {
        let Some(line) = lines.next() else {
            return Err(format!("patch terminated without `{END}`"));
        };

        if line.trim() == END {
            if let Some(op) = current_file.take() {
                patch.ops.push(op);
            }
            break;
        }

        // File header? Flush whatever we were building and start a new op.
        if let Some(path) = line.strip_prefix(UPDATE) {
            if let Some(op) = current_file.take() {
                patch.ops.push(op);
            }
            let path = path.trim().to_string();
            if path.is_empty() {
                return Err(format!("`{UPDATE}` with empty path"));
            }
            current_file = Some(FileOp::Update {
                path,
                hunks: vec![Hunk {
                    anchor: None,
                    lines: vec![],
                }],
            });
            continue;
        }
        if let Some(path) = line.strip_prefix(ADD) {
            if let Some(op) = current_file.take() {
                patch.ops.push(op);
            }
            let path = path.trim().to_string();
            if path.is_empty() {
                return Err(format!("`{ADD}` with empty path"));
            }
            current_file = Some(FileOp::Add {
                path,
                content: String::new(),
            });
            continue;
        }
        if let Some(path) = line.strip_prefix(DELETE) {
            if let Some(op) = current_file.take() {
                patch.ops.push(op);
            }
            let path = path.trim().to_string();
            if path.is_empty() {
                return Err(format!("`{DELETE}` with empty path"));
            }
            current_file = Some(FileOp::Delete { path });
            continue;
        }

        // Body of the current file.
        let op = current_file.as_mut().ok_or_else(|| {
            format!("body line `{line}` before any `*** Update/Add/Delete File:` header")
        })?;

        match op {
            FileOp::Update { hunks, .. } => {
                if let Some(rest) = line.strip_prefix(HUNK_SEP) {
                    // New hunk; first hunk is pre-allocated above, so we only push if the current is non-empty.
                    let anchor = normalize_hunk_header(rest);
                    let last = hunks.last_mut().unwrap();
                    if last.lines.is_empty() {
                        last.anchor = anchor;
                    } else {
                        hunks.push(Hunk {
                            anchor,
                            lines: vec![],
                        });
                    }
                    continue;
                }

                let parsed = if let Some(rest) = line.strip_prefix('-') {
                    HunkLine::Remove(rest.to_string())
                } else if let Some(rest) = line.strip_prefix('+') {
                    HunkLine::Add(rest.to_string())
                } else if let Some(rest) = line.strip_prefix(' ') {
                    HunkLine::Context(rest.to_string())
                } else if line.is_empty() {
                    // Unprefixed blank lines are treated as a blank context line.
                    // (Models sometimes emit `\n` instead of ` \n`.)
                    HunkLine::Context(String::new())
                } else {
                    return Err(format!("unexpected line in Update hunk: `{line}`"));
                };
                hunks.last_mut().unwrap().lines.push(parsed);
            }
            FileOp::Add { content, .. } => {
                let body_line = if let Some(rest) = line.strip_prefix('+') {
                    rest
                } else if line.is_empty() {
                    ""
                } else {
                    return Err(format!(
                        "Add File body lines must start with `+`, got `{line}`"
                    ));
                };
                if !content.is_empty() {
                    content.push('\n');
                }
                content.push_str(body_line);
            }
            FileOp::Delete { .. } => {
                // No body allowed.
                if !line.trim().is_empty() {
                    return Err(format!("Delete File body must be empty, got `{line}`"));
                }
            }
        }
    }

    // Validation: paths unique, hunks non-empty for Update.
    let mut seen: HashSet<&String> = HashSet::new();
    for op in &patch.ops {
        let path = match op {
            FileOp::Update { path, .. } | FileOp::Add { path, .. } | FileOp::Delete { path } => {
                path
            }
        };
        if !seen.insert(path) {
            return Err(format!("path `{path}` appears in patch more than once"));
        }
        if let FileOp::Update { hunks, .. } = op {
            if hunks.iter().all(|h| h.lines.is_empty()) {
                return Err(format!("Update File `{path}` has no hunks"));
            }
            for (i, h) in hunks.iter().enumerate() {
                if h.lines.is_empty() {
                    return Err(format!("Update File `{path}` hunk {} is empty", i + 1));
                }
                if !h
                    .lines
                    .iter()
                    .any(|l| matches!(l, HunkLine::Add(_) | HunkLine::Remove(_)))
                {
                    return Err(format!(
                        "Update File `{path}` hunk {} has no +/- lines",
                        i + 1
                    ));
                }
            }
        }
    }

    Ok(patch)
}

// ---- Applier ---------------------------------------------------------------

struct StagedWrite {
    abs_path: PathBuf,
    rel_path: String,
    kind: StagedKind,
}

enum StagedKind {
    WriteText(String),
    Delete,
}

async fn stage(
    patch: &Patch,
    root: &std::path::Path,
) -> std::result::Result<Vec<StagedWrite>, String> {
    let mut staged = Vec::new();
    for op in &patch.ops {
        let path = match op {
            FileOp::Update { path, .. } | FileOp::Add { path, .. } | FileOp::Delete { path } => {
                path
            }
        };
        let abs = resolve_within(root, path).map_err(|e| e.to_string())?;

        match op {
            FileOp::Update { hunks, .. } => {
                let current = tokio::fs::read_to_string(&abs)
                    .await
                    .map_err(|e| format!("update `{path}`: {e}"))?;
                let updated =
                    apply_hunks(&current, hunks).map_err(|e| format!("update `{path}`: {e}"))?;
                staged.push(StagedWrite {
                    abs_path: abs,
                    rel_path: path.clone(),
                    kind: StagedKind::WriteText(updated),
                });
            }
            FileOp::Add { content, .. } => {
                if abs.exists() {
                    return Err(format!("add `{path}`: file already exists"));
                }
                staged.push(StagedWrite {
                    abs_path: abs,
                    rel_path: path.clone(),
                    kind: StagedKind::WriteText(content.clone()),
                });
            }
            FileOp::Delete { .. } => {
                if !abs.exists() {
                    return Err(format!("delete `{path}`: file does not exist"));
                }
                staged.push(StagedWrite {
                    abs_path: abs,
                    rel_path: path.clone(),
                    kind: StagedKind::Delete,
                });
            }
        }
    }
    Ok(staged)
}

async fn commit(staged: Vec<StagedWrite>) -> std::result::Result<String, String> {
    let mut summary = Vec::new();
    for w in &staged {
        match &w.kind {
            StagedKind::WriteText(content) => {
                if let Some(parent) = w.abs_path.parent() {
                    tokio::fs::create_dir_all(parent)
                        .await
                        .map_err(|e| format!("mkdir for `{}`: {e}", w.rel_path))?;
                }
                tokio::fs::write(&w.abs_path, content)
                    .await
                    .map_err(|e| format!("write `{}`: {e}", w.rel_path))?;
                summary.push(format!("wrote {} ({} bytes)", w.rel_path, content.len()));
            }
            StagedKind::Delete => {
                tokio::fs::remove_file(&w.abs_path)
                    .await
                    .map_err(|e| format!("delete `{}`: {e}", w.rel_path))?;
                summary.push(format!("deleted {}", w.rel_path));
            }
        }
    }
    Ok(format!(
        "applied {} change(s):\n{}",
        staged.len(),
        summary.join("\n")
    ))
}

/// Find up to 3 unique lines near the match location that could serve as anchors.
/// We look 5 lines before and 5 lines after the first matched location,
/// and keep only lines that appear exactly once in the whole file.
fn find_unique_anchor_suggestions(
    lines: &[String],
    match_start: usize,
    pattern: &[&str],
) -> Vec<String> {
    let mut suggestions = Vec::new();
    let window = 5;

    // Collect candidate lines: 5 before through 5 after the match location
    let start = match_start.saturating_sub(window);
    let end = (match_start + pattern.len() + window).min(lines.len());

    for i in start..end {
        let line = &lines[i];
        if line.is_empty() {
            continue;
        }

        // Count occurrences of this exact line in the whole file
        let count = lines.iter().filter(|l| l.as_str() == line.as_str()).count();
        if count == 1 {
            suggestions.push(line.clone());
        }

        if suggestions.len() >= 3 {
            break;
        }
    }

    suggestions
}

fn apply_hunks(content: &str, hunks: &[Hunk]) -> std::result::Result<String, String> {
    let trailing_newline = content.ends_with('\n');
    let mut lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();

    for (idx, hunk) in hunks.iter().enumerate() {
        // Pattern: context + remove lines in order. Replacement: context + add.
        let pattern: Vec<&str> = hunk
            .lines
            .iter()
            .filter_map(|l| match l {
                HunkLine::Context(s) | HunkLine::Remove(s) => Some(s.as_str()),
                HunkLine::Add(_) => None,
            })
            .collect();

        let replacement: Vec<String> = hunk
            .lines
            .iter()
            .filter_map(|l| match l {
                HunkLine::Context(s) | HunkLine::Add(s) => Some(s.clone()),
                HunkLine::Remove(_) => None,
            })
            .collect();

        if pattern.is_empty() {
            // Pure-add hunk with no anchor: prepend to file. Discouraged but allowed.
            // We only allow this if the file is currently empty AND there's no anchor.
            if !lines.is_empty() || hunk.anchor.is_some() {
                return Err(format!(
                    "hunk {} has no context/remove lines; need at least one for matching",
                    idx + 1
                ));
            }
            lines.extend(replacement);
            continue;
        }

        // Find all positions where pattern matches.
        let mut matches: Vec<usize> = Vec::new();
        if pattern.len() <= lines.len() {
            for start in 0..=(lines.len() - pattern.len()) {
                if lines[start..start + pattern.len()]
                    .iter()
                    .zip(pattern.iter())
                    .all(|(actual, expected)| actual == expected)
                {
                    matches.push(start);
                }
            }
        }

        // Anchor filtering: the anchor text must appear in some line at or
        // before the END of the matched region. Spec'd anchors sit *above*
        // the hunk, but models sometimes inline them into the first context
        // line — both should disambiguate equally well.
        if let Some(anchor) = &hunk.anchor {
            matches.retain(|&start| {
                let end = start + pattern.len();
                lines[..end].iter().any(|l| l.contains(anchor.as_str()))
            });
        }

        let pos = match matches.len() {
            0 => {
                return Err(format!(
                    "hunk {} pattern not found{}.\nFirst 3 pattern lines:\n{}",
                    idx + 1,
                    hunk.anchor
                        .as_deref()
                        .map(|a| format!(" (anchor `{a}`)"))
                        .unwrap_or_default(),
                    pattern
                        .iter()
                        .take(3)
                        .map(|l| format!("    {l}"))
                        .collect::<Vec<_>>()
                        .join("\n")
                ));
            }
            1 => matches[0],
            n => {
                // Find unique anchor suggestions around the first match location
                let suggestions = find_unique_anchor_suggestions(&lines, matches[0], &pattern);

                let suggestion_text = if suggestions.is_empty() {
                    String::new()
                } else {
                    format!(
                        "\nAdd an `@@ <anchor>` line above the hunk with one of these unique nearby lines:\n{}",
                        suggestions
                            .iter()
                            .map(|s| format!("  @@ {}", s))
                            .collect::<Vec<_>>()
                            .join("\n")
                    )
                };

                return Err(format!(
                    "hunk {} pattern matches {} locations; add an `@@ anchor` line above the hunk to disambiguate{}",
                    idx + 1, n, suggestion_text
                ));
            }
        };

        let end = pos + pattern.len();
        lines.splice(pos..end, replacement);
    }

    let mut result = lines.join("\n");
    if trailing_newline {
        result.push('\n');
    }
    Ok(result)
}

// ---- Tests -----------------------------------------------------------------

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

    fn p(input: &str) -> Patch {
        parse_patch(input).expect("parse")
    }

    // -- normalize_hunk_header ------------------------------------------

    #[test]
    fn parses_v4a_anchor() {
        assert_eq!(normalize_hunk_header("fn foo"), Some("fn foo".to_string()));
    }

    #[test]
    fn parses_unified_header_with_anchor() {
        assert_eq!(
            normalize_hunk_header("-10,5 +10,7 @@ pub use foo;"),
            Some("pub use foo;".to_string())
        );
    }

    #[test]
    fn parses_unified_header_without_anchor() {
        assert_eq!(normalize_hunk_header("-10,5 +10,7 @@"), None);
    }

    #[test]
    fn parses_unified_header_singular_counts() {
        assert_eq!(
            normalize_hunk_header("-10 +10 @@ fn bar"),
            Some("fn bar".to_string())
        );
    }

    #[test]
    fn normalize_empty_returns_none() {
        assert_eq!(normalize_hunk_header(""), None);
        assert_eq!(normalize_hunk_header("  "), None);
    }

    #[test]
    fn normalize_non_unified_returns_whole() {
        assert_eq!(
            normalize_hunk_header("some random text"),
            Some("some random text".to_string())
        );
    }

    #[test]
    fn normalize_unified_with_extra_whitespace() {
        assert_eq!(
            normalize_hunk_header("  -14,6 +14,28 @@  pub use mock::MockProvider;  "),
            Some("pub use mock::MockProvider;".to_string())
        );
    }

    // -- parser ----------------------------------------------------------

    #[test]
    fn parse_update_single_hunk() {
        let patch = p("\
*** Begin Patch
*** Update File: a.txt
 keep
-old
+new
*** End Patch
");
        assert_eq!(patch.ops.len(), 1);
        match &patch.ops[0] {
            FileOp::Update { path, hunks } => {
                assert_eq!(path, "a.txt");
                assert_eq!(hunks.len(), 1);
                assert_eq!(hunks[0].anchor, None);
                assert_eq!(
                    hunks[0].lines,
                    vec![
                        HunkLine::Context("keep".into()),
                        HunkLine::Remove("old".into()),
                        HunkLine::Add("new".into()),
                    ]
                );
            }
            _ => panic!("wrong op"),
        }
    }

    #[test]
    fn parse_multi_hunk_with_anchors() {
        let patch = p("\
*** Begin Patch
*** Update File: a.txt
@@ fn foo
 a
-b
+B
@@ fn bar
 c
-d
+D
*** End Patch
");
        match &patch.ops[0] {
            FileOp::Update { hunks, .. } => {
                assert_eq!(hunks.len(), 2);
                assert_eq!(hunks[0].anchor.as_deref(), Some("fn foo"));
                assert_eq!(hunks[1].anchor.as_deref(), Some("fn bar"));
            }
            _ => panic!(),
        }
    }

    #[test]
    fn parse_unified_header_hunk() {
        // A hunk header in unified-diff style should be accepted.
        let patch = p("\
*** Begin Patch
*** Update File: a.txt
@@ -10,5 +10,7 @@ pub use foo;
 a
-b
+B
*** End Patch
");
        match &patch.ops[0] {
            FileOp::Update { hunks, .. } => {
                assert_eq!(hunks.len(), 1);
                assert_eq!(hunks[0].anchor.as_deref(), Some("pub use foo;"));
            }
            _ => panic!(),
        }
    }

    #[test]
    fn parse_unified_header_no_anchor() {
        let patch = p("\
*** Begin Patch
*** Update File: a.txt
@@ -10,5 +10,7 @@
 a
-b
+B
*** End Patch
");
        match &patch.ops[0] {
            FileOp::Update { hunks, .. } => {
                assert_eq!(hunks.len(), 1);
                assert_eq!(hunks[0].anchor, None);
            }
            _ => panic!(),
        }
    }

    #[test]
    fn parse_add_file_collects_plus_lines() {
        let patch = p("\
*** Begin Patch
*** Add File: new.txt
+hello
+world
*** End Patch
");
        match &patch.ops[0] {
            FileOp::Add { path, content } => {
                assert_eq!(path, "new.txt");
                assert_eq!(content, "hello\nworld");
            }
            _ => panic!(),
        }
    }

    #[test]
    fn parse_delete_file() {
        let patch = p("\
*** Begin Patch
*** Delete File: doomed.txt
*** End Patch
");
        assert!(matches!(&patch.ops[0], FileOp::Delete { path, .. } if path == "doomed.txt"));
    }

    #[test]
    fn parse_rejects_missing_begin() {
        let e = parse_patch("hello\n*** End Patch\n").unwrap_err();
        assert!(e.contains("first line"));
    }

    #[test]
    fn parse_rejects_missing_end() {
        let e = parse_patch("*** Begin Patch\n*** Update File: a\n keep\n").unwrap_err();
        assert!(e.contains("terminated"));
    }

    #[test]
    fn parse_rejects_duplicate_path() {
        let e = parse_patch(
            "\
*** Begin Patch
*** Add File: a.txt
+x
*** Delete File: a.txt
*** End Patch
",
        )
        .unwrap_err();
        assert!(e.contains("more than once"));
    }

    #[test]
    fn parse_rejects_body_without_header() {
        let e = parse_patch("*** Begin Patch\n+stray\n*** End Patch\n").unwrap_err();
        assert!(e.contains("before any"));
    }

    #[test]
    fn parse_rejects_hunk_without_changes() {
        let e = parse_patch(
            "\
*** Begin Patch
*** Update File: a
 just
 context
*** End Patch
",
        )
        .unwrap_err();
        assert!(e.contains("no +/- lines"));
    }

    // -- applier (in-memory) --------------------------------------------

    #[test]
    fn applies_single_hunk_round_trip() {
        let original = "line1\nold\nline3\n";
        let patch = p("\
*** Begin Patch
*** Update File: f
 line1
-old
+new
 line3
*** End Patch
");
        let FileOp::Update { hunks, .. } = &patch.ops[0] else {
            panic!()
        };
        let updated = apply_hunks(original, hunks).unwrap();
        assert_eq!(updated, "line1\nnew\nline3\n");
    }

    #[test]
    fn applies_multi_hunk() {
        let original = "alpha\nbeta\ngamma\ndelta\n";
        let hunks = vec![
            Hunk {
                anchor: None,
                lines: vec![
                    HunkLine::Context("alpha".into()),
                    HunkLine::Remove("beta".into()),
                    HunkLine::Add("BETA".into()),
                ],
            },
            Hunk {
                anchor: None,
                lines: vec![
                    HunkLine::Context("gamma".into()),
                    HunkLine::Remove("delta".into()),
                    HunkLine::Add("DELTA".into()),
                ],
            },
        ];
        assert_eq!(
            apply_hunks(original, &hunks).unwrap(),
            "alpha\nBETA\ngamma\nDELTA\n"
        );
    }

    #[test]
    fn errors_when_pattern_not_found() {
        let e = apply_hunks(
            "hello\nworld\n",
            &[Hunk {
                anchor: None,
                lines: vec![
                    HunkLine::Context("foo".into()),
                    HunkLine::Remove("bar".into()),
                    HunkLine::Add("baz".into()),
                ],
            }],
        )
        .unwrap_err();
        assert!(e.contains("not found"));
    }

    #[test]
    fn errors_when_pattern_ambiguous() {
        let original = "x\ny\nx\ny\n";
        let e = apply_hunks(
            original,
            &[Hunk {
                anchor: None,
                lines: vec![
                    HunkLine::Context("x".into()),
                    HunkLine::Remove("y".into()),
                    HunkLine::Add("Y".into()),
                ],
            }],
        )
        .unwrap_err();
        assert!(e.contains("matches"));
    }

    #[test]
    fn ambiguous_error_shows_unique_anchor_suggestions() {
        // File with duplicated context and unique function definitions nearby
        let original = "UNIQUE_FUNC_A()\n    x\n    y\n}\nUNIQUE_FUNC_B()\n    x\n    y\n}\nUNIQUE_FUNC_C() {}\n";
        let hunks = vec![Hunk {
            anchor: None,
            lines: vec![
                HunkLine::Context("    x".into()),
                HunkLine::Remove("    y".into()),
                HunkLine::Add("    Y".into()),
            ],
        }];
        let e = apply_hunks(original, &hunks).unwrap_err();

        // Should mention multiple matches
        assert!(e.contains("matches"));
        // Should contain anchor suggestion section
        assert!(e.contains("@@ <anchor>"));
        // Should contain at least one unique suggestion that exists in the original
        assert!(
            e.contains("UNIQUE_FUNC_A")
                || e.contains("UNIQUE_FUNC_B")
                || e.contains("UNIQUE_FUNC_C")
        );
    }

    #[test]
    fn anchor_disambiguates_repeated_context() {
        // Two regions, same shape, anchor picks the second.
        let original = "fn foo {\n  x\n  y\n}\nfn bar {\n  x\n  y\n}\n";
        let hunks = vec![Hunk {
            anchor: Some("fn bar".into()),
            lines: vec![
                HunkLine::Context("  x".into()),
                HunkLine::Remove("  y".into()),
                HunkLine::Add("  Y".into()),
            ],
        }];
        let out = apply_hunks(original, &hunks).unwrap();
        assert_eq!(out, "fn foo {\n  x\n  y\n}\nfn bar {\n  x\n  Y\n}\n");
    }

    #[test]
    fn preserves_no_trailing_newline() {
        let original = "a\nb";
        let hunks = vec![Hunk {
            anchor: None,
            lines: vec![
                HunkLine::Remove("a".into()),
                HunkLine::Add("A".into()),
                HunkLine::Context("b".into()),
            ],
        }];
        assert_eq!(apply_hunks(original, &hunks).unwrap(), "A\nb");
    }

    // -- end-to-end (tool) ---------------------------------------------

    #[tokio::test]
    async fn tool_updates_existing_file() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("hello.txt"), "before\n").unwrap();
        let tool = ApplyPatch::new(tmp.path());
        let result = tool
            .execute(json!({"patch": "\
*** Begin Patch
*** Update File: hello.txt
-before
+after
*** End Patch
"}))
            .await
            .unwrap();
        assert!(result.contains("wrote hello.txt"));
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("hello.txt")).unwrap(),
            "after\n"
        );
    }

    #[tokio::test]
    async fn tool_adds_new_file() {
        let tmp = TempDir::new().unwrap();
        let tool = ApplyPatch::new(tmp.path());
        tool.execute(json!({"patch": "\
*** Begin Patch
*** Add File: sub/new.txt
+hi
+there
*** End Patch
"}))
            .await
            .unwrap();
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("sub/new.txt")).unwrap(),
            "hi\nthere"
        );
    }

    #[tokio::test]
    async fn tool_deletes_existing_file() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("doomed.txt"), "x").unwrap();
        ApplyPatch::new(tmp.path())
            .execute(json!({"patch": "\
*** Begin Patch
*** Delete File: doomed.txt
*** End Patch
"}))
            .await
            .unwrap();
        assert!(!tmp.path().join("doomed.txt").exists());
    }

    #[tokio::test]
    async fn tool_is_atomic_on_failure() {
        // Two-file patch: first hunk succeeds (would update a.txt), second fails.
        // After apply, neither file should be modified.
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("a.txt"), "original-a\n").unwrap();
        std::fs::write(tmp.path().join("b.txt"), "original-b\n").unwrap();
        let err = ApplyPatch::new(tmp.path())
            .execute(json!({"patch": "\
*** Begin Patch
*** Update File: a.txt
-original-a
+changed-a
*** Update File: b.txt
-nonexistent-line
+changed-b
*** End Patch
"}))
            .await
            .unwrap_err();
        assert!(matches!(err, Error::Tool { .. }));
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("a.txt")).unwrap(),
            "original-a\n"
        );
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("b.txt")).unwrap(),
            "original-b\n"
        );
    }

    #[tokio::test]
    async fn tool_rejects_add_when_file_exists() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("exists.txt"), "x").unwrap();
        let err = ApplyPatch::new(tmp.path())
            .execute(json!({"patch": "\
*** Begin Patch
*** Add File: exists.txt
+content
*** End Patch
"}))
            .await
            .unwrap_err();
        assert!(matches!(err, Error::Tool { .. }));
    }

    #[tokio::test]
    async fn tool_rejects_delete_when_file_missing() {
        let tmp = TempDir::new().unwrap();
        let err = ApplyPatch::new(tmp.path())
            .execute(json!({"patch": "\
*** Begin Patch
*** Delete File: ghost.txt
*** End Patch
"}))
            .await
            .unwrap_err();
        assert!(matches!(err, Error::Tool { .. }));
    }

    #[tokio::test]
    async fn tool_rejects_sandbox_escape() {
        let tmp = TempDir::new().unwrap();
        let err = ApplyPatch::new(tmp.path())
            .execute(json!({"patch": "\
*** Begin Patch
*** Add File: ../escape.txt
+evil
*** End Patch
"}))
            .await
            .unwrap_err();
        // Wrapped as a Tool error (resolve_within returned BadToolArgs internally,
        // but we re-wrapped it). Just check it failed.
        assert!(matches!(err, Error::Tool { .. }));
        assert!(!tmp.path().parent().unwrap().join("escape.txt").exists());
    }

    #[tokio::test]
    async fn tool_round_trips_a_real_change() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("lib.rs"),
            "\
fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn sub(a: i32, b: i32) -> i32 {
    a - b
}
",
        )
        .unwrap();
        let tool = ApplyPatch::new(tmp.path());
        tool.execute(json!({"patch": "\
*** Begin Patch
*** Update File: lib.rs
@@ fn sub
 fn sub(a: i32, b: i32) -> i32 {
-    a - b
+    a.saturating_sub(b)
 }
*** End Patch
"}))
            .await
            .unwrap();
        let got = std::fs::read_to_string(tmp.path().join("lib.rs")).unwrap();
        assert!(got.contains("a.saturating_sub(b)"));
        assert!(got.contains("a + b"), "add() unchanged");
    }

    #[tokio::test]
    async fn tool_applies_patch_with_unified_header() {
        // End-to-end test using a unified-diff-style header.
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("greeting.txt"), "hello\nworld\n").unwrap();
        let tool = ApplyPatch::new(tmp.path());
        tool.execute(json!({"patch": "\
*** Begin Patch
*** Update File: greeting.txt
@@ -1,3 +1,4 @@ hello
 hello
-world
+earth
*** End Patch
"}))
            .await
            .unwrap();
        let got = std::fs::read_to_string(tmp.path().join("greeting.txt")).unwrap();
        assert_eq!(got, "hello\nearth\n");
    }

    #[tokio::test]
    async fn dry_run_returns_summary_and_does_not_write() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("target.txt"), "before\n").unwrap();
        let tool = ApplyPatch::new(tmp.path());
        let result = tool
            .execute(json!({"patch": "\
*** Begin Patch
*** Update File: target.txt
-before
+after
*** End Patch
", "dry_run": true}))
            .await
            .unwrap();
        assert!(result.contains("dry-run: would apply"));
        assert!(result.contains("target.txt"));
        // File must be unchanged
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("target.txt")).unwrap(),
            "before\n"
        );
    }

    #[tokio::test]
    async fn dry_run_errors_on_ambiguous_anchor() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("dup.txt"), "x\ny\nx\ny\n").unwrap();
        let tool = ApplyPatch::new(tmp.path());
        let err = tool
            .execute(json!({"patch": "\
*** Begin Patch
*** Update File: dup.txt
 x
-y
+Y
*** End Patch
", "dry_run": true}))
            .await
            .unwrap_err();
        assert!(matches!(err, Error::Tool { .. }));
        let msg = format!("{}", err);
        assert!(
            msg.contains("matches"),
            "error should mention multiple matches: {msg}"
        );
    }

    #[tokio::test]
    async fn dry_run_false_is_same_as_omitting_field() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("test.txt"), "old\n").unwrap();
        let tool = ApplyPatch::new(tmp.path());
        tool.execute(json!({"patch": "\
*** Begin Patch
*** Update File: test.txt
-old
+new
*** End Patch
", "dry_run": false}))
            .await
            .unwrap();
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("test.txt")).unwrap(),
            "new\n"
        );
    }
}