ayaml-edit 1.0.0

Verified source-preserving edits for YAML documents built on ayaml.
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
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
#![forbid(unsafe_code)]
#![warn(rustdoc::all)]

//! Verified, source-preserving edits for YAML documents built on [`ayaml`]'s public API.
//!
//! Every edit returned by this crate is reparsed and checked against both the expected
//! [`Value`] tree and the [`Event`] stream before it is returned.
//! Constructs whose source-preserving edit rules are not yet proven exact — anchors, aliases,
//! tags, block scalars, multiple documents, merge-key expansion, and ambiguous comment placement
//! — are refused conservatively.

use std::cmp::Ordering;
use std::fmt;

use ayaml::{
    EmitOptions, Event, Limits, ParseOptions, PathSegment, ScalarStyle, Span, SpannedTree, Value,
    parse_events_with, parse_value_with, to_string_value_with,
};

/// A single byte-range replacement against a source string.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TextEdit {
    span: Span,
    replacement: String,
}

impl TextEdit {
    /// Create a text edit replacing `span` with `replacement`.
    #[must_use]
    pub fn new(span: Span, replacement: impl Into<String>) -> Self {
        Self {
            span,
            replacement: replacement.into(),
        }
    }

    /// The byte span in the original source text.
    #[must_use]
    pub const fn span(&self) -> Span {
        self.span
    }

    /// The replacement text substituted for [`Self::span`].
    #[must_use]
    pub fn replacement(&self) -> &str {
        &self.replacement
    }

    /// Whether this edit inserts text at a zero-width byte offset.
    #[must_use]
    pub const fn is_insertion(&self) -> bool {
        self.span.is_empty()
    }
}

/// Pure span ordering: ascending start offset, with zero-width insertions ordered before
/// replacements starting at the same byte offset, then ascending end offset.
fn span_order(a: Span, b: Span) -> Ordering {
    a.start()
        .cmp(&b.start())
        .then_with(|| b.is_empty().cmp(&a.is_empty()))
        .then_with(|| a.end().cmp(&b.end()))
}

/// Ordering for [`TextEdit`]: delegates to [`span_order`].
fn edit_order(a: &TextEdit, b: &TextEdit) -> Ordering {
    span_order(a.span, b.span)
}

/// Validate a single edit span against `input` bounds, UTF-8 character boundaries, and `prev_end`.
fn validate_edit_span(input: &str, span: Span, prev_end: usize) -> Result<usize, &'static str> {
    let start = span.start();
    let end = span.end();
    if start > end || end > input.len() {
        return Err("text edit span is out of bounds");
    }
    if !input.is_char_boundary(start) || !input.is_char_boundary(end) {
        return Err("text edit span does not lie on UTF-8 character boundaries");
    }
    if start < prev_end {
        return Err("text edits must be sorted and non-overlapping");
    }
    Ok(end)
}

/// Validate ordering and non-overlap between two adjacent edit spans.
fn validate_adjacent_spans(prev: Span, next: Span) -> Result<(), &'static str> {
    if span_order(prev, next) == Ordering::Greater {
        return Err(
            "text edits must be sorted with insertions before replacements at the same offset",
        );
    }
    if prev.start() == next.start() && !prev.is_empty() && !next.is_empty() {
        return Err("overlapping text edits at the same offset");
    }
    Ok(())
}

/// The verified result of one or more YAML edits.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct VerifiedEdit {
    output: String,
    edits: Vec<TextEdit>,
}

impl VerifiedEdit {
    /// The resulting YAML document text.
    #[must_use]
    pub fn output(&self) -> &str {
        &self.output
    }

    /// Consume the verified edit and return the resulting YAML document text.
    #[must_use]
    pub fn into_output(self) -> String {
        self.output
    }

    /// The sorted, non-overlapping [`TextEdit`]s that transform the original input into
    /// [`Self::output`]. When two edits share a start offset, an insertion appears first.
    #[must_use]
    pub fn edits(&self) -> &[TextEdit] {
        &self.edits
    }
}

/// Coarse category of an [`EditError`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EditErrorKind {
    /// The input YAML document could not be parsed.
    Parse,
    /// The target path did not resolve unambiguously in the document.
    NotFound,
    /// The requested edit was refused conservatively (for example, anchors, aliases, tags,
    /// block scalars, multiple documents, flow entries, or ambiguous comment placement).
    Unsupported,
    /// Post-edit re-parse or event/value verification failed.
    VerificationFailed,
    /// Supplied [`TextEdit`]s were unsorted, overlapping, or out of UTF-8 bounds.
    InvalidEdit,
}

impl fmt::Display for EditErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let label = match self {
            Self::Parse => "parse error",
            Self::NotFound => "target not found",
            Self::Unsupported => "unsupported edit",
            Self::VerificationFailed => "verification failed",
            Self::InvalidEdit => "invalid edit",
        };
        f.write_str(label)
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct EditErrorInner {
    kind: EditErrorKind,
    message: String,
    source: Option<ayaml::Error>,
}

/// An error returned when an edit cannot be constructed or verified.
///
/// Normal [`Display`](fmt::Display) and [`Debug`](fmt::Debug) output on [`EditError`] (and
/// [`std::error::Error::source`]) may include text from the YAML document when parsing failed.
/// Use [`EditError::masked`] ([`MaskedEditError`]) when logging or returning diagnostics from
/// sensitive or untrusted documents.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EditError(Box<EditErrorInner>);

impl EditError {
    fn new(kind: EditErrorKind, message: impl Into<String>) -> Self {
        Self(Box::new(EditErrorInner {
            kind,
            message: message.into(),
            source: None,
        }))
    }

    fn parse(error: ayaml::Error) -> Self {
        Self(Box::new(EditErrorInner {
            kind: EditErrorKind::Parse,
            message: error.to_string(),
            source: Some(error),
        }))
    }

    fn verification_with_source(message: impl Into<String>, source: ayaml::Error) -> Self {
        Self(Box::new(EditErrorInner {
            kind: EditErrorKind::VerificationFailed,
            message: message.into(),
            source: Some(source),
        }))
    }

    /// The coarse error category.
    #[must_use]
    pub fn kind(&self) -> EditErrorKind {
        self.0.kind
    }

    /// Human-readable description of why the edit failed or was refused.
    ///
    /// For [`EditErrorKind::Parse`], this message may include text from the YAML document;
    /// use [`Self::masked`] when redaction is required.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.0.message
    }

    /// Return a view whose [`Display`](fmt::Display) and [`Debug`](fmt::Debug) output exclude all
    /// YAML document text.
    ///
    /// Mirrors [`ayaml::Error::masked`]: reports only the [`EditErrorKind`] and, when an
    /// underlying [`ayaml::Error`] caused the failure, its [`ayaml::MaskedError`] view. Its
    /// [`std::error::Error::source`] always returns `None` so an unmasked cause cannot leak
    /// through error-chain formatters.
    #[must_use]
    pub const fn masked(&self) -> MaskedEditError<'_> {
        MaskedEditError(self)
    }
}

impl fmt::Display for EditError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0.message)
    }
}

impl std::error::Error for EditError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.0.source.as_ref().map(|error| {
            let err: &(dyn std::error::Error + 'static) = error;
            err
        })
    }
}

/// A view of an [`EditError`] whose [`Display`](fmt::Display) and [`Debug`](fmt::Debug) forms
/// exclude all YAML document text.
///
/// Returned by [`EditError::masked`]. Its [`std::error::Error::source`] always returns `None` so
/// error-chain formatters cannot expose an unmasked underlying [`ayaml::Error`].
#[derive(Clone, Copy)]
pub struct MaskedEditError<'a>(&'a EditError);

impl<'a> MaskedEditError<'a> {
    /// The coarse error category.
    #[must_use]
    pub fn kind(&self) -> EditErrorKind {
        self.0.kind()
    }

    /// The masked view of the underlying [`ayaml::Error`], if one caused this error.
    #[must_use]
    pub fn source_error(&self) -> Option<ayaml::MaskedError<'a>> {
        self.0.0.source.as_ref().map(ayaml::Error::masked)
    }
}

impl PartialEq for MaskedEditError<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.kind() == other.kind() && self.source_error() == other.source_error()
    }
}

impl Eq for MaskedEditError<'_> {}

impl fmt::Display for MaskedEditError<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.source_error() {
            Some(source) => write!(f, "{}: {source}", self.kind()),
            None => fmt::Display::fmt(&self.kind(), f),
        }
    }
}

impl fmt::Debug for MaskedEditError<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MaskedEditError")
            .field("kind", &self.kind())
            .field("source", &self.source_error())
            .finish()
    }
}

impl std::error::Error for MaskedEditError<'_> {}

/// Options controlling how documents are parsed and verified during editing.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct EditOptions {
    parse: ParseOptions,
}

impl EditOptions {
    /// Default edit options using [`ParseOptions::new`].
    #[must_use]
    pub const fn new() -> Self {
        Self {
            parse: ParseOptions::new(),
        }
    }

    /// Set the [`ParseOptions`] used to parse and re-verify documents.
    #[must_use]
    pub const fn with_parse_options(mut self, options: ParseOptions) -> Self {
        self.parse = options;
        self
    }

    /// The active [`ParseOptions`].
    #[must_use]
    pub const fn parse_options(&self) -> &ParseOptions {
        &self.parse
    }
}

/// One edit operation for [`apply_batch`] / [`apply_batch_with`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum EditOp {
    /// Replace the scalar at `path` with `value`.
    ReplaceScalar {
        /// Path to the target scalar.
        path: Vec<PathSegment>,
        /// New scalar value (must be null, bool, number, or string).
        value: Value,
    },
    /// Remove the block entry at `path`.
    RemoveEntry {
        /// Path to the target entry.
        path: Vec<PathSegment>,
    },
}

/// Pure arithmetic step for spliced output byte length (shared with Kani proofs).
const fn step_spliced_len(len: usize, span: Span, replacement_len: usize) -> Option<usize> {
    let span_len = span.end().saturating_sub(span.start());
    match len.checked_sub(span_len) {
        Some(base) => base.checked_add(replacement_len),
        None => None,
    }
}

/// Compute the exact spliced output byte length from `(span, replacement_len)` pairs without
/// allocating.
#[cfg(any(test, kani))]
fn spliced_output_len_pairs(
    input_len: usize,
    edits: &[(Span, usize)],
) -> Result<usize, &'static str> {
    let mut len = input_len;
    for &(span, replacement_len) in edits {
        len = step_spliced_len(len, span, replacement_len)
            .ok_or("edited output length overflows usize")?;
    }
    Ok(len)
}

/// Compute the exact spliced output byte length for validated non-overlapping edits.
fn spliced_output_len(input_len: usize, edits: &[TextEdit]) -> Result<usize, &'static str> {
    let mut len = input_len;
    for edit in edits {
        len = step_spliced_len(len, edit.span, edit.replacement.len())
            .ok_or("edited output length overflows usize")?;
    }
    Ok(len)
}

fn apply_edits_bounded(
    input: &str,
    edits: &[TextEdit],
    limits: Option<&Limits>,
) -> Result<String, EditError> {
    let mut prev_end = 0;
    for edit in edits {
        prev_end = validate_edit_span(input, edit.span, prev_end)
            .map_err(|msg| EditError::new(EditErrorKind::InvalidEdit, msg))?;
    }
    for pair in edits.windows(2) {
        validate_adjacent_spans(pair[0].span, pair[1].span)
            .map_err(|msg| EditError::new(EditErrorKind::InvalidEdit, msg))?;
    }

    let out_len = spliced_output_len(input.len(), edits)
        .map_err(|msg| EditError::new(EditErrorKind::InvalidEdit, msg))?;
    if let Some(limits) = limits
        && let Err(limit_err) = limits.check_input(out_len)
    {
        let source = ayaml::Error::from(limit_err);
        return Err(EditError::verification_with_source(
            format!("edited document failed to re-parse: {}", source.masked()),
            source,
        ));
    }

    let mut output = String::with_capacity(out_len);
    let mut cursor = 0;
    for edit in edits {
        output.push_str(&input[cursor..edit.span.start()]);
        output.push_str(&edit.replacement);
        cursor = edit.span.end();
    }
    output.push_str(&input[cursor..]);
    Ok(output)
}

/// Apply sorted, non-overlapping [`TextEdit`]s to `input`.
///
/// Two edits may share a start offset only if the earlier one is an insertion (empty span).
///
/// # Errors
///
/// Returns [`EditErrorKind::InvalidEdit`] if any edit is out of bounds, lands inside a UTF-8
/// code point, is out of order, or overlaps another edit.
pub fn apply_edits(input: &str, edits: &[TextEdit]) -> Result<String, EditError> {
    apply_edits_bounded(input, edits, None)
}

/// Replace the scalar at `path` with `replacement`, verifying both the resulting value tree
/// and event stream before returning.
///
/// # Errors
///
/// Returns [`EditError`] if the input fails to parse, `path` cannot be found, the document or
/// target uses an unsupported construct, or post-edit verification fails.
pub fn replace_scalar(
    input: &str,
    path: &[PathSegment],
    replacement: &Value,
) -> Result<VerifiedEdit, EditError> {
    replace_scalar_with(input, path, replacement, &EditOptions::new())
}

/// Replace the scalar at `path` with `replacement` using explicit [`EditOptions`].
///
/// # Errors
///
/// Returns [`EditError`] if the input fails to parse, `path` cannot be found, the document or
/// target uses an unsupported construct, or post-edit verification fails.
pub fn replace_scalar_with(
    input: &str,
    path: &[PathSegment],
    replacement: &Value,
    options: &EditOptions,
) -> Result<VerifiedEdit, EditError> {
    let op = EditOp::ReplaceScalar {
        path: path.to_vec(),
        value: replacement.clone(),
    };
    apply_batch_with(input, &[op], options)
}

/// Remove the block entry at `path`, verifying both the resulting value tree and event stream
/// before returning.
///
/// # Errors
///
/// Returns [`EditError`] if the input fails to parse, `path` cannot be found, the entry has no
/// exact removal span or uses an unsupported construct, or post-edit verification fails.
pub fn remove_entry(input: &str, path: &[PathSegment]) -> Result<VerifiedEdit, EditError> {
    remove_entry_with(input, path, &EditOptions::new())
}

/// Remove the block entry at `path` using explicit [`EditOptions`].
///
/// # Errors
///
/// Returns [`EditError`] if the input fails to parse, `path` cannot be found, the entry has no
/// exact removal span or uses an unsupported construct, or post-edit verification fails.
pub fn remove_entry_with(
    input: &str,
    path: &[PathSegment],
    options: &EditOptions,
) -> Result<VerifiedEdit, EditError> {
    let op = EditOp::RemoveEntry {
        path: path.to_vec(),
    };
    apply_batch_with(input, &[op], options)
}

/// Apply a batch of [`EditOp`]s atomically and verify the resulting document.
///
/// # Errors
///
/// Returns [`EditError`] if any operation is unsupported, if resulting edits overlap, or if
/// post-edit value or event-stream verification fails.
pub fn apply_batch(input: &str, ops: &[EditOp]) -> Result<VerifiedEdit, EditError> {
    apply_batch_with(input, ops, &EditOptions::new())
}

/// Apply a batch of [`EditOp`]s atomically using explicit [`EditOptions`].
///
/// # Errors
///
/// Returns [`EditError`] if any operation is unsupported, if resulting edits overlap, or if
/// post-edit value or event-stream verification fails.
pub fn apply_batch_with(
    input: &str,
    ops: &[EditOp],
    options: &EditOptions,
) -> Result<VerifiedEdit, EditError> {
    if ops.is_empty() {
        // Still validate that the input is a single supported document with no duplicate keys or
        // invalid core-schema scalars.
        let _unused = inspect_document(input, &options.parse)?;
        let _unused_val = parse_value_with(input, &options.parse).map_err(EditError::parse)?;
        return Ok(VerifiedEdit {
            output: input.to_owned(),
            edits: Vec::new(),
        });
    }

    let before_events = inspect_document(input, &options.parse)?;
    let tree = SpannedTree::parse_with(input, &options.parse).map_err(EditError::parse)?;
    if tree.documents().len() != 1 {
        return Err(EditError::new(
            EditErrorKind::Unsupported,
            "multi-document streams are not supported",
        ));
    }
    let original_value = parse_value_with(input, &options.parse).map_err(EditError::parse)?;

    let mut planned: Vec<(TextEdit, &EditOp)> = Vec::with_capacity(ops.len());
    for op in ops {
        let edit = match op {
            EditOp::ReplaceScalar { path, value } => {
                plan_replace_scalar(input, &tree, path, value, &options.parse.limits)?
            }
            EditOp::RemoveEntry { path } => plan_remove_entry(&tree, path)?,
        };
        planned.push((edit, op));
    }

    planned.sort_by(|(a, _), (b, _)| edit_order(a, b));
    let (edits, ordered_ops): (Vec<TextEdit>, Vec<&EditOp>) = planned.into_iter().unzip();
    let output = apply_edits_bounded(input, &edits, Some(&options.parse.limits))?;

    // Apply expected-value updates from highest source offset downward so removing an earlier
    // sequence item does not shift the indices of later planned operations.
    let mut expected_value = original_value;
    for op in ordered_ops.iter().rev() {
        match op {
            EditOp::ReplaceScalar { path, value } => {
                if !replace_value_at_mut(&mut expected_value, path, value) {
                    return Err(EditError::new(
                        EditErrorKind::NotFound,
                        "target path does not exist in value tree",
                    ));
                }
            }
            EditOp::RemoveEntry { path } => {
                if !remove_value_at_mut(&mut expected_value, path) {
                    return Err(EditError::new(
                        EditErrorKind::Unsupported,
                        "cannot remove target entry from value tree",
                    ));
                }
            }
        }
    }

    // Post-edit verification: re-parse value and events and compare.
    // Mask any parser error details so raw document text cannot leak through `VerificationFailed`.
    // Preserve `source` for limit errors (which carry no document text) so callers can inspect
    // `LimitExceeded` consistently across pre-allocation and re-parse limit failures.
    let reparsed_value = parse_value_with(&output, &options.parse)
        .map_err(|error| verification_reparse_error("edited document failed to re-parse", error))?;
    if !values_match_exact(&reparsed_value, &expected_value) {
        return Err(EditError::new(
            EditErrorKind::VerificationFailed,
            "edited document did not match the expected value tree",
        ));
    }

    let after_events = collect_canonical_events(&output, &options.parse).map_err(|error| {
        verification_reparse_error("edited document failed event verification", error)
    })?;

    let ok = if ops.len() == 1 {
        match &ops[0] {
            EditOp::ReplaceScalar { .. } => {
                one_scalar_changed(&before_events.texts, &after_events.texts)
            }
            EditOp::RemoveEntry { .. } => {
                one_run_removed(&before_events.texts, &after_events.texts)
            }
        }
    } else {
        verify_batch_events_with_spans(&before_events, &after_events, &edits, &ordered_ops)
    };
    if !ok {
        return Err(EditError::new(
            EditErrorKind::VerificationFailed,
            "edited document changed unexpected events outside the target span",
        ));
    }

    Ok(VerifiedEdit { output, edits })
}

fn verification_reparse_error(context: &str, error: ayaml::Error) -> EditError {
    let message = format!("{context}: {}", error.masked());
    if error.kind() == ayaml::ErrorKind::Limit {
        EditError::verification_with_source(message, error)
    } else {
        EditError::new(EditErrorKind::VerificationFailed, message)
    }
}

fn values_match_exact(reparsed: &Value, expected: &Value) -> bool {
    reparsed == expected && format!("{reparsed:?}") == format!("{expected:?}")
}

#[cfg_attr(test, derive(Debug))]
struct CanonicalEvents {
    texts: Vec<String>,
    spans: Vec<Span>,
    is_non_empty_scalar: Vec<bool>,
}

impl CanonicalEvents {
    fn new() -> Self {
        Self {
            texts: Vec::new(),
            spans: Vec::new(),
            is_non_empty_scalar: Vec::new(),
        }
    }

    fn push(&mut self, event: &Event<'_>) {
        let span = event.span();
        let is_non_empty_scalar = matches!(event, Event::Scalar { .. }) && !span.is_empty();
        self.texts.push(canonical_event(event));
        self.spans.push(span);
        self.is_non_empty_scalar.push(is_non_empty_scalar);
    }
}

/// Parse `input`'s events and refuse documents with multiple documents, anchors, aliases,
/// tags, block scalars, or opt-in merge-key expansion.
fn inspect_document(input: &str, options: &ParseOptions) -> Result<CanonicalEvents, EditError> {
    if options.merge_keys {
        return Err(EditError::new(
            EditErrorKind::Unsupported,
            "documents with merge-key expansion enabled are not supported",
        ));
    }
    let mut doc_count = 0usize;
    let mut canonical = CanonicalEvents::new();
    let stream = parse_events_with(input, options).map_err(EditError::parse)?;
    for item in stream {
        let event = item.map_err(EditError::parse)?;
        match &event {
            Event::DocumentStart { .. } => {
                doc_count += 1;
                if doc_count > 1 {
                    return Err(EditError::new(
                        EditErrorKind::Unsupported,
                        "multi-document streams are not supported",
                    ));
                }
            }
            Event::Alias { .. } => {
                return Err(EditError::new(
                    EditErrorKind::Unsupported,
                    "documents with aliases are not supported",
                ));
            }
            Event::Scalar {
                style, tag, anchor, ..
            } => {
                if anchor.is_some() {
                    return Err(EditError::new(
                        EditErrorKind::Unsupported,
                        "documents with anchors are not supported",
                    ));
                }
                if tag.is_some() {
                    return Err(EditError::new(
                        EditErrorKind::Unsupported,
                        "documents with tags are not supported",
                    ));
                }
                if matches!(style, ScalarStyle::Literal | ScalarStyle::Folded) {
                    return Err(EditError::new(
                        EditErrorKind::Unsupported,
                        "documents with block scalars are not supported",
                    ));
                }
            }
            Event::SequenceStart { tag, anchor, .. } | Event::MappingStart { tag, anchor, .. } => {
                if anchor.is_some() {
                    return Err(EditError::new(
                        EditErrorKind::Unsupported,
                        "documents with anchors are not supported",
                    ));
                }
                if tag.is_some() {
                    return Err(EditError::new(
                        EditErrorKind::Unsupported,
                        "documents with tags are not supported",
                    ));
                }
            }
            _ => {}
        }
        canonical.push(&event);
    }
    if doc_count != 1 {
        return Err(EditError::new(
            EditErrorKind::Unsupported,
            "expected exactly one YAML document",
        ));
    }
    Ok(canonical)
}

fn collect_canonical_events(
    input: &str,
    options: &ParseOptions,
) -> Result<CanonicalEvents, ayaml::Error> {
    let stream = parse_events_with(input, options)?;
    let mut out = CanonicalEvents::new();
    for item in stream {
        let event = item?;
        out.push(&event);
    }
    Ok(out)
}

fn canonical_event(event: &Event<'_>) -> String {
    match event {
        Event::Scalar {
            value,
            style,
            tag,
            anchor,
            ..
        } => format!("scalar {value:?} {style:?} {tag:?} {anchor:?}"),
        Event::Alias { anchor, .. } => format!("alias {anchor:?}"),
        Event::SequenceStart {
            tag, anchor, style, ..
        } => format!("sequence {style:?} {tag:?} {anchor:?}"),
        Event::MappingStart {
            tag, anchor, style, ..
        } => format!("mapping {style:?} {tag:?} {anchor:?}"),
        Event::DocumentStart { explicit, .. } => format!("document {explicit}"),
        Event::DocumentEnd { explicit, .. } => format!("document end {explicit}"),
        Event::Directive { name, value, .. } => format!("directive {name} {value}"),
        other => format!("{:?}", std::mem::discriminant(other)),
    }
}

fn plan_replace_scalar(
    input: &str,
    tree: &SpannedTree<'_>,
    path: &[PathSegment],
    replacement: &Value,
    limits: &Limits,
) -> Result<TextEdit, EditError> {
    if !matches!(
        replacement,
        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_)
    ) {
        return Err(EditError::new(
            EditErrorKind::Unsupported,
            "replace_scalar only accepts scalar values",
        ));
    }
    let node = tree
        .lookup(path)
        .ok_or_else(|| EditError::new(EditErrorKind::NotFound, "target path not found"))?;
    if !node.is_scalar() {
        return Err(EditError::new(
            EditErrorKind::Unsupported,
            "target node is not a scalar",
        ));
    }
    let span = node.span();
    if span.is_empty() {
        return Err(EditError::new(
            EditErrorKind::Unsupported,
            "replacing an unwritten empty scalar is not supported",
        ));
    }
    let raw = node.scalar_text().ok_or_else(|| {
        EditError::new(EditErrorKind::Unsupported, "target scalar has no raw text")
    })?;
    if raw.contains(['\n', '\r']) {
        return Err(EditError::new(
            EditErrorKind::Unsupported,
            "replacing a multiline scalar is not supported",
        ));
    }
    // Refuse ambiguous comment placement immediately after the scalar without whitespace.
    if let Some(rest) = input.get(span.end()..)
        && rest.starts_with('#')
    {
        return Err(EditError::new(
            EditErrorKind::Unsupported,
            "ambiguous comment immediately follows target scalar",
        ));
    }

    // Reject oversized replacement strings before cloning or emitting them: even in the densest
    // YAML escape form (`\u{2028}` -> `\L`, 3 bytes -> 2 bytes), the formatted scalar is at least
    // `text.len() / 2` bytes long.
    if let Value::String(text) = replacement
        && let Err(limit_err) = limits.check_input(text.len() / 2)
    {
        let source = ayaml::Error::from(limit_err);
        return Err(EditError::verification_with_source(
            format!("edited document failed to re-parse: {}", source.masked()),
            source,
        ));
    }

    let formatted = format_inline_scalar(replacement, limits)?;
    Ok(TextEdit::new(span, formatted))
}

fn format_inline_scalar(value: &Value, limits: &Limits) -> Result<String, EditError> {
    // Emit inside a 1-element flow sequence so `ayaml`'s emitter uses flow-context quoting
    // (quoting strings with `,`, `[`, `]`, `{`, `}` as well as block-unsafe indicators).
    // Bound emitter output by `max_input_bytes + 3` (`[` + scalar + `]\n`) so heavily escaped
    // replacement strings fail before allocating an oversized buffer.
    let input_cap = limits.max_input_bytes.saturating_add(3);
    let capped_by_input = input_cap < limits.max_output_bytes;
    let mut emit_limits = limits.clone();
    if capped_by_input {
        emit_limits.max_output_bytes = input_cap;
    }
    let emit_options = EmitOptions::new().with_flow(true).with_limits(emit_limits);
    let wrapped = Value::Sequence(vec![value.clone()]);
    let emitted = to_string_value_with(&wrapped, &emit_options).map_err(|error| {
        if capped_by_input && error.code() == ayaml::ErrorCode::OutputSizeLimit {
            let observed = error
                .limit()
                .map_or_else(
                    || limits.max_input_bytes.saturating_add(1),
                    |info| {
                        usize::try_from(info.observed())
                            .unwrap_or(usize::MAX)
                            .saturating_sub(3)
                    },
                )
                .max(limits.max_input_bytes.saturating_add(1));
            let source = match limits.check_input(observed) {
                Err(limit_err) => ayaml::Error::from(limit_err),
                Ok(()) => error,
            };
            EditError::verification_with_source(
                format!("edited document failed to re-parse: {}", source.masked()),
                source,
            )
        } else {
            EditError::new(
                EditErrorKind::Unsupported,
                format!("could not format replacement scalar: {}", error.masked()),
            )
        }
    })?;
    unwrap_inline_flow_scalar(&emitted)
}

fn unwrap_inline_flow_scalar(emitted: &str) -> Result<String, EditError> {
    let trimmed = emitted.trim_end_matches(['\n', '\r']);
    let inner = trimmed
        .strip_prefix('[')
        .and_then(|rest| rest.strip_suffix(']'))
        .ok_or_else(|| {
            EditError::new(
                EditErrorKind::Unsupported,
                "replacement scalar cannot be formatted on a single line",
            )
        })?;
    if inner.is_empty() || inner.contains(['\n', '\r']) {
        return Err(EditError::new(
            EditErrorKind::Unsupported,
            "replacement scalar cannot be formatted on a single line",
        ));
    }
    Ok(inner.to_owned())
}

fn plan_remove_entry(tree: &SpannedTree<'_>, path: &[PathSegment]) -> Result<TextEdit, EditError> {
    if path.is_empty() {
        return Err(EditError::new(
            EditErrorKind::Unsupported,
            "cannot remove the document root",
        ));
    }
    let node = tree
        .lookup(path)
        .ok_or_else(|| EditError::new(EditErrorKind::NotFound, "target path not found"))?;
    let span = node.entry_span().ok_or_else(|| {
        EditError::new(
            EditErrorKind::Unsupported,
            "target entry has no exact removal span",
        )
    })?;
    Ok(TextEdit::new(span, String::new()))
}

fn replace_value_at_mut(
    mut current: &mut Value,
    path: &[PathSegment],
    replacement: &Value,
) -> bool {
    for segment in path {
        current = match (current, segment) {
            (Value::Mapping(mapping), PathSegment::Key(key)) => match mapping.get_mut(key) {
                Some(inner) => inner,
                None => return false,
            },
            (Value::Sequence(items), PathSegment::Index(idx)) => match items.get_mut(*idx) {
                Some(inner) => inner,
                None => return false,
            },
            _ => return false,
        };
    }
    *current = replacement.clone();
    true
}

fn remove_value_at_mut(mut current: &mut Value, path: &[PathSegment]) -> bool {
    let Some((last, parents)) = path.split_last() else {
        return false;
    };
    for segment in parents {
        current = match (current, segment) {
            (Value::Mapping(mapping), PathSegment::Key(key)) => match mapping.get_mut(key) {
                Some(inner) => inner,
                None => return false,
            },
            (Value::Sequence(items), PathSegment::Index(idx)) => match items.get_mut(*idx) {
                Some(inner) => inner,
                None => return false,
            },
            _ => return false,
        };
    }
    match (current, last) {
        (Value::Mapping(mapping), PathSegment::Key(key)) => {
            mapping.shift_remove(key).is_some() && !mapping.is_empty()
        }
        (Value::Sequence(items), PathSegment::Index(idx)) => {
            if *idx >= items.len() || items.len() == 1 {
                return false;
            }
            items.remove(*idx);
            true
        }
        _ => false,
    }
}

fn count_ops(ops: &[&EditOp]) -> (usize, usize) {
    let mut replaces = 0usize;
    let mut removals = 0usize;
    for op in ops {
        match op {
            EditOp::ReplaceScalar { .. } => replaces += 1,
            EditOp::RemoveEntry { .. } => removals += 1,
        }
    }
    (replaces, removals)
}

/// Partition multi-op event verification along every untouched non-empty scalar whose shifted byte
/// span and canonical event text match verbatim in `after`. Each bounded gap between anchors is
/// checked against only the exact ops whose spans fall inside that gap.
fn verify_batch_events_with_spans(
    before: &CanonicalEvents,
    after: &CanonicalEvents,
    edits: &[TextEdit],
    ordered_ops: &[&EditOp],
) -> bool {
    debug_assert_eq!(edits.len(), ordered_ops.len());
    debug_assert_eq!(before.texts.len(), before.spans.len());
    debug_assert_eq!(before.texts.len(), before.is_non_empty_scalar.len());
    debug_assert_eq!(after.texts.len(), after.spans.len());
    debug_assert_eq!(after.texts.len(), after.is_non_empty_scalar.len());

    let mut edit_idx = 0usize;
    let mut removed_bytes = 0usize;
    let mut added_bytes = 0usize;

    let mut gap_b_start = 0usize;
    let mut gap_a_start = 0usize;
    let mut gap_edit_start = 0usize;
    let mut after_cursor = 0usize;
    let mut min_next_start = 0usize;

    for b_idx in 0..before.texts.len() {
        if !before.is_non_empty_scalar[b_idx] {
            continue;
        }
        let span = before.spans[b_idx];
        if span.start() < min_next_start {
            continue;
        }

        while edit_idx < edits.len() && edits[edit_idx].span.end() <= span.start() {
            let edit = &edits[edit_idx];
            removed_bytes += edit.span.end() - edit.span.start();
            added_bytes += edit.replacement.len();
            edit_idx += 1;
        }
        min_next_start = span.start();

        // Only anchor on scalars strictly outside all edit spans.
        if edit_idx < edits.len() && span.end() > edits[edit_idx].span.start() {
            continue;
        }

        let Some(shifted_start) = span
            .start()
            .checked_sub(removed_bytes)
            .and_then(|base| base.checked_add(added_bytes))
        else {
            return false;
        };
        let Some(shifted_end) = span
            .end()
            .checked_sub(removed_bytes)
            .and_then(|base| base.checked_add(added_bytes))
        else {
            return false;
        };
        let shifted_span = Span::new(shifted_start, shifted_end);

        // Advance `after_cursor` monotonically to locate this exact shifted anchor.
        let mut matched_a = None;
        while after_cursor < after.texts.len() {
            if !after.is_non_empty_scalar[after_cursor] {
                after_cursor += 1;
                continue;
            }
            let a_span = after.spans[after_cursor];
            if a_span.start() < shifted_start {
                after_cursor += 1;
                continue;
            }
            if a_span == shifted_span && after.texts[after_cursor] == before.texts[b_idx] {
                matched_a = Some(after_cursor);
            }
            break;
        }

        if let Some(a_idx) = matched_a {
            let (gap_replaces, gap_removals) = count_ops(&ordered_ops[gap_edit_start..edit_idx]);
            if !batch_events_match(
                &before.texts[gap_b_start..b_idx],
                &after.texts[gap_a_start..a_idx],
                gap_replaces,
                gap_removals,
            ) {
                return false;
            }
            gap_b_start = b_idx + 1;
            gap_a_start = a_idx + 1;
            gap_edit_start = edit_idx;
            min_next_start = span.end();
        }
    }

    let (tail_replaces, tail_removals) = count_ops(&ordered_ops[gap_edit_start..]);
    batch_events_match(
        &before.texts[gap_b_start..],
        &after.texts[gap_a_start..],
        tail_replaces,
        tail_removals,
    )
}

fn one_scalar_changed(before: &[String], after: &[String]) -> bool {
    if before.len() != after.len() {
        return false;
    }
    let mut diffs = 0usize;
    for (b, a) in before.iter().zip(after) {
        if b != a {
            if !b.starts_with("scalar ") || !a.starts_with("scalar ") {
                return false;
            }
            diffs += 1;
        }
    }
    diffs <= 1
}

fn one_run_removed(before: &[String], after: &[String]) -> bool {
    let same = |pair: &(&String, &String)| pair.0 == pair.1;
    let prefix = before.iter().zip(after).take_while(same).count();
    let suffix = before[prefix..]
        .iter()
        .rev()
        .zip(after[prefix..].iter().rev())
        .take_while(same)
        .count();
    after.len() < before.len() && prefix + suffix == after.len()
}

/// Verify that `after` can be obtained from `before` by at most `max_replaces` scalar-to-scalar
/// substitutions and at most `max_removals` contiguous deleted event runs (and zero insertions or
/// structural changes elsewhere).
fn batch_events_match(
    before: &[String],
    after: &[String],
    max_replaces: usize,
    max_removals: usize,
) -> bool {
    if after.len() > before.len() {
        return false;
    }
    if max_removals == 0 {
        if before.len() != after.len() {
            return false;
        }
        if max_replaces == 0 {
            return before == after;
        }
        let mut diffs = 0usize;
        for (b, a) in before.iter().zip(after) {
            if b != a {
                if !b.starts_with("scalar ") || !a.starts_with("scalar ") {
                    return false;
                }
                diffs += 1;
                if diffs > max_replaces {
                    return false;
                }
            }
        }
        return true;
    }
    // Strip common prefix and suffix to shrink the DP window.
    let same = |pair: &(&String, &String)| pair.0 == pair.1;
    let prefix = before.iter().zip(after).take_while(same).count();
    let suffix = before[prefix..]
        .iter()
        .rev()
        .zip(after[prefix..].iter().rev())
        .take_while(same)
        .count();
    let b = &before[prefix..before.len() - suffix];
    let a = &after[prefix..after.len() - suffix];
    let max_skip = b.len() - a.len();
    match select_batch_matcher(a.len(), max_skip, max_replaces, max_removals) {
        BatchMatcher::Greedy => batch_events_match_greedy(b, a, max_replaces, max_removals),
        BatchMatcher::DpByRemovals => {
            batch_events_match_dp_by_removals(b, a, max_skip, max_replaces, max_removals)
        }
        BatchMatcher::DpByReplaces => {
            batch_events_match_dp_by_replaces(b, a, max_skip, max_replaces, max_removals)
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BatchMatcher {
    Greedy,
    DpByRemovals,
    DpByReplaces,
}

/// Choose the exact DP orientation (minimizing table stride on the smaller budget) or fall back to
/// bounded greedy alignment when the exact DP table would exceed 1M cells.
fn select_batch_matcher(
    a_len: usize,
    max_skip: usize,
    max_replaces: usize,
    max_removals: usize,
) -> BatchMatcher {
    let cols = max_skip.saturating_add(1);
    let stride = max_removals.min(max_replaces).saturating_add(1);
    if a_len
        .saturating_add(1)
        .saturating_mul(cols)
        .saturating_mul(stride)
        > 1_000_000
    {
        BatchMatcher::Greedy
    } else if max_removals <= max_replaces {
        BatchMatcher::DpByRemovals
    } else {
        BatchMatcher::DpByReplaces
    }
}

/// Exact DP indexed by `(skip, removals_used)` minimizing `replaces_used`.
fn batch_events_match_dp_by_removals(
    b: &[String],
    a: &[String],
    max_skip: usize,
    max_replaces: usize,
    max_removals: usize,
) -> bool {
    const INF: usize = usize::MAX;
    let cols = max_skip + 1;
    let stride = max_removals + 1;
    let mut curr = vec![[INF; 2]; cols * stride];
    let mut next = vec![[INF; 2]; cols * stride];
    curr[0][0] = 0;

    for j in 0..=a.len() {
        next.fill([INF; 2]);
        for skip in 0..=max_skip {
            let i = j + skip;
            let row_base = skip * stride;
            let next_skip_base = (skip + 1) * stride;
            for r in 0..=max_removals {
                let [not_in, in_run] = curr[row_base + r];
                if not_in == INF && in_run == INF {
                    continue;
                }
                // Option 1: delete `b[i]` (advance `skip` by 1, enter/stay in removed run).
                if skip < max_skip {
                    if not_in != INF && r < max_removals {
                        let slot = &mut curr[next_skip_base + r + 1][1];
                        *slot = (*slot).min(not_in);
                    }
                    if in_run != INF {
                        let slot = &mut curr[next_skip_base + r][1];
                        *slot = (*slot).min(in_run);
                    }
                }
                // Option 2: match or replace `b[i]` with `a[j]` (advance `j` by 1, exit run).
                if j < a.len() {
                    let best = not_in.min(in_run);
                    if b[i] == a[j] {
                        let slot = &mut next[row_base + r][0];
                        *slot = (*slot).min(best);
                    } else if b[i].starts_with("scalar ")
                        && a[j].starts_with("scalar ")
                        && best < max_replaces
                    {
                        let slot = &mut next[row_base + r][0];
                        *slot = (*slot).min(best + 1);
                    }
                }
            }
        }
        if j < a.len() {
            std::mem::swap(&mut curr, &mut next);
        }
    }

    let final_base = max_skip * stride;
    (0..=max_removals).any(|r| {
        let [not_in, in_run] = curr[final_base + r];
        not_in.min(in_run) != INF
    })
}

/// Exact DP indexed by `(skip, replaces_used)` minimizing `removals_used`.
fn batch_events_match_dp_by_replaces(
    b: &[String],
    a: &[String],
    max_skip: usize,
    max_replaces: usize,
    max_removals: usize,
) -> bool {
    const INF: usize = usize::MAX;
    let cols = max_skip + 1;
    let stride = max_replaces + 1;
    let mut curr = vec![[INF; 2]; cols * stride];
    let mut next = vec![[INF; 2]; cols * stride];
    curr[0][0] = 0;

    for j in 0..=a.len() {
        next.fill([INF; 2]);
        for skip in 0..=max_skip {
            let i = j + skip;
            let row_base = skip * stride;
            let next_skip_base = (skip + 1) * stride;
            for p in 0..=max_replaces {
                let [not_in, in_run] = curr[row_base + p];
                if not_in == INF && in_run == INF {
                    continue;
                }
                // Option 1: delete `b[i]` (advance `skip` by 1, enter/stay in removed run).
                if skip < max_skip {
                    if not_in < max_removals {
                        let slot = &mut curr[next_skip_base + p][1];
                        *slot = (*slot).min(not_in + 1);
                    }
                    if in_run != INF {
                        let slot = &mut curr[next_skip_base + p][1];
                        *slot = (*slot).min(in_run);
                    }
                }
                // Option 2: match or replace `b[i]` with `a[j]` (advance `j` by 1, exit run).
                if j < a.len() {
                    let best = not_in.min(in_run);
                    if b[i] == a[j] {
                        let slot = &mut next[row_base + p][0];
                        *slot = (*slot).min(best);
                    } else if b[i].starts_with("scalar ")
                        && a[j].starts_with("scalar ")
                        && p < max_replaces
                    {
                        let slot = &mut next[row_base + p + 1][0];
                        *slot = (*slot).min(best);
                    }
                }
            }
        }
        if j < a.len() {
            std::mem::swap(&mut curr, &mut next);
        }
    }

    let final_base = max_skip * stride;
    (0..=max_replaces).any(|p| {
        let [not_in, in_run] = curr[final_base + p];
        not_in.min(in_run) != INF
    })
}

/// Lookahead predicate: two matching events immediately after `(i, j)` (or a single matching tail
/// with zero remaining skips) identify an isolated scalar replacement.
fn is_isolated_scalar_replace(
    before: &[String],
    after: &[String],
    i: usize,
    j: usize,
    rem_skip: usize,
) -> bool {
    before.get(i + 1) == after.get(j + 1)
        && ((j + 2 >= after.len() && rem_skip == 0)
            || (j + 2 < after.len() && before.get(i + 2) == after.get(j + 2)))
}

/// Lookahead predicate for greedy skip-window resynchronization at `before[bi] == after[j]`:
/// either the immediate successor also matches (or ends `after`), or a matched mapping key is
/// followed by a scalar replacement whose own successor matches (or ends `after`).
fn sync_matches_at(
    before: &[String],
    after: &[String],
    bi: usize,
    j: usize,
    has_replace_budget: bool,
) -> bool {
    let next_matches = j + 1 == after.len() || before.get(bi + 1) == after.get(j + 1);
    let key_then_replace = has_replace_budget
        && before.get(bi + 1).is_some_and(|s| s.starts_with("scalar "))
        && after.get(j + 1).is_some_and(|s| s.starts_with("scalar "))
        && (j + 2 >= after.len() || before.get(bi + 2) == after.get(j + 2));
    next_matches || key_then_replace
}

/// Linear-time lookahead greedy alignment used when an extreme unanchored multi-op gap exceeds the
/// 1M-cell exact DP cap. Distinguishes scalar replacements from deleted runs using immediate
/// post-event sync and bounded skip-window resynchronization.
fn batch_events_match_greedy(
    before: &[String],
    after: &[String],
    max_replaces: usize,
    max_removals: usize,
) -> bool {
    let probe_budget = before.len().saturating_mul(4).max(1024);
    batch_events_match_greedy_with_probes(before, after, max_replaces, max_removals, probe_budget)
}

fn batch_events_match_greedy_with_probes(
    before: &[String],
    after: &[String],
    max_replaces: usize,
    max_removals: usize,
    mut remaining_probes: usize,
) -> bool {
    let mut i = 0usize;
    let mut j = 0usize;
    let mut replaces = 0usize;
    let mut removals = 0usize;
    let mut in_run = false;
    let mut no_sync_j: Option<usize> = None;
    while i < before.len() && j < after.len() {
        if before[i] == after[j] {
            in_run = false;
            i += 1;
            j += 1;
            continue;
        }
        let rem_skip = (before.len() - i).saturating_sub(after.len() - j);
        let both_scalar = before[i].starts_with("scalar ") && after[j].starts_with("scalar ");
        let can_replace = both_scalar && replaces < max_replaces;

        if !in_run && can_replace && is_isolated_scalar_replace(before, after, i, j, rem_skip) {
            replaces += 1;
            i += 1;
            j += 1;
            continue;
        }

        if rem_skip > 0 && (in_run || removals < max_removals) {
            if no_sync_j != Some(j) {
                let limit = rem_skip.min(remaining_probes);
                let mut found = None;
                for d in 1..=limit {
                    remaining_probes -= 1;
                    if before[i + d] != after[j] {
                        continue;
                    }
                    if sync_matches_at(before, after, i + d, j, replaces < max_replaces) {
                        found = Some(d);
                        break;
                    }
                }
                if let Some(d) = found {
                    if !in_run {
                        removals += 1;
                    }
                    in_run = false;
                    i += d;
                    continue;
                }
                if limit == rem_skip {
                    no_sync_j = Some(j);
                }
            }
            if !in_run && can_replace {
                replaces += 1;
                i += 1;
                j += 1;
                continue;
            }
            if !in_run {
                removals += 1;
                in_run = true;
            }
            i += 1;
        } else if can_replace {
            in_run = false;
            replaces += 1;
            i += 1;
            j += 1;
        } else {
            return false;
        }
    }
    if j != after.len() {
        return false;
    }
    if i < before.len() && !in_run && removals == max_removals {
        return false;
    }
    true
}

#[cfg(test)]
mod tests;

#[cfg(kani)]
mod kani_proofs {
    use std::cmp::Ordering;

    use ayaml::Span;

    use super::{
        span_order, spliced_output_len_pairs, step_spliced_len, validate_adjacent_spans,
        validate_edit_span,
    };

    fn validate_edit_spans(input: &str, spans: &[Span]) -> Result<(), &'static str> {
        let mut prev_end = 0;
        for &span in spans {
            prev_end = validate_edit_span(input, span, prev_end)?;
        }
        for pair in spans.windows(2) {
            validate_adjacent_spans(pair[0], pair[1])?;
        }
        Ok(())
    }

    #[kani::proof]
    fn verify_span_order_is_strict_total_order() {
        let a = Span::new(kani::any(), kani::any());
        let b = Span::new(kani::any(), kani::any());
        let c = Span::new(kani::any(), kani::any());

        // Reflexive.
        assert_eq!(span_order(a, a), Ordering::Equal);
        // Antisymmetric.
        assert_eq!(span_order(a, b), span_order(b, a).reverse());
        // Transitive.
        let ab = span_order(a, b);
        let bc = span_order(b, c);
        let ac = span_order(a, c);
        if ab != Ordering::Greater && bc != Ordering::Greater {
            assert_ne!(ac, Ordering::Greater);
            if ab == Ordering::Less || bc == Ordering::Less {
                assert_eq!(ac, Ordering::Less);
            }
        }
        // Zero-width insertions always sort before non-empty replacements at the same start offset.
        if a.start() == b.start() && a.is_empty() && !b.is_empty() {
            assert_eq!(span_order(a, b), Ordering::Less);
            assert_eq!(span_order(b, a), Ordering::Greater);
        }
    }

    #[kani::proof]
    fn verify_step_spliced_len_never_overflows() {
        let len: usize = kani::any();
        let start: usize = kani::any();
        let end: usize = kani::any();
        let replacement_len: usize = kani::any();
        let span = Span::new(start, end);
        let result = step_spliced_len(len, span, replacement_len);
        if start <= end {
            let span_len = end - start;
            if span_len <= len {
                assert_eq!(result, (len - span_len).checked_add(replacement_len));
            } else {
                assert_eq!(result, None);
            }
        } else {
            assert_eq!(result, len.checked_add(replacement_len));
        }
    }

    #[kani::proof]
    #[kani::unwind(5)]
    fn verify_apply_edits_span_validation_guarantees_safe_slicing() {
        // Multi-byte UTF-8 input exercising 1-, 2-, 3-, and 4-byte UTF-8 sequences (11 bytes).
        let input = "aé€🚀\n";
        let mut spans = [Span::new(0, 0); 3];
        let mut repl_lens = [0usize; 3];
        for i in 0..3 {
            let start: u8 = kani::any();
            let end: u8 = kani::any();
            let repl_len: u8 = kani::any();
            kani::assume(start <= 13 && end <= 13 && repl_len <= 64);
            spans[i] = Span::new(usize::from(start), usize::from(end));
            repl_lens[i] = usize::from(repl_len);
        }

        if validate_edit_spans(input, &spans).is_ok() {
            // Validated spans are strictly ordered, non-overlapping, on char boundaries, and
            // guarantee that `apply_edits`'s slicing cursor cannot panic and `spliced_output_len`
            // computes the exact output byte length without heap allocation.
            let mut cursor = 0;
            let mut expected_len = 0usize;
            for i in 0..3 {
                let span = spans[i];
                assert!(cursor <= span.start());
                assert!(span.start() <= span.end());
                assert!(span.end() <= input.len());
                assert!(input.is_char_boundary(cursor));
                assert!(input.is_char_boundary(span.start()));
                assert!(input.is_char_boundary(span.end()));
                // Use `str::get` so CBMC proves `&input[cursor..span.start()]` cannot panic
                // without symbolically unwinding `core::str::slice_error_fail_rt`.
                let Some(unchanged) = input.get(cursor..span.start()) else {
                    panic!("validated edit span must slice input on UTF-8 boundaries");
                };
                expected_len += unchanged.len();
                expected_len += repl_lens[i];
                cursor = span.end();
            }
            let Some(tail) = input.get(cursor..) else {
                panic!("validated edit cursor must slice input tail on UTF-8 boundaries");
            };
            expected_len += tail.len();
            let pairs = [
                (spans[0], repl_lens[0]),
                (spans[1], repl_lens[1]),
                (spans[2], repl_lens[2]),
            ];
            assert_eq!(
                spliced_output_len_pairs(input.len(), &pairs),
                Ok(expected_len)
            );
            for pair in spans.windows(2) {
                assert_ne!(span_order(pair[0], pair[1]), Ordering::Greater);
                assert!(pair[0].end() <= pair[1].start());
                if pair[0].start() == pair[1].start() {
                    assert!(pair[0].is_empty() || pair[1].is_empty());
                }
            }
        }
    }
}