dpc-tau-ext-shell 0.2.0

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

use std::collections::HashSet;
use std::io as path_std_io;
use std::path::{Path, PathBuf};

use tau_proto::{CborValue, ToolUsePayload};

use crate::diff::compute_diff;
use crate::display::{ToolFailure, ToolOutput};
use crate::tools::find::escape_path_text;
use crate::tools::world::{MAX_SAFE_FILE_READ_BYTES, ShellWorld};

const SUMMARY_HEADER: &str = "Success. Updated the following files:";
const MAX_CONTEXT_MISMATCH_DETAIL_BYTES: usize = 4 * 1024;
const MAX_CONTEXT_MISMATCH_PATH_BYTES: usize = 1024;

#[expect(unused)]
pub(crate) const APPLY_PATCH_LARK_GRAMMAR: &str = include_str!("apply_patch.lark");

pub(crate) fn apply_patch(
    arguments: &CborValue,
    world: &mut ShellWorld,
) -> Result<ToolOutput, ToolFailure> {
    let patch = patch_text(arguments)?;

    let hunks = parse_patch(patch).map_err(ToolFailure::new)?;
    let changes = match apply_hunks(&hunks, world) {
        Ok(changes) => changes,
        Err(failure) => {
            let details = failure_details(&failure);
            let mut tool_failure = ToolFailure::new(failure.message)
                .with_payload(display_payload_for_failure(&failure.changes));
            populate_change_display(&mut tool_failure.display, &failure.changes);
            if let Some(details) = details {
                tool_failure = tool_failure.with_details(details);
            }
            return Err(tool_failure);
        }
    };

    let summary = format_summary(&changes);
    let payload = display_payload_for_changes(&changes, &summary);
    let result = CborValue::Text(summary.clone());

    let mut display = crate::display::ok_display("");
    populate_change_display(&mut display, &changes);
    display.payload = payload;
    Ok(ToolOutput {
        result,
        provider_content: Vec::new(),
        display,
    })
}

pub(crate) fn lock_directories_in_dir(
    arguments: &CborValue,
    cwd: &Path,
) -> Result<Vec<PathBuf>, ToolFailure> {
    let patch = patch_text(arguments)?;
    let hunks = parse_patch(patch).map_err(ToolFailure::new)?;
    let mut dirs = Vec::new();

    for hunk in &hunks {
        match hunk {
            Hunk::Add { path, .. } => {
                let abs = resolve_path(cwd, path);
                dirs.push(crate::dir_lock::canonical_write_lock_dir(&abs)?);
            }
            Hunk::Delete { path } => {
                let abs = resolve_path(cwd, path);
                dirs.push(crate::dir_lock::canonical_path_parent(&abs)?);
            }
            Hunk::Update {
                path, move_path, ..
            } => {
                let abs = resolve_path(cwd, path);
                if let Some(move_path) = move_path {
                    dirs.push(crate::dir_lock::canonical_path_parent(&abs)?);
                    let dest_abs = resolve_path(cwd, move_path);
                    dirs.push(crate::dir_lock::canonical_write_lock_dir(&dest_abs)?);
                } else {
                    dirs.push(crate::dir_lock::canonical_update_lock_dir(&abs)?);
                }
            }
        }
    }

    Ok(dirs)
}

fn patch_text(arguments: &CborValue) -> Result<&str, ToolFailure> {
    match arguments {
        CborValue::Text(text) => Ok(text),
        _ => Err(ToolFailure::new(
            "apply_patch expects freeform patch text, not a structured payload",
        )),
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum Hunk {
    Add {
        path: PathBuf,
        contents: String,
    },
    Delete {
        path: PathBuf,
    },
    Update {
        path: PathBuf,
        move_path: Option<PathBuf>,
        chunks: Vec<UpdateChunk>,
    },
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct UpdateChunk {
    change_context: Option<String>,
    old_lines: Vec<String>,
    new_lines: Vec<String>,
    is_end_of_file: bool,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ChangeStatus {
    Add,
    Modify,
    Delete,
}

impl ChangeStatus {
    fn short_name(self) -> &'static str {
        match self {
            Self::Add => "A",
            Self::Modify => "M",
            Self::Delete => "D",
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct AppliedChange {
    display_path: String,
    path: PathBuf,
    status: ChangeStatus,
    old_content: String,
    new_content: Option<String>,
}

#[derive(Debug, Eq, PartialEq)]
/// One failed patch application plus truthful evidence of any earlier effects.
struct ApplyPatchFailure {
    /// Single-line provider-visible failure summary.
    message: String,
    /// Optional bounded multiline recovery body.
    recovery_output: Option<String>,
    /// Files changed before the failure occurred.
    changes: Vec<AppliedChange>,
}

impl ApplyPatchFailure {
    fn new(message: impl Into<String>, changes: &[AppliedChange]) -> Self {
        Self {
            message: message.into(),
            recovery_output: None,
            changes: changes.to_vec(),
        }
    }

    fn with_recovery_output(mut self, recovery_output: String) -> Self {
        self.recovery_output = Some(recovery_output);
        self
    }
}

fn apply_hunks(
    hunks: &[Hunk],
    world: &mut ShellWorld,
) -> Result<Vec<AppliedChange>, ApplyPatchFailure> {
    if hunks.is_empty() {
        return Err(ApplyPatchFailure::new("No files were modified.", &[]));
    }

    HunkApplier::new(world, hunks.len()).apply(hunks)
}

struct HunkApplier<'world> {
    /// Filesystem abstraction used for reads, writes, and deletes.
    world: &'world mut ShellWorld,
    /// Directory used to resolve relative patch paths.
    cwd: PathBuf,
    /// Changes already applied, used both for summaries and partial failures.
    changes: Vec<AppliedChange>,
}

impl<'world> HunkApplier<'world> {
    fn new(world: &'world mut ShellWorld, expected_hunks: usize) -> Self {
        Self {
            cwd: world.current_dir().to_path_buf(),
            world,
            changes: Vec::with_capacity(expected_hunks),
        }
    }

    fn apply(mut self, hunks: &[Hunk]) -> Result<Vec<AppliedChange>, ApplyPatchFailure> {
        for hunk in hunks {
            self.apply_hunk(hunk)?;
        }
        Ok(self.changes)
    }

    fn apply_hunk(&mut self, hunk: &Hunk) -> Result<(), ApplyPatchFailure> {
        match hunk {
            Hunk::Add { path, contents } => {
                self.apply_add(path, contents)?;
            }
            Hunk::Delete { path } => {
                self.apply_delete(path)?;
            }
            Hunk::Update {
                path,
                move_path,
                chunks,
            } => {
                self.apply_update(path, move_path.as_deref(), chunks)?;
            }
        }
        Ok(())
    }

    fn apply_add(&mut self, path: &Path, contents: &str) -> Result<(), ApplyPatchFailure> {
        let abs = resolve_path(&self.cwd, path);
        if self.read_optional_file(&abs)?.is_some() {
            return Err(self.failure(format!(
                "Add File target already exists: {}",
                render_path(&abs)
            )));
        }
        write_file_creating_parent(&abs, contents, self.world).map_err(|error| {
            self.failure(format!(
                "Failed to write file {}: {}",
                render_path(&abs),
                render_diagnostic(error)
            ))
        })?;
        self.changes.push(AppliedChange {
            display_path: render_path(path),
            path: abs,
            status: ChangeStatus::Add,
            old_content: String::new(),
            new_content: Some(contents.to_owned()),
        });
        Ok(())
    }

    fn apply_delete(&mut self, path: &Path) -> Result<(), ApplyPatchFailure> {
        let abs = resolve_path(&self.cwd, path);
        self.ensure_not_dir_for_delete(&abs)?;
        let old_content = self.read_file_to_delete(&abs)?;
        self.remove_file_to_delete(&abs)?;
        self.changes.push(AppliedChange {
            display_path: render_path(path),
            path: abs,
            status: ChangeStatus::Delete,
            old_content,
            new_content: None,
        });
        Ok(())
    }

    fn apply_update(
        &mut self,
        path: &Path,
        move_path: Option<&Path>,
        chunks: &[UpdateChunk],
    ) -> Result<(), ApplyPatchFailure> {
        let abs = resolve_path(&self.cwd, path);
        let old_content = self.read_file_to_update(&abs)?;
        let new_content =
            derive_new_contents_from_chunks(&abs, &old_content, chunks).map_err(|diagnostic| {
                let failure = self.failure(diagnostic.message);
                match diagnostic.recovery_output {
                    Some(output) => failure.with_recovery_output(output),
                    None => failure,
                }
            })?;

        if let Some(move_path) = move_path {
            self.apply_move_update(&abs, move_path, old_content, new_content)
        } else {
            self.apply_in_place_update(path, abs, old_content, new_content)
        }
    }

    fn apply_in_place_update(
        &mut self,
        path: &Path,
        abs: PathBuf,
        old_content: String,
        new_content: String,
    ) -> Result<(), ApplyPatchFailure> {
        self.world
            .write_file(&abs, new_content.as_bytes())
            .map_err(|error| {
                self.failure(format!(
                    "Failed to write file {}: {}",
                    render_path(&abs),
                    render_diagnostic(error)
                ))
            })?;
        self.changes.push(AppliedChange {
            display_path: render_path(path),
            path: abs,
            status: ChangeStatus::Modify,
            old_content,
            new_content: Some(new_content),
        });
        Ok(())
    }

    fn apply_move_update(
        &mut self,
        source_abs: &Path,
        move_path: &Path,
        old_content: String,
        new_content: String,
    ) -> Result<(), ApplyPatchFailure> {
        let dest_abs = resolve_path(&self.cwd, move_path);
        if self.read_optional_file(&dest_abs)?.is_some() {
            return Err(self.failure(format!(
                "Move destination already exists: {}",
                render_path(&dest_abs)
            )));
        }
        let dest_write_change_index =
            self.write_and_record_move_destination(move_path, &dest_abs, &new_content)?;
        self.remove_move_source(source_abs)?;
        // Until the source removal succeeds, failures must report the already
        // written destination as a partial Add. Only the fully successful move
        // is summarized as one Modify of the original file.
        self.changes[dest_write_change_index] = AppliedChange {
            display_path: render_path(move_path),
            path: source_abs.to_path_buf(),
            status: ChangeStatus::Modify,
            old_content,
            new_content: Some(new_content),
        };
        Ok(())
    }

    fn write_and_record_move_destination(
        &mut self,
        move_path: &Path,
        dest_abs: &Path,
        new_content: &str,
    ) -> Result<usize, ApplyPatchFailure> {
        write_file_creating_parent(dest_abs, new_content, self.world).map_err(|error| {
            self.failure(format!(
                "Failed to write file {}: {}",
                render_path(dest_abs),
                render_diagnostic(error)
            ))
        })?;
        let change_index = self.changes.len();
        self.changes.push(AppliedChange {
            display_path: render_path(move_path),
            path: dest_abs.to_path_buf(),
            status: ChangeStatus::Add,
            old_content: String::new(),
            new_content: Some(new_content.to_owned()),
        });
        Ok(change_index)
    }

    fn ensure_not_dir_for_delete(&mut self, abs: &Path) -> Result<(), ApplyPatchFailure> {
        if self
            .world
            .is_dir(abs)
            .map_err(|_| self.failure(format!("Failed to delete file {}", render_path(abs))))?
        {
            return Err(self.failure(format!("Failed to delete file {}", render_path(abs))));
        }
        Ok(())
    }

    fn read_file_to_delete(&mut self, abs: &Path) -> Result<String, ApplyPatchFailure> {
        self.world
            .read_to_string_limited(abs, MAX_SAFE_FILE_READ_BYTES)
            .map_err(|_| self.failure(format!("Failed to delete file {}", render_path(abs))))
    }

    fn remove_file_to_delete(&mut self, abs: &Path) -> Result<(), ApplyPatchFailure> {
        self.world
            .remove_file(abs)
            .map_err(|_| self.failure(format!("Failed to delete file {}", render_path(abs))))
    }

    fn read_file_to_update(&mut self, abs: &Path) -> Result<String, ApplyPatchFailure> {
        self.world
            .read_to_string_limited(abs, MAX_SAFE_FILE_READ_BYTES)
            .map_err(|error| {
                self.failure(format!(
                    "Failed to read file to update {}: {}",
                    render_path(abs),
                    render_diagnostic(error)
                ))
            })
    }

    fn remove_move_source(&mut self, source_abs: &Path) -> Result<(), ApplyPatchFailure> {
        let message = || format!("Failed to remove original {}", render_path(source_abs));
        if self
            .world
            .is_dir(source_abs)
            .map_err(|_| self.failure(message()))?
        {
            return Err(self.failure(message()));
        }
        self.world
            .remove_file(source_abs)
            .map_err(|_| self.failure(message()))
    }

    fn read_optional_file(&mut self, path: &Path) -> Result<Option<String>, ApplyPatchFailure> {
        read_optional_file(path, self.world).map_err(|message| self.failure(message))
    }

    fn failure(&self, message: impl Into<String>) -> ApplyPatchFailure {
        ApplyPatchFailure::new(message, &self.changes)
    }
}

fn display_payload_for_changes(changes: &[AppliedChange], summary: &str) -> Option<ToolUsePayload> {
    let files = changes
        .iter()
        .map(|change| {
            let new_content = change.new_content.as_deref().unwrap_or_default();
            tau_proto::FileDiffSummary {
                path: change.display_path.clone(),
                diff: compute_diff(&change.old_content, new_content),
            }
        })
        .collect::<Vec<_>>();
    if files.is_empty() {
        Some(ToolUsePayload::Text {
            text: summary.to_owned(),
        })
    } else {
        Some(ToolUsePayload::Diffs { files })
    }
}

fn display_payload_for_failure(changes: &[AppliedChange]) -> Option<ToolUsePayload> {
    if changes.is_empty() {
        return None;
    }

    let summary = format_partial_summary(changes);
    display_payload_for_changes(changes, &summary)
}

fn populate_change_display(display: &mut tau_proto::ToolUseState, changes: &[AppliedChange]) {
    let Some(first) = changes.first() else {
        return;
    };
    let mut distinct_paths = HashSet::new();
    for change in changes {
        distinct_paths.insert(change.display_path.as_str());
    }
    display.args = first.display_path.clone();
    if distinct_paths.len() > 1 {
        display.args.push_str(",…");
    }
    display
        .info_chips
        .push(format!("{}F", distinct_paths.len()));
}

fn failure_details(failure: &ApplyPatchFailure) -> Option<CborValue> {
    if failure.changes.is_empty() && failure.recovery_output.is_none() {
        return None;
    }

    let mut details = Vec::new();
    if let Some(output) = &failure.recovery_output {
        details.push((
            CborValue::Text("output".to_owned()),
            CborValue::Text(output.clone()),
        ));
    }
    let changes = failure
        .changes
        .iter()
        .map(|change| {
            CborValue::Map(vec![
                (
                    CborValue::Text("status".to_owned()),
                    CborValue::Text(change.status.short_name().to_owned()),
                ),
                (
                    CborValue::Text("path".to_owned()),
                    CborValue::Text(change.display_path.clone()),
                ),
            ])
        })
        .collect();
    if !failure.changes.is_empty() {
        details.push((
            CborValue::Text("partial_changes".to_owned()),
            CborValue::Array(changes),
        ));
    }
    Some(CborValue::Map(details))
}

fn format_partial_summary(changes: &[AppliedChange]) -> String {
    let mut lines = vec!["Partial changes applied before failure:".to_owned()];
    for status in [
        ChangeStatus::Add,
        ChangeStatus::Modify,
        ChangeStatus::Delete,
    ] {
        for change in changes.iter().filter(|change| change.status == status) {
            lines.push(format!(
                "{} {}",
                change.status.short_name(),
                change.display_path
            ));
        }
    }
    lines.join("\n")
}

fn format_summary(changes: &[AppliedChange]) -> String {
    let mut lines = vec![SUMMARY_HEADER.to_owned()];
    for status in [
        ChangeStatus::Add,
        ChangeStatus::Modify,
        ChangeStatus::Delete,
    ] {
        for change in changes.iter().filter(|change| change.status == status) {
            lines.push(format!(
                "{} {}",
                change.status.short_name(),
                change.display_path
            ));
        }
    }
    lines.join("\n")
}

fn render_path(path: &Path) -> String {
    escape_path_text(&path.display().to_string())
}

fn render_diagnostic(error: impl std::fmt::Display) -> String {
    escape_path_text(&error.to_string())
}

fn read_optional_file(path: &Path, world: &mut ShellWorld) -> Result<Option<String>, String> {
    match world.read_to_string_limited(path, MAX_SAFE_FILE_READ_BYTES) {
        Ok(content) => Ok(Some(content)),
        Err(error) if error.kind() == path_std_io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(render_diagnostic(error)),
    }
}

fn write_file_creating_parent(
    path: &Path,
    contents: &str,
    world: &mut ShellWorld,
) -> Result<(), std::io::Error> {
    if let Some(parent) = path.parent() {
        world.create_dir_all(parent)?;
    }
    world.write_file(path, contents.as_bytes())
}

fn resolve_path(cwd: &Path, path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        cwd.join(path)
    }
}

fn derive_new_contents_from_chunks(
    path: &Path,
    original_contents: &str,
    chunks: &[UpdateChunk],
) -> Result<String, UpdateDiagnostic> {
    let mut original_lines: Vec<String> = original_contents.split('\n').map(String::from).collect();
    if original_lines.last().is_some_and(String::is_empty) {
        original_lines.pop();
    }

    let replacements = compute_replacements(&original_lines, path, chunks)?;
    let mut new_lines = apply_replacements(original_lines, &replacements);
    if !new_lines.last().is_some_and(String::is_empty) {
        new_lines.push(String::new());
    }
    Ok(new_lines.join("\n"))
}

fn compute_replacements(
    original_lines: &[String],
    path: &Path,
    chunks: &[UpdateChunk],
) -> Result<Vec<(usize, usize, Vec<String>)>, UpdateDiagnostic> {
    let mut replacements = Vec::new();
    let mut line_index = 0usize;

    for chunk in chunks {
        if let Some(ctx_line) = &chunk.change_context {
            if let Some(idx) = seek_sequence(
                original_lines,
                std::slice::from_ref(ctx_line),
                line_index,
                false,
            ) {
                line_index = idx + 1;
            } else {
                return Err(UpdateDiagnostic::message(format!(
                    "Failed to find context '{}' in {}",
                    ctx_line,
                    render_path(path)
                )));
            }
        }

        if chunk.old_lines.is_empty() {
            let insertion_idx = if original_lines.last().is_some_and(String::is_empty) {
                original_lines.len().saturating_sub(1)
            } else {
                original_lines.len()
            };
            replacements.push((insertion_idx, 0, chunk.new_lines.clone()));
            continue;
        }

        let mut pattern: &[String] = &chunk.old_lines;
        let mut new_slice: &[String] = &chunk.new_lines;
        let mut found = seek_sequence(original_lines, pattern, line_index, chunk.is_end_of_file);

        if found.is_none() && pattern.last().is_some_and(String::is_empty) {
            pattern = &pattern[..pattern.len() - 1];
            if new_slice.last().is_some_and(String::is_empty) {
                new_slice = &new_slice[..new_slice.len() - 1];
            }
            found = seek_sequence(original_lines, pattern, line_index, chunk.is_end_of_file);
        }

        if let Some(start_idx) = found {
            replacements.push((start_idx, pattern.len(), new_slice.to_vec()));
            line_index = start_idx + pattern.len();
        } else {
            let rendered_path = render_path(path);
            return Err(UpdateDiagnostic {
                message: format!("Failed to find expected lines in {rendered_path}"),
                recovery_output: Some(bounded_context_mismatch_output(
                    &rendered_path,
                    &chunk.old_lines,
                )),
            });
        }
    }

    replacements.sort_by_key(|(start_idx, _, _)| *start_idx);
    Ok(replacements)
}

#[derive(Debug, Eq, PartialEq)]
/// Structured update-planning failure split into header and body content.
struct UpdateDiagnostic {
    /// Single-line diagnostic suitable for the provider-visible error header.
    message: String,
    /// Bounded multiline context intended for the provider-visible body.
    recovery_output: Option<String>,
}

impl UpdateDiagnostic {
    fn message(message: String) -> Self {
        Self {
            message,
            recovery_output: None,
        }
    }
}

fn bounded_context_mismatch_output(path: &str, expected_lines: &[String]) -> String {
    let path = truncate_utf8(path, MAX_CONTEXT_MISMATCH_PATH_BYTES, "...(path truncated)");
    let full = format!("Expected lines in {path}:\n{}", expected_lines.join("\n"));
    if full.len() <= MAX_CONTEXT_MISMATCH_DETAIL_BYTES {
        return full;
    }

    let marker = "\n...(context truncated)";
    let retained_bytes = MAX_CONTEXT_MISMATCH_DETAIL_BYTES.saturating_sub(marker.len());
    let retained_end = (0..=retained_bytes.min(full.len()))
        .rev()
        .find(|index| full.is_char_boundary(*index))
        .unwrap_or(0);
    format!("{}{marker}", &full[..retained_end])
}

fn truncate_utf8(value: &str, max_bytes: usize, marker: &str) -> String {
    if value.len() <= max_bytes {
        return value.to_owned();
    }
    let retained_bytes = max_bytes.saturating_sub(marker.len());
    let retained_end = (0..=retained_bytes.min(value.len()))
        .rev()
        .find(|index| value.is_char_boundary(*index))
        .unwrap_or(0);
    format!("{}{marker}", &value[..retained_end])
}

fn apply_replacements(
    mut lines: Vec<String>,
    replacements: &[(usize, usize, Vec<String>)],
) -> Vec<String> {
    for (start_idx, old_len, new_segment) in replacements.iter().rev() {
        for _ in 0..*old_len {
            if *start_idx < lines.len() {
                lines.remove(*start_idx);
            }
        }
        for (offset, new_line) in new_segment.iter().enumerate() {
            lines.insert(*start_idx + offset, new_line.clone());
        }
    }
    lines
}

fn seek_sequence(lines: &[String], pattern: &[String], start: usize, eof: bool) -> Option<usize> {
    if pattern.is_empty() {
        return Some(start);
    }
    if pattern.len() > lines.len() {
        return None;
    }

    let search_start = if eof && lines.len() >= pattern.len() {
        lines.len() - pattern.len()
    } else {
        start
    };

    for i in search_start..=lines.len().saturating_sub(pattern.len()) {
        if lines[i..i + pattern.len()] == *pattern {
            return Some(i);
        }
    }
    for i in search_start..=lines.len().saturating_sub(pattern.len()) {
        let ok = pattern
            .iter()
            .enumerate()
            .all(|(p_idx, pat)| lines[i + p_idx].trim_end() == pat.trim_end());
        if ok {
            return Some(i);
        }
    }
    for i in search_start..=lines.len().saturating_sub(pattern.len()) {
        let ok = pattern
            .iter()
            .enumerate()
            .all(|(p_idx, pat)| lines[i + p_idx].trim() == pat.trim());
        if ok {
            return Some(i);
        }
    }
    None
}

fn parse_patch(patch: &str) -> Result<Vec<Hunk>, String> {
    PatchParser::new(patch)?.parse()
}

// Parser section. This manually implements `apply_patch.lark`: begin/end
// sentinels are validated before parsing starts, and `index` only advances
// through body lines between the begin header and end footer.
struct PatchParser<'a> {
    lines: Vec<&'a str>,
    index: usize,
}

impl<'a> PatchParser<'a> {
    fn new(patch: &'a str) -> Result<Self, String> {
        let lines: Vec<&str> = patch.trim().lines().collect();
        if lines.first().copied() != Some("*** Begin Patch") {
            return Err("invalid patch: missing '*** Begin Patch' header".to_owned());
        }
        if lines.last().copied() != Some("*** End Patch") {
            return Err("invalid patch: missing '*** End Patch' footer".to_owned());
        }

        Ok(Self { lines, index: 1 })
    }

    fn parse(mut self) -> Result<Vec<Hunk>, String> {
        let mut hunks = Vec::new();
        while self.has_body_line() {
            hunks.push(self.parse_hunk()?);
        }

        if hunks.is_empty() {
            return Err("invalid patch: no file operations found".to_owned());
        }
        Ok(hunks)
    }

    fn parse_hunk(&mut self) -> Result<Hunk, String> {
        let line = self.current_line();
        if let Some(path) = line.strip_prefix("*** Add File: ") {
            return self.parse_add(path);
        }
        if let Some(path) = line.strip_prefix("*** Delete File: ") {
            return Ok(self.parse_delete(path));
        }
        if let Some(path) = line.strip_prefix("*** Update File: ") {
            return self.parse_update(path);
        }

        Err(format!(
            "invalid patch operation: {}",
            escape_path_text(line)
        ))
    }

    fn parse_add(&mut self, path: &str) -> Result<Hunk, String> {
        self.advance();
        let mut contents = Vec::new();
        while self.has_body_line() && !self.current_line().starts_with("*** ") {
            let Some(content) = self.current_line().strip_prefix('+') else {
                return Err(format!(
                    "invalid add-file line: {}",
                    escape_path_text(self.current_line())
                ));
            };
            contents.push(content.to_owned());
            self.advance();
        }

        if contents.is_empty() {
            return Err(format!(
                "Add File hunk for {} must contain at least one line",
                escape_path_text(path)
            ));
        }

        Ok(Hunk::Add {
            path: PathBuf::from(path),
            contents: contents.join("\n") + "\n",
        })
    }

    fn parse_delete(&mut self, path: &str) -> Hunk {
        self.advance();
        Hunk::Delete {
            path: PathBuf::from(path),
        }
    }

    fn parse_update(&mut self, path: &str) -> Result<Hunk, String> {
        self.advance();
        let move_path = self.parse_move_path();
        let mut chunks = Vec::new();

        while self.has_body_line() && !self.current_line().starts_with("*** ") {
            chunks.push(self.parse_update_chunk(path)?);
        }

        if chunks.is_empty() {
            return Err(format!(
                "Update File hunk for {} must contain at least one chunk",
                escape_path_text(path)
            ));
        }

        Ok(Hunk::Update {
            path: PathBuf::from(path),
            move_path,
            chunks,
        })
    }

    fn parse_move_path(&mut self) -> Option<PathBuf> {
        if self.has_body_line()
            && let Some(dest) = self.current_line().strip_prefix("*** Move to: ")
        {
            let move_path = PathBuf::from(dest);
            self.advance();
            Some(move_path)
        } else {
            None
        }
    }

    fn parse_update_chunk(&mut self, path: &str) -> Result<UpdateChunk, String> {
        let change_context = self.parse_update_header()?;
        let mut chunk = ParsedUpdateChunk::default();

        while self.has_body_line()
            && !self.current_line().starts_with("@@")
            && !self.current_line_is_patch_operation_boundary()
        {
            if self.current_line() == "*** End of File" {
                chunk.is_end_of_file = true;
                self.advance();
                break;
            }
            self.parse_update_line(&mut chunk)?;
            self.advance();
        }

        if chunk.old_lines.is_empty() && chunk.new_lines.is_empty() {
            return Err(format!(
                "Update File hunk for {} must contain at least one line",
                escape_path_text(path)
            ));
        }

        Ok(UpdateChunk {
            change_context,
            old_lines: chunk.old_lines,
            new_lines: chunk.new_lines,
            is_end_of_file: chunk.is_end_of_file,
        })
    }

    fn parse_update_header(&mut self) -> Result<Option<String>, String> {
        let header = self.current_line();
        let change_context = if header == "@@" {
            None
        } else if let Some(context) = header.strip_prefix("@@ ") {
            Some(context.to_owned())
        } else {
            return Err(format!(
                "invalid update hunk header: {}",
                escape_path_text(header)
            ));
        };
        self.advance();
        Ok(change_context)
    }

    fn parse_update_line(&self, chunk: &mut ParsedUpdateChunk) -> Result<(), String> {
        let line = self.current_line();
        let mut chars = line.chars();
        match chars.next() {
            None => {
                chunk.old_lines.push(String::new());
                chunk.new_lines.push(String::new());
            }
            Some(' ') => {
                let rest = chars.as_str().to_owned();
                chunk.old_lines.push(rest.clone());
                chunk.new_lines.push(rest);
            }
            Some('-') => {
                chunk.old_lines.push(chars.as_str().to_owned());
            }
            Some('+') => {
                chunk.new_lines.push(chars.as_str().to_owned());
            }
            _ => {
                return Err(format!(
                    "invalid update hunk line: {}",
                    escape_path_text(line)
                ));
            }
        }
        Ok(())
    }

    fn current_line(&self) -> &'a str {
        self.lines[self.index]
    }

    fn advance(&mut self) {
        self.index += 1;
    }

    fn has_body_line(&self) -> bool {
        self.index + 1 < self.lines.len()
    }

    fn current_line_is_patch_operation_boundary(&self) -> bool {
        self.current_line().starts_with("*** ") && self.current_line() != "*** End of File"
    }
}

#[derive(Default)]
struct ParsedUpdateChunk {
    old_lines: Vec<String>,
    new_lines: Vec<String>,
    is_end_of_file: bool,
}

#[cfg(test)]
mod tests;