omni-dev 0.46.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, Datadog, Gmail, and Drive.
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
//! Content anchors resolved against the same inline snapshot as the write lease.
//!
//! This is the production UTF-16 arithmetic boundary. Offsets are computed
//! within server-indexed text runs, never by summing document text. Non-text
//! elements break matches; ranges cannot cross containers or structural gaps.

use std::collections::HashSet;

use regex::RegexBuilder;
use serde::Serialize;

use super::types::{Document, StructuralElement};

/// Why an anchor or range cannot safely address an edit. Never contains prose.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "reason", rename_all = "kebab-case")]
pub enum AnchorError {
    /// The anchor is empty or contains a paragraph separator.
    InvalidAnchor,
    /// No characters would remain after the API strips unsupported input.
    InvalidInsertionText,
    /// The segment selector is empty or inconsistent.
    InvalidSelection,
    /// No selected segment exists.
    SegmentNotFound,
    /// A segment ID identifies more than one segment.
    AmbiguousSegment,
    /// No selected text matches.
    NotFound,
    /// More than one occurrence, including overlapping occurrences.
    Ambiguous {
        /// Number of matches across all tab bodies.
        count: usize,
    },
    /// Missing or inconsistent server indices or tab identity.
    InvalidIndices,
    /// The edit overlaps pending content suggestions.
    SuggestedContent,
    /// The range crosses a structural boundary or includes a protected newline.
    UnsafeRange,
    /// The second anchor precedes the first or is in another tab/container.
    UnorderedRange,
}

/// An explicit existing segment, optionally narrowed to one tab.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SegmentSelection {
    /// Header, footer or footnote map key; absent selects all tab bodies.
    pub segment_id: Option<String>,
    /// Optional tab identity; requires a segment ID.
    pub tab_id: Option<String>,
}

impl SegmentSelection {
    /// Reject empty identifiers and a tab without a segment before I/O.
    pub fn validate(&self) -> Result<(), AnchorError> {
        if self.segment_id.as_ref().is_some_and(String::is_empty)
            || self.tab_id.as_ref().is_some_and(String::is_empty)
        {
            return Err(AnchorError::InvalidSelection);
        }
        if self.tab_id.is_some() && self.segment_id.is_none() {
            return Err(AnchorError::InvalidSelection);
        }
        Ok(())
    }
}

/// Kind of an explicitly selected non-body segment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SegmentKind {
    /// Page header.
    Header,
    /// Page footer.
    Footer,
    /// Footnote content.
    Footnote,
}

/// Whether inserted text goes before or after the unique anchor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Side {
    /// Before the first code unit of the anchor.
    Before,
    /// After the last code unit of the anchor.
    After,
}

/// Metadata shared by a dry-run and a successful edit. No document prose.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct EditPreview {
    /// Inclusive start in server UTF-16 code units.
    pub start_index: i64,
    /// Exclusive end; equals start for insertion.
    pub end_index: i64,
    /// The addressed tab; absent only for legacy top-level body responses.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tab_id: Option<String>,
    /// Explicit non-body segment identity.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub segment_id: Option<String>,
    /// Selected segment family.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub segment_kind: Option<SegmentKind>,
    /// Number of paragraphs touched.
    pub paragraphs: usize,
    /// Unicode scalar values inserted or removed.
    pub chars: usize,
    /// UTF-8 bytes inserted or removed.
    pub bytes: usize,
}

struct Run<'a> {
    text: &'a str,
    start: i64,
    end: i64,
    suggested: bool,
}

struct Paragraph<'a> {
    tab: usize,
    tab_id: Option<String>,
    container: usize,
    start: i64,
    end: i64,
    // The last newline of a container, or one preceding a structural element.
    protected_newline: bool,
    runs: Vec<Run<'a>>,
}

#[derive(Clone, Copy)]
struct Match {
    paragraph: usize,
    start: i64,
    end: i64,
    suggested: bool,
}

fn utf16_len(text: &str) -> Result<i64, AnchorError> {
    i64::try_from(text.encode_utf16().count()).map_err(|_| AnchorError::InvalidIndices)
}

fn paragraphs<'a>(
    document: &'a Document,
    selection: &SegmentSelection,
) -> Result<(Vec<Paragraph<'a>>, Option<SegmentKind>), AnchorError> {
    selection.validate()?;
    let mut out = Vec::new();
    let mut selected = Vec::new();
    let mut container = 0;
    let mut tab_ids = HashSet::new();
    for (tab, resolved) in document.resolved_tabs().iter().enumerate() {
        if !document.tabs.is_empty() {
            let id = resolved
                .tab_id
                .filter(|id| !id.is_empty())
                .ok_or(AnchorError::InvalidIndices)?;
            if !tab_ids.insert(id) {
                return Err(AnchorError::InvalidIndices);
            }
        }
        if let Some(id) = &selection.segment_id {
            if selection
                .tab_id
                .as_deref()
                .is_some_and(|tab| Some(tab) != resolved.tab_id)
            {
                continue;
            }
            for (kind, segments) in [
                (SegmentKind::Header, resolved.headers()),
                (SegmentKind::Footer, resolved.footers()),
                (SegmentKind::Footnote, resolved.footnotes()),
            ] {
                for segment in segments {
                    if segment.segment_id == id {
                        selected.push((tab, resolved.tab_id, kind, segment));
                    }
                }
            }
        } else if let Some(body) = resolved.body {
            collect(
                &body.content,
                tab,
                resolved.tab_id,
                false,
                &mut container,
                &mut out,
            )?;
        }
    }
    let mut segment_kind = None;
    if selection.segment_id.is_some() {
        let (tab, tab_id, kind, segment) = match selected.as_slice() {
            [] => return Err(AnchorError::SegmentNotFound),
            [one] => *one,
            _ => return Err(AnchorError::AmbiguousSegment),
        };
        segment_kind = Some(kind);
        collect(segment.content, tab, tab_id, true, &mut container, &mut out)?;
    }
    Ok((out, segment_kind))
}

fn collect<'a>(
    elements: &'a [StructuralElement],
    tab: usize,
    tab_id: Option<&str>,
    segment: bool,
    next_container: &mut usize,
    out: &mut Vec<Paragraph<'a>>,
) -> Result<(), AnchorError> {
    let container = *next_container;
    *next_container += 1;
    for (position, element) in elements.iter().enumerate() {
        if let Some(paragraph) = &element.paragraph {
            let start = if segment {
                element.start_index()
            } else {
                element.start_index.ok_or(AnchorError::InvalidIndices)?
            };
            let end = element.end_index.ok_or(AnchorError::InvalidIndices)?;
            if start < i64::from(!segment) || end <= start {
                return Err(AnchorError::InvalidIndices);
            }
            let mut runs = Vec::new();
            let mut previous_end = start;
            for inline in &paragraph.elements {
                let run_start = if segment {
                    inline.start_index.unwrap_or(0)
                } else {
                    inline.start_index.ok_or(AnchorError::InvalidIndices)?
                };
                let run_end = inline.end_index.ok_or(AnchorError::InvalidIndices)?;
                if run_start < previous_end || run_end <= run_start || run_end > end {
                    return Err(AnchorError::InvalidIndices);
                }
                previous_end = run_end;
                if let Some(text) = &inline.text_run {
                    if run_start.checked_add(utf16_len(&text.content)?) != Some(run_end) {
                        return Err(AnchorError::InvalidIndices);
                    }
                    runs.push(Run {
                        text: &text.content,
                        start: run_start,
                        end: run_end,
                        suggested: !text.suggested_insertion_ids.is_empty()
                            || !text.suggested_deletion_ids.is_empty(),
                    });
                }
            }
            if !runs
                .last()
                .is_some_and(|run| run.end == end && run.text.ends_with('\n'))
            {
                return Err(AnchorError::InvalidIndices);
            }
            let protected_newline = elements
                .get(position + 1)
                .is_none_or(|next| next.paragraph.is_none());
            out.push(Paragraph {
                tab,
                tab_id: tab_id.map(str::to_owned),
                container,
                start,
                end,
                protected_newline,
                runs,
            });
        } else if let Some(table) = &element.table {
            for row in &table.table_rows {
                for cell in &row.table_cells {
                    collect(&cell.content, tab, tab_id, segment, next_container, out)?;
                }
            }
        }
        // Tables of contents remain deliberately uneditable.
    }
    Ok(())
}

fn find(
    paragraphs: &[Paragraph<'_>],
    needle: &str,
    match_case: bool,
) -> Result<Match, AnchorError> {
    if needle.is_empty() || needle.contains(['\n', '\r']) {
        return Err(AnchorError::InvalidAnchor);
    }
    let pattern = RegexBuilder::new(&regex::escape(needle))
        .case_insensitive(!match_case)
        .build()
        .map_err(|_| AnchorError::InvalidAnchor)?;
    let mut count = 0;
    let mut unique = None;
    for (paragraph, p) in paragraphs.iter().enumerate() {
        // Group contiguous text runs. A missing index unit (image, break, etc.)
        // must not disappear and manufacture a match over its neighbours.
        let mut first = 0;
        while first < p.runs.len() {
            let mut last = first + 1;
            while last < p.runs.len() && p.runs[last - 1].end == p.runs[last].start {
                last += 1;
            }
            let runs = &p.runs[first..last];
            let text: String = runs.iter().map(|run| run.text).collect();
            let mut offset = 0;
            while let Some(found) = pattern.find_at(&text, offset) {
                let start = map_boundary(runs, found.start())?;
                let end = map_boundary(runs, found.end())?;
                let suggested = runs
                    .iter()
                    .any(|run| run.suggested && run.start < end && run.end > start);
                count += 1;
                unique = Some(Match {
                    paragraph,
                    start,
                    end,
                    suggested,
                });
                // Advance one scalar from the match start, so overlaps count too.
                offset = found.start()
                    + text[found.start()..]
                        .chars()
                        .next()
                        .ok_or(AnchorError::InvalidAnchor)?
                        .len_utf8();
            }
            first = last;
        }
    }
    match count {
        0 => Err(AnchorError::NotFound),
        1 => unique.ok_or(AnchorError::NotFound),
        count => Err(AnchorError::Ambiguous { count }),
    }
}

fn map_boundary(runs: &[Run<'_>], mut byte: usize) -> Result<i64, AnchorError> {
    for run in runs {
        if byte <= run.text.len() {
            let prefix = run.text.get(..byte).ok_or(AnchorError::InvalidIndices)?;
            return run
                .start
                .checked_add(utf16_len(prefix)?)
                .ok_or(AnchorError::InvalidIndices);
        }
        byte -= run.text.len();
    }
    Err(AnchorError::InvalidIndices) // omni-dev: coverage ignore-line reason="map_boundary is only called with a byte offset inside the text its runs concatenate, so the loop always returns first; the Err keeps the function total without a panic"
}

/// Counts the text Google actually inserts, excluding documented stripped
/// control characters and BMP private-use characters. The original text is
/// still sent verbatim; the server performs this filtering.
pub(crate) fn insertion_counts(text: &str) -> (usize, usize) {
    text.chars().filter(|ch| !matches!(ch, '\u{0000}'..='\u{0008}' | '\u{000c}'..='\u{001f}' | '\u{e000}'..='\u{f8ff}'))
        .fold((0, 0), |(chars, bytes), ch| (chars + 1, bytes + ch.len_utf8()))
}

/// Resolve insertion against a body anchor in the leased inline snapshot.
pub fn resolve_insert(
    document: &Document,
    anchor: &str,
    side: Side,
    text: &str,
    match_case: bool,
) -> Result<EditPreview, AnchorError> {
    resolve_insert_in(
        document,
        anchor,
        side,
        text,
        match_case,
        &SegmentSelection::default(),
    )
}

/// Resolve an anchored insert within an explicitly selected segment or tab bodies.
pub fn resolve_insert_in(
    document: &Document,
    anchor: &str,
    side: Side,
    text: &str,
    match_case: bool,
    selection: &SegmentSelection,
) -> Result<EditPreview, AnchorError> {
    let (chars, bytes) = insertion_counts(text);
    if chars == 0 {
        return Err(AnchorError::InvalidInsertionText);
    }
    let (paragraphs, segment_kind) = paragraphs(document, selection)?;
    let found = find(&paragraphs, anchor, match_case)?;
    if found.suggested {
        return Err(AnchorError::SuggestedContent);
    }
    let p = &paragraphs[found.paragraph];
    let index = match side {
        Side::Before => found.start,
        Side::After => found.end,
    };
    if index < p.start || index >= p.end {
        return Err(AnchorError::UnsafeRange); // omni-dev: coverage ignore-line reason="a match never contains the paragraph's closing newline (find rejects a needle with one) and collect verified the last run ends at it, so the index always lies inside the paragraph; kept as defence on the write boundary"
    }
    Ok(EditPreview {
        start_index: index,
        end_index: index,
        tab_id: p.tab_id.clone(),
        segment_id: selection.segment_id.clone(),
        segment_kind,
        paragraphs: 1,
        chars,
        bytes,
    })
}

/// Resolve deletion of one unique match, or an inclusive pair of anchors.
///
/// Cross-paragraph deletion is permitted only through contiguous plain text
/// within the same body or table cell. Protected newlines cannot be removed.
pub fn resolve_delete(
    document: &Document,
    from: &str,
    to: Option<&str>,
    match_case: bool,
) -> Result<EditPreview, AnchorError> {
    resolve_delete_in(document, from, to, match_case, &SegmentSelection::default())
}

/// Resolve an anchored delete within an explicitly selected segment or tab bodies.
pub fn resolve_delete_in(
    document: &Document,
    from: &str,
    to: Option<&str>,
    match_case: bool,
    selection: &SegmentSelection,
) -> Result<EditPreview, AnchorError> {
    let (paragraphs, segment_kind) = paragraphs(document, selection)?;
    let first = find(&paragraphs, from, match_case)?;
    let last = if let Some(to) = to {
        find(&paragraphs, to, match_case)?
    } else {
        first
    };
    let a = &paragraphs[first.paragraph];
    let b = &paragraphs[last.paragraph];
    if a.tab != b.tab
        || a.container != b.container
        || first.start > last.start
        || first.end > last.end
    {
        return Err(AnchorError::UnorderedRange);
    }
    let start = first.start;
    let end = last.end;
    let mut cursor = start;
    let mut chars = 0;
    let mut bytes = 0;
    let mut count = 0;
    for p in &paragraphs[first.paragraph..=last.paragraph] {
        if p.tab != a.tab || p.container != a.container {
            return Err(AnchorError::UnsafeRange); // omni-dev: coverage ignore-line reason="a container switch between two paragraphs of one container is always a table, and the paragraph before it has protected_newline, so the check below refuses the range before the walk reaches a foreign paragraph; kept as defence in depth"
        }
        if p.protected_newline && start < p.end && end >= p.end {
            return Err(AnchorError::UnsafeRange);
        }
        count += 1;
        for run in &p.runs {
            if run.end <= start || run.start >= end {
                continue;
            }
            if run.start > cursor {
                return Err(AnchorError::UnsafeRange);
            }
            if run.suggested {
                return Err(AnchorError::SuggestedContent);
            }
            let lo = cursor.max(run.start);
            let hi = end.min(run.end);
            let mut index = run.start;
            for ch in run.text.chars() {
                let next = index + ch.len_utf16() as i64;
                if index >= lo && next <= hi {
                    chars += 1;
                    bytes += ch.len_utf8();
                } else if index < hi && next > lo {
                    return Err(AnchorError::InvalidIndices); // omni-dev: coverage ignore-line reason="lo and hi are regex match boundaries mapped through whole runs, so neither falls inside a surrogate pair; kept as defence in the UTF-16 arithmetic"
                }
                index = next;
            }
            cursor = hi;
        }
    }
    if cursor != end {
        return Err(AnchorError::UnsafeRange); // omni-dev: coverage ignore-line reason="end is the end of the last anchor, which lies inside a run the loop above visits, and a gap before it already returned UnsafeRange, so the cursor always reaches it; kept as defence in depth"
    }
    Ok(EditPreview {
        start_index: start,
        end_index: end,
        tab_id: a.tab_id.clone(),
        segment_id: selection.segment_id.clone(),
        segment_kind,
        paragraphs: count,
        chars,
        bytes,
    })
}

/// Whole-paragraph formatting metadata. Indices describe the pre-write snapshot.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ListPreview {
    /// Inclusive start in server UTF-16 units.
    pub start_index: i64,
    /// Exclusive end, including the last selected paragraph's newline.
    pub end_index: i64,
    /// Absent only for legacy top-level body responses.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tab_id: Option<String>,
    /// Number of complete paragraphs selected.
    pub paragraphs: usize,
    /// Leading tabs Google removes on creation; zero for removal.
    pub leading_tabs_removed: usize,
}

/// Resolve whole paragraphs for list formatting, within one body or table cell.
/// Unlike deletion, this range may include a container's final newline.
pub fn resolve_list(
    document: &Document,
    from: &str,
    to: Option<&str>,
    match_case: bool,
    creating: bool,
) -> Result<ListPreview, AnchorError> {
    // List formatting is body-only: it never selects a header, footer or footnote.
    let (paragraphs, _) = paragraphs(document, &SegmentSelection::default())?;
    let first = find(&paragraphs, from, match_case)?;
    let last = if let Some(to) = to {
        find(&paragraphs, to, match_case)?
    } else {
        first
    };
    let a = &paragraphs[first.paragraph];
    let b = &paragraphs[last.paragraph];
    if first.paragraph > last.paragraph
        || a.tab != b.tab
        || a.container != b.container
        || first.start > last.start
        || first.end > last.end
    {
        return Err(AnchorError::UnorderedRange);
    }
    let mut cursor = a.start;
    let mut leading_tabs_removed = 0;
    for p in &paragraphs[first.paragraph..=last.paragraph] {
        if p.tab != a.tab || p.container != a.container || p.start != cursor {
            return Err(AnchorError::UnsafeRange);
        }
        let mut leading = creating;
        for run in &p.runs {
            if run.start != cursor {
                return Err(AnchorError::UnsafeRange);
            }
            if run.suggested {
                return Err(AnchorError::SuggestedContent);
            }
            for ch in run.text.chars() {
                if leading && ch == '\t' {
                    leading_tabs_removed += 1;
                } else {
                    leading = false;
                }
            }
            cursor = run.end;
        }
        if cursor != p.end {
            return Err(AnchorError::UnsafeRange); // omni-dev: coverage ignore-line reason="collect verified every paragraph has a final run ending at p.end, and the loop above leaves cursor at that run's end, so it always matches; kept as defence in depth on the write boundary"
        }
        // Structural elements can occupy no text index space, so contiguity
        // alone is insufficient. The last paragraph is safe to format.
        if p.protected_newline && p.end != b.end {
            return Err(AnchorError::UnsafeRange);
        }
    }
    Ok(ListPreview {
        start_index: a.start,
        end_index: b.end,
        tab_id: a.tab_id.clone(),
        paragraphs: last.paragraph - first.paragraph + 1,
        leading_tabs_removed,
    })
}

/// Resolve formatting against the leased snapshot. Paragraph styling affects
/// whole paragraphs, so validate and count their complete contents as well.
pub fn resolve_format(
    document: &Document,
    from: &str,
    to: Option<&str>,
    match_case: bool,
    whole_paragraphs: bool,
) -> Result<EditPreview, AnchorError> {
    let mut edit = resolve_delete(document, from, to, match_case)?;
    let (paragraphs, _) = paragraphs(document, &SegmentSelection::default())?;
    if !whole_paragraphs {
        // Google may extend text styling to adjacent newlines. Validate any
        // suggested newline at either edge even when it is outside the
        // requested range; its styling must not bypass suggestion refusal.
        for p in paragraphs.iter().filter(|p| p.tab_id == edit.tab_id) {
            for run in &p.runs {
                if run.suggested
                    && ((run.end == edit.start_index && run.text.ends_with('\n'))
                        || (run.start == edit.end_index && run.text.starts_with('\n')))
                {
                    return Err(AnchorError::SuggestedContent);
                }
            }
        }
        return Ok(edit);
    }
    let affected: Vec<_> = paragraphs
        .iter()
        .filter(|p| {
            p.tab_id == edit.tab_id && p.start.max(edit.start_index) < p.end.min(edit.end_index)
        })
        .collect();
    let first = affected.first().ok_or(AnchorError::InvalidIndices)?;
    let last = affected.last().ok_or(AnchorError::InvalidIndices)?;
    let mut cursor = first.start;
    edit.chars = 0;
    edit.bytes = 0;
    for p in &affected {
        if p.container != first.container || p.start != cursor {
            return Err(AnchorError::UnsafeRange);
        }
        for run in &p.runs {
            if run.start != cursor {
                return Err(AnchorError::UnsafeRange);
            }
            if run.suggested {
                return Err(AnchorError::SuggestedContent);
            }
            edit.chars += run.text.chars().count();
            edit.bytes += run.text.len();
            cursor = run.end;
        }
        if cursor != p.end {
            return Err(AnchorError::UnsafeRange); // omni-dev: coverage ignore-line reason="collect refuses a paragraph whose last run does not end at the paragraph's end, and the loop above leaves cursor on the last run's end, so cursor always equals p.end here; kept as defence in depth on the write boundary"
        }
    }
    edit.start_index = first.start;
    edit.end_index = last.end;
    edit.paragraphs = affected.len();
    Ok(edit)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use proptest::prelude::*;
    use serde_json::{json, Value};

    fn paragraph(start: i64, runs: &[&str]) -> Value {
        let mut index = start;
        let elements: Vec<Value> = runs
            .iter()
            .map(|text| {
                let end = index + text.encode_utf16().count() as i64;
                let element =
                    json!({"startIndex": index, "endIndex": end, "textRun": {"content": text}});
                index = end;
                element
            })
            .collect();
        json!({"startIndex": start, "endIndex": index, "paragraph": {"elements": elements}})
    }

    fn doc(content: Vec<Value>) -> Document {
        serde_json::from_value(json!({"body": {"content": content}})).unwrap()
    }

    fn selection(id: &str) -> SegmentSelection {
        SegmentSelection {
            segment_id: Some(id.into()),
            tab_id: None,
        }
    }

    #[test]
    fn all_segment_families_use_zero_based_utf16_and_ignore_other_content() {
        for (map, kind) in [
            ("headers", SegmentKind::Header),
            ("footers", SegmentKind::Footer),
            ("footnotes", SegmentKind::Footnote),
        ] {
            let mut p = paragraph(0, &["😀 a", "nchor\n"]);
            p.as_object_mut().unwrap().remove("startIndex");
            p["paragraph"]["elements"][0]
                .as_object_mut()
                .unwrap()
                .remove("startIndex");
            let document: Document = serde_json::from_value(json!({
                "body": {"content": [paragraph(1, &["anchor anchor\n"])]},
                map: {"s": {"content": [p]}, "other": {"content": [{"paragraph": {}}]}}
            }))
            .unwrap();
            let edit = resolve_delete_in(&document, "anchor", None, true, &selection("s")).unwrap();
            assert_eq!(
                (edit.start_index, edit.end_index, edit.chars, edit.bytes),
                (3, 9, 6, 6)
            );
            assert_eq!(edit.segment_id.as_deref(), Some("s"));
            assert_eq!(edit.segment_kind, Some(kind));
            assert_eq!(
                resolve_insert_in(&document, "😀", Side::Before, "x", true, &selection("s"))
                    .unwrap()
                    .start_index,
                0
            );
            assert_eq!(
                resolve_delete(&document, "anchor", None, true),
                Err(AnchorError::Ambiguous { count: 2 })
            );
        }
    }

    #[test]
    fn segment_identity_is_resolved_before_anchor_uniqueness_in_child_tabs() {
        let document: Document = serde_json::from_value(json!({"tabs": [{
            "tabProperties": {"tabId": "parent"},
            "documentTab": {"headers": {"s": {"content": [paragraph(0, &["other\n"])]}}},
            "childTabs": [{"tabProperties": {"tabId": "child"}, "documentTab": {"footnotes": {"s": {"content": [paragraph(0, &["anchor\n"])]}}}}]
        }]})).unwrap();
        assert_eq!(
            resolve_delete_in(&document, "anchor", None, true, &selection("s")),
            Err(AnchorError::AmbiguousSegment)
        );
        let mut selected = selection("s");
        selected.tab_id = Some("child".into());
        let edit = resolve_delete_in(&document, "anchor", None, true, &selected).unwrap();
        assert_eq!(edit.tab_id.as_deref(), Some("child"));
        assert_eq!(edit.segment_kind, Some(SegmentKind::Footnote));
        selected.tab_id = Some("missing".into());
        assert_eq!(
            resolve_delete_in(&document, "anchor", None, true, &selected),
            Err(AnchorError::SegmentNotFound)
        );
        for invalid in [
            selection(""),
            SegmentSelection {
                segment_id: None,
                tab_id: Some("child".into()),
            },
            SegmentSelection {
                segment_id: Some("s".into()),
                tab_id: Some(String::new()),
            },
        ] {
            assert_eq!(
                resolve_delete_in(&document, "anchor", None, true, &invalid),
                Err(AnchorError::InvalidSelection)
            );
        }
    }

    #[test]
    fn selected_segments_preserve_suggestion_and_structural_guards() {
        let mut suggested = paragraph(0, &["anchor\n"]);
        suggested["paragraph"]["elements"][0]["textRun"]["suggestedDeletionIds"] =
            json!(["suggestion"]);
        let document: Document =
            serde_json::from_value(json!({"headers": {"s": {"content": [suggested]}}})).unwrap();
        assert_eq!(
            resolve_delete_in(&document, "anchor", None, true, &selection("s")),
            Err(AnchorError::SuggestedContent)
        );
        assert_eq!(
            resolve_insert_in(&document, "anchor", Side::After, "x", true, &selection("s")),
            Err(AnchorError::SuggestedContent)
        );
        let document: Document = serde_json::from_value(json!({"footers": {"s": {"content": [
            paragraph(0, &["first\n"]), {"startIndex": 6, "endIndex": 7, "sectionBreak": {}}, paragraph(7, &["last\n"])
        ]}}})).unwrap();
        assert_eq!(
            resolve_delete_in(&document, "first", Some("last"), true, &selection("s")),
            Err(AnchorError::UnsafeRange)
        );
        assert_eq!(
            resolve_delete_in(&document, "last\n", None, true, &selection("s")),
            Err(AnchorError::InvalidAnchor)
        );
        let edit = resolve_delete_in(&document, "last", None, true, &selection("s")).unwrap();
        assert_eq!(edit.end_index, 11); // The final newline at 11 survives.
    }

    #[test]
    fn segment_table_cells_and_inline_gaps_cannot_be_crossed() {
        let gap = json!({"endIndex": 4, "paragraph": {"elements": [
            {"endIndex": 1, "textRun": {"content": "a"}},
            {"startIndex": 1, "endIndex": 2, "footnoteReference": {"footnoteId": "note"}},
            {"startIndex": 2, "endIndex": 4, "textRun": {"content": "b\n"}}
        ]}});
        let document: Document =
            serde_json::from_value(json!({"footnotes": {"s": {"content": [gap]}}})).unwrap();
        assert_eq!(
            resolve_delete_in(&document, "ab", None, true, &selection("s")),
            Err(AnchorError::NotFound)
        );
        assert_eq!(
            resolve_delete_in(&document, "a", Some("b"), true, &selection("s")),
            Err(AnchorError::UnsafeRange)
        );
        let document: Document = serde_json::from_value(json!({"headers": {"s": {"content": [
            paragraph(0, &["before\n"]), {"startIndex": 7, "endIndex": 30, "table": {"tableRows": [{"tableCells": [
                {"content": [paragraph(9, &["first\n"])]}, {"content": [paragraph(20, &["last\n"])]}
            ]}]}}
        ]}}})).unwrap();
        assert_eq!(
            resolve_delete_in(&document, "first", Some("last"), true, &selection("s")),
            Err(AnchorError::UnorderedRange)
        );
        assert_eq!(
            resolve_delete_in(&document, "before", Some("first"), true, &selection("s")),
            Err(AnchorError::UnorderedRange)
        );
        assert_eq!(
            resolve_delete_in(&document, "first", None, true, &selection("s"))
                .unwrap()
                .end_index,
            14
        );
    }

    #[test]
    fn astral_characters_and_split_runs_use_server_utf16_indices() {
        let document = doc(vec![paragraph(1, &["😀 a", "nchor\n"])]);
        let edit = resolve_insert(&document, "anchor", Side::After, "x", true).unwrap();
        assert_eq!((edit.start_index, edit.end_index), (10, 10));
        let edit = resolve_delete(&document, "anchor", None, true).unwrap();
        assert_eq!((edit.start_index, edit.end_index, edit.chars), (4, 10, 6));
    }

    #[test]
    fn unicode_case_folding_preserves_original_boundaries_and_matches_literals() {
        let document = doc(vec![paragraph(1, &["😀 \u{212a}.[İ]\n"])]);
        let edit = resolve_delete(&document, "k.[İ]", None, false).unwrap();
        assert_eq!(
            (edit.start_index, edit.end_index, edit.chars, edit.bytes),
            (4, 9, 5, 8)
        );
        assert_eq!(
            resolve_delete(&document, "k.[İ]", None, true),
            Err(AnchorError::NotFound)
        );
    }

    #[test]
    fn overlapping_matches_are_ambiguous_and_paragraph_breaks_are_not_anchors() {
        let document = doc(vec![paragraph(1, &["aaa\n"])]);
        assert_eq!(
            resolve_delete(&document, "aa", None, true),
            Err(AnchorError::Ambiguous { count: 2 })
        );
        assert_eq!(
            resolve_delete(&document, "a\na", None, true),
            Err(AnchorError::InvalidAnchor)
        );
        assert_eq!(
            resolve_delete(&document, "", None, true),
            Err(AnchorError::InvalidAnchor)
        );
        assert_eq!(
            resolve_delete(&document, "absent", None, true),
            Err(AnchorError::NotFound)
        );
    }

    #[test]
    fn inline_objects_do_not_shift_later_anchors_or_manufacture_matches() {
        let document = doc(vec![
            json!({"startIndex": 1, "endIndex": 5, "paragraph": {"elements": [
                {"startIndex": 1, "endIndex": 2, "textRun": {"content": "a"}},
                {"startIndex": 2, "endIndex": 3, "inlineObjectElement": {"inlineObjectId": "img"}},
                {"startIndex": 3, "endIndex": 5, "textRun": {"content": "b\n"}}
            ]}}),
        ]);
        assert_eq!(
            resolve_insert(&document, "b", Side::Before, "x", true)
                .unwrap()
                .start_index,
            3
        );
        assert_eq!(
            resolve_delete(&document, "ab", None, true),
            Err(AnchorError::NotFound)
        );
        assert_eq!(
            resolve_delete(&document, "a", Some("b"), true),
            Err(AnchorError::UnsafeRange)
        );
    }

    #[test]
    fn incomplete_or_inconsistent_indices_are_refused() {
        let mut p = paragraph(1, &["anchor\n"]);
        p["paragraph"]["elements"][0]
            .as_object_mut()
            .unwrap()
            .remove("startIndex");
        assert_eq!(
            resolve_delete(&doc(vec![p]), "anchor", None, true),
            Err(AnchorError::InvalidIndices)
        );
        let mut p = paragraph(1, &["😀 anchor\n"]);
        p["paragraph"]["elements"][0]["endIndex"] = json!(8);
        assert_eq!(
            resolve_delete(&doc(vec![p]), "anchor", None, true),
            Err(AnchorError::InvalidIndices)
        );
    }

    #[test]
    fn paragraph_and_run_indices_that_do_not_nest_are_refused() {
        type Mutation = fn(&mut Value);
        let cases: [(&str, Mutation); 7] = [
            ("paragraph starts before the body", |p| {
                p["startIndex"] = json!(0);
            }),
            ("paragraph is empty", |p| {
                p["endIndex"] = json!(1);
            }),
            ("run overlaps the previous run", |p| {
                p["paragraph"]["elements"][1]["startIndex"] = json!(2);
            }),
            ("run is empty", |p| {
                p["paragraph"]["elements"][1]["endIndex"] = json!(4);
            }),
            ("run overruns its paragraph", |p| {
                p["endIndex"] = json!(7);
            }),
            ("last run is not newline-terminated", |p| {
                p["paragraph"]["elements"][1]["textRun"]["content"] = json!("def");
                p["paragraph"]["elements"][1]["endIndex"] = json!(7);
                p["endIndex"] = json!(7);
            }),
            ("last run stops short of the paragraph end", |p| {
                p["endIndex"] = json!(9);
            }),
        ];
        for (name, mutate) in cases {
            let mut p = paragraph(1, &["abc", "def\n"]);
            mutate(&mut p);
            assert_eq!(
                resolve_delete(&doc(vec![p]), "abc", None, true),
                Err(AnchorError::InvalidIndices),
                "{name}"
            );
        }
        let mut p = paragraph(1, &["abc\n"]);
        p["paragraph"]["elements"] = json!([]);
        assert_eq!(
            resolve_delete(&doc(vec![p]), "abc", None, true),
            Err(AnchorError::InvalidIndices),
            "a paragraph with no runs"
        );
    }

    #[test]
    fn suggestions_in_anchors_and_inside_ranges_are_refused() {
        for field in ["suggestedInsertionIds", "suggestedDeletionIds"] {
            let mut p = paragraph(1, &["start ", "pending", " finish\n"]);
            p["paragraph"]["elements"][1]["textRun"][field] = json!(["suggestion"]);
            let document = doc(vec![p]);
            assert_eq!(
                resolve_insert(&document, "pending", Side::After, "x", true),
                Err(AnchorError::SuggestedContent)
            );
            assert_eq!(
                resolve_delete(&document, "start", Some("finish"), true),
                Err(AnchorError::SuggestedContent)
            );
            assert!(resolve_delete(&document, "start", None, true).is_ok());
        }
    }

    #[test]
    fn safe_ranges_span_paragraphs_and_preserve_the_last_newline() {
        let document = doc(vec![paragraph(1, &["start\n"]), paragraph(7, &["end\n"])]);
        let edit = resolve_delete(&document, "start", Some("end"), true).unwrap();
        assert_eq!(
            (
                edit.start_index,
                edit.end_index,
                edit.chars,
                edit.paragraphs
            ),
            (1, 10, 9, 2)
        );
        assert_eq!(
            resolve_delete(&document, "end", Some("start"), true),
            Err(AnchorError::UnorderedRange)
        );
        assert_eq!(
            resolve_insert(&document, "end", Side::After, "x", true)
                .unwrap()
                .start_index,
            10
        );
        assert_eq!(
            resolve_insert(&document, "end\n", Side::After, "x", true),
            Err(AnchorError::InvalidAnchor)
        );
    }

    #[test]
    fn tables_cells_and_tabs_have_independent_boundaries() {
        let table = json!({"startIndex": 8, "endIndex": 30, "table": {"tableRows": [{"tableCells": [
            {"content": [paragraph(11, &["cell\n"])]},
            {"content": [paragraph(18, &["other\n"])]}
        ]}]}});
        let document = doc(vec![
            paragraph(1, &["before\n"]),
            table,
            paragraph(30, &["after\n"]),
        ]);
        assert_eq!(
            resolve_insert(&document, "cell", Side::After, "x", true)
                .unwrap()
                .start_index,
            15
        );
        assert_eq!(
            resolve_delete(&document, "cell", Some("other"), true),
            Err(AnchorError::UnorderedRange)
        );
        assert_eq!(
            resolve_delete(&document, "before", Some("after"), true),
            Err(AnchorError::UnsafeRange)
        );
        let tabbed: Document = serde_json::from_value(json!({"tabs": [
            {"tabProperties": {"tabId": "t1"}, "documentTab": {"body": {"content": [paragraph(1, &["start\n"])]}},
             "childTabs": [{"tabProperties": {"tabId": "t2"}, "documentTab": {"body": {"content": [paragraph(1, &["end\n"])]}}}]}
        ]})).unwrap();
        assert_eq!(
            resolve_insert(&tabbed, "end", Side::Before, "x", true)
                .unwrap()
                .tab_id
                .as_deref(),
            Some("t2")
        );
        assert_eq!(
            resolve_delete(&tabbed, "start", Some("end"), true),
            Err(AnchorError::UnorderedRange)
        );
    }

    #[test]
    fn non_body_and_table_of_contents_text_is_not_addressable() {
        let document: Document = serde_json::from_value(json!({
            "headers": {"h1": {"content": [paragraph(1, &["header\n"])]}},
            "body": {"content": [{"tableOfContents": {"content": [paragraph(1, &["toc\n"])]}}]}
        }))
        .unwrap();
        for needle in ["header", "toc"] {
            assert_eq!(
                resolve_delete(&document, needle, None, true),
                Err(AnchorError::NotFound)
            );
        }
    }

    #[test]
    fn lists_expand_unicode_anchors_to_whole_paragraphs_and_count_split_leading_tabs() {
        let document = doc(vec![
            paragraph(1, &["\t", "\t😀 K", "elvin\n"]),
            paragraph(13, &["\tlast\n"]),
            paragraph(19, &["untouched\n"]),
        ]);
        let edit = resolve_list(&document, "kelvin", Some("last"), false, true).unwrap();
        assert_eq!(
            (
                edit.start_index,
                edit.end_index,
                edit.paragraphs,
                edit.leading_tabs_removed
            ),
            (1, 19, 2, 3)
        );
        let single = resolve_list(&document, "last", None, true, false).unwrap();
        assert_eq!(
            (
                single.start_index,
                single.end_index,
                single.leading_tabs_removed
            ),
            (13, 19, 0)
        );
        assert_eq!(
            resolve_list(&document, "last", Some("Kelvin"), true, true),
            Err(AnchorError::UnorderedRange)
        );
        assert_eq!(
            resolve_list(&document, "Kelvin", None, false, true)
                .unwrap()
                .end_index,
            13
        );
    }

    #[test]
    fn list_formatting_refuses_objects_gaps_structures_and_suggestions_outside_anchor() {
        let object = json!({"startIndex": 1, "endIndex": 5, "paragraph": {"elements": [
            {"startIndex": 1, "endIndex": 2, "inlineObjectElement": {"inlineObjectId": "img"}},
            {"startIndex": 2, "endIndex": 5, "textRun": {"content": "ok\n"}}
        ]}});
        assert_eq!(
            resolve_list(&doc(vec![object]), "ok", None, true, true),
            Err(AnchorError::UnsafeRange)
        );
        let gap = doc(vec![paragraph(1, &["first\n"]), paragraph(8, &["last\n"])]);
        assert_eq!(
            resolve_list(&gap, "first", Some("last"), true, true),
            Err(AnchorError::UnsafeRange)
        );
        // Even a structural break occupying no additional index must refuse.
        let structure = doc(vec![
            paragraph(1, &["first\n"]),
            json!({"sectionBreak": {}}),
            paragraph(7, &["last\n"]),
        ]);
        assert_eq!(
            resolve_list(&structure, "first", Some("last"), true, true),
            Err(AnchorError::UnsafeRange)
        );
        for creating in [true, false] {
            for field in ["suggestedInsertionIds", "suggestedDeletionIds"] {
                let mut p = paragraph(1, &["\t", "anchor", " pending\n"]);
                p["paragraph"]["elements"][0]["textRun"][field] = json!(["s"]);
                assert_eq!(
                    resolve_list(&doc(vec![p]), "anchor", None, true, creating),
                    Err(AnchorError::SuggestedContent)
                );
            }
        }
        let out_of_order = doc(vec![
            paragraph(10, &["later\n"]),
            paragraph(1, &["earlier\n"]),
        ]);
        assert_eq!(
            resolve_list(&out_of_order, "earlier", Some("later"), true, true),
            Err(AnchorError::UnorderedRange)
        );
        let mut invalid = paragraph(1, &["anchor\n"]);
        invalid["endIndex"] = json!(9);
        assert_eq!(
            resolve_list(&doc(vec![invalid]), "anchor", None, true, true),
            Err(AnchorError::InvalidIndices)
        );
    }

    #[test]
    fn lists_respect_table_cells_and_nested_tab_identity_and_final_newlines() {
        let table = json!({"table": {"tableRows": [{"tableCells": [
            {"content": [paragraph(11, &["cell\n"])]},
            {"content": [paragraph(18, &["other\n"])]}
        ]}]}});
        let document = doc(vec![
            paragraph(1, &["before\n"]),
            table,
            paragraph(30, &["after\n"]),
        ]);
        assert_eq!(
            resolve_list(&document, "cell", None, true, true)
                .unwrap()
                .end_index,
            16
        );
        assert_eq!(
            resolve_list(&document, "cell", Some("other"), true, false),
            Err(AnchorError::UnorderedRange)
        );
        assert_eq!(
            resolve_list(&document, "before", Some("after"), true, true),
            Err(AnchorError::UnsafeRange)
        );
        let tabbed: Document = serde_json::from_value(json!({"tabs": [
            {"tabProperties": {"tabId": "t1"}, "documentTab": {"body": {"content": [paragraph(1, &["first\n"])]}},
             "childTabs": [{"tabProperties": {"tabId": "t2"}, "documentTab": {"body": {"content": [paragraph(1, &["last\n"])]}}}]}
        ]})).unwrap();
        let edit = resolve_list(&tabbed, "last", None, true, true).unwrap();
        assert_eq!(edit.tab_id.as_deref(), Some("t2"));
        assert_eq!((edit.start_index, edit.end_index), (1, 6));
        assert_eq!(
            resolve_list(&tabbed, "first", Some("last"), true, true),
            Err(AnchorError::UnorderedRange)
        );
        assert_eq!(
            resolve_list(&doc(vec![paragraph(1, &["aaa\n"])]), "aa", None, true, true),
            Err(AnchorError::Ambiguous { count: 2 })
        );
    }

    proptest! {
        #[test]
        fn random_unicode_prefixes_and_run_splits_preserve_utf16_offsets(
            prefix in prop::collection::vec(prop_oneof![Just('😀'), Just('𠀀'), Just('é'), Just('x')], 0..80),
            split in 0usize..100,
        ) {
            let prefix: String = prefix.into_iter().collect();
            let text = format!("{prefix}ANCHOR\n");
            let boundaries: Vec<usize> = text.char_indices().map(|(i, _)| i).chain(std::iter::once(text.len())).collect();
            let byte = boundaries[split % boundaries.len()];
            let runs: Vec<&str> = [&text[..byte], &text[byte..]].into_iter().filter(|s| !s.is_empty()).collect();
            let document = doc(vec![paragraph(1, &runs)]);
            let edit = resolve_delete(&document, "ANCHOR", None, true).unwrap();
            prop_assert_eq!(edit.start_index, 1 + prefix.encode_utf16().count() as i64);
            prop_assert_eq!(edit.end_index, edit.start_index + 6);
            let list = resolve_list(&document, "ANCHOR", None, true, true).unwrap();
            prop_assert_eq!(list.start_index, 1);
            prop_assert_eq!(list.end_index, 1 + text.encode_utf16().count() as i64);
            prop_assert_eq!(list.paragraphs, 1);
        }
    }
    #[test]
    fn insertion_counts_exclude_characters_stripped_by_google() {
        let document = doc(vec![paragraph(1, &["anchor\n"])]);
        let edit =
            resolve_insert(&document, "anchor", Side::After, "\0😀\r\u{e000}x\n", true).unwrap();
        assert_eq!((edit.chars, edit.bytes), (3, 6));
        assert_eq!(
            resolve_insert(&document, "anchor", Side::After, "\0\r", true),
            Err(AnchorError::InvalidInsertionText)
        );
    }

    #[test]
    fn missing_empty_or_duplicate_tab_ids_are_refused() {
        for ids in [vec![None], vec![Some("")], vec![Some("same"), Some("same")]] {
            let tabs: Vec<Value> = ids.into_iter().map(|id| json!({
                "tabProperties": {"tabId": id}, "documentTab": {"body": {"content": [paragraph(1, &["anchor\n"])]}}
            })).collect();
            let document: Document = serde_json::from_value(json!({"tabs": tabs})).unwrap();
            assert_eq!(
                resolve_insert(&document, "anchor", Side::Before, "x", true),
                Err(AnchorError::InvalidIndices)
            );
            assert_eq!(
                resolve_list(&document, "anchor", None, true, true),
                Err(AnchorError::InvalidIndices)
            );
        }
    }
    #[test]
    fn formatting_resolves_utf16_and_expands_whole_paragraph_effects() {
        let document = doc(vec![
            paragraph(1, &["😀 pre ", "anchor tail\n"]),
            paragraph(21, &["end\n"]),
        ]);
        let text = resolve_format(&document, "anchor", None, true, false).unwrap();
        assert_eq!(
            (text.start_index, text.end_index, text.chars, text.bytes),
            (8, 14, 6, 6)
        );
        let p = resolve_format(&document, "anchor", None, true, true).unwrap();
        assert_eq!(
            (p.start_index, p.end_index, p.chars, p.bytes, p.paragraphs),
            (1, 20, 18, 21, 1)
        );
        // A gap between paragraphs remains unsafe.
        assert!(resolve_format(&document, "anchor", Some("end"), true, true).is_err());
        let document = doc(vec![
            paragraph(1, &["😀 pre ", "anchor tail\n"]),
            paragraph(20, &["end\n"]),
        ]);
        let p = resolve_format(&document, "anchor", Some("end"), true, true).unwrap();
        assert_eq!(
            (p.start_index, p.end_index, p.paragraphs, p.chars, p.bytes),
            (1, 24, 2, 22, 25)
        );
    }

    #[test]
    fn paragraph_formatting_refuses_suggestions_and_objects_outside_anchors() {
        let mut p = paragraph(1, &["prefix ", "anchor\n"]);
        p["paragraph"]["elements"][0]["textRun"]["suggestedInsertionIds"] = json!(["pending"]);
        let document = doc(vec![p]);
        assert!(resolve_format(&document, "anchor", None, true, false).is_ok());
        assert_eq!(
            resolve_format(&document, "anchor", None, true, true),
            Err(AnchorError::SuggestedContent)
        );
        let document = doc(vec![
            json!({"startIndex": 1, "endIndex": 9, "paragraph": {"elements": [
                {"startIndex": 1, "endIndex": 2, "inlineObjectElement": {"inlineObjectId": "img"}},
                {"startIndex": 2, "endIndex": 9, "textRun": {"content": "anchor\n"}}
            ]}}),
        ]);
        assert!(resolve_format(&document, "anchor", None, true, false).is_ok());
        assert_eq!(
            resolve_format(&document, "anchor", None, true, true),
            Err(AnchorError::UnsafeRange)
        );
    }

    /// `resolve_delete` only walks the runs under the anchors, so paragraph
    /// styling re-checks that the whole paragraphs it widens to tile the range
    /// without overlapping — a server-side inconsistency must not be styled.
    #[test]
    fn paragraph_formatting_refuses_paragraphs_whose_indices_overlap() {
        let document = doc(vec![
            paragraph(1, &["aaaaaa\n"]),
            paragraph(5, &["bbbbbb\n"]),
        ]);
        assert!(resolve_delete(&document, "aaaaaa", Some("bbbbbb"), true).is_ok());
        assert!(resolve_format(&document, "aaaaaa", Some("bbbbbb"), true, false).is_ok());
        assert_eq!(
            resolve_format(&document, "aaaaaa", Some("bbbbbb"), true, true),
            Err(AnchorError::UnsafeRange)
        );
    }

    #[test]
    fn paragraph_formatting_preserves_nested_tab_identity() {
        let document: Document = serde_json::from_value(json!({"tabs": [{"tabProperties": {"tabId": "parent"}, "childTabs": [{"tabProperties": {"tabId": "child"}, "documentTab": {"body": {"content": [paragraph(1, &["😀 anchor\n"])]}}}]}]})).unwrap();
        let p = resolve_format(&document, "anchor", None, true, true).unwrap();
        assert_eq!(p.tab_id.as_deref(), Some("child"));
        assert_eq!((p.start_index, p.end_index), (1, 11));
    }
    #[test]
    fn text_formatting_refuses_suggested_adjacent_newlines() {
        let mut p = paragraph(1, &["anchor", "\n"]);
        p["paragraph"]["elements"][1]["textRun"]["suggestedDeletionIds"] = json!(["pending"]);
        assert_eq!(
            resolve_format(&doc(vec![p]), "anchor", None, true, false),
            Err(AnchorError::SuggestedContent)
        );
        let mut preceding = paragraph(1, &["before", "\n"]);
        preceding["paragraph"]["elements"][1]["textRun"]["suggestedInsertionIds"] =
            json!(["pending"]);
        assert_eq!(
            resolve_format(
                &doc(vec![preceding, paragraph(8, &["anchor\n"])]),
                "anchor",
                None,
                true,
                false
            ),
            Err(AnchorError::SuggestedContent)
        );
        // Unsuggested adjacent newlines remain valid.
        assert!(resolve_format(
            &doc(vec![paragraph(1, &["anchor", "\n"])]),
            "anchor",
            None,
            true,
            false
        )
        .is_ok());
    }
}