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
//! Wire types for the Docs v1 REST API.
//!
//! Field naming follows Docs' camelCase JSON via per-field
//! `#[serde(rename = "...")]`, mirroring `src/drive/types.rs` and
//! `src/drive/sheets/types.rs`. Only the subset the CLI actually renders is
//! modelled; every unmodelled field is tolerated and dropped, so a Google
//! response gaining a field never breaks a parse.
//!
//! Four shapes here are load-bearing and easy to get wrong:
//!
//! - **`startIndex` is absent, not `0`, for the first element.** Docs
//!   serialises proto3 JSON, which omits zero-valued integers, so every real
//!   `documents.get` has `body.content[0]` (the leading `sectionBreak`) with
//!   no `startIndex` key at all. Every index field is therefore
//!   `Option<i64>`, read through the `start_index()`/`end_index()`
//!   accessors. This is the direct analogue of `ValueRange::values` being
//!   absent-not-empty for a blank sheet.
//! - **Indices are UTF-16 code units, and `endIndex` is exclusive.** Not
//!   chars, not bytes. Any code deriving an index from a `&str` must use
//!   `s.encode_utf16().count()`. The difference is invisible in ASCII and
//!   wrong the moment a document contains an emoji or a CJK astral
//!   character, so only the anchor resolver computes one — see
//!   `crate::drive::docs::anchor`.
//! - **An empty message still serialises as `{}` when present.** A
//!   `sectionBreak` with no fields set arrives as `"sectionBreak": {}`, so
//!   the union variants this module does not inspect are modelled as
//!   `Option<serde_json::Value>`: `Some(Object({}))` when present, `None`
//!   when absent, which is exactly the discriminator semantics needed.
//! - **`tabs` and `body` are mutually exclusive.** With
//!   `includeTabsContent=true` the content lives under `tabs[]` and the
//!   top-level `body` is absent; without it, only `body` is populated. That
//!   is normalised once, in [`Document::resolved_tabs`], rather than at
//!   every call site.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

/// A document's full structural model, from `documents.get`.
///
/// Deliberately **not** `fields`-masked when fetched — unlike
/// `spreadsheets.get`, whose mask exists to keep every cell out of the
/// response. A Docs mask has to spell nesting depth out literally, and a
/// table may contain a table to arbitrary depth, so any fixed-depth mask
/// silently drops document text below its deepest named level. See
/// `crate::drive::docs::api`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Document {
    /// The document's id (echoes the one requested).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "documentId"
    )]
    pub document_id: Option<String>,
    /// The document's display title.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// The revision this response reflects.
    ///
    /// Google populates this **only for callers with edit access**, so a
    /// read-only caller sees `None`. It is the `writeControl`
    /// `requiredRevisionId` token a later `documents.batchUpdate` presents
    /// to refuse a write against a document that moved underneath it.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "revisionId"
    )]
    pub revision_id: Option<String>,
    /// Legacy single-tab content, populated only when the request did not
    /// ask for tab content. Mutually exclusive with [`Self::tabs`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<Body>,
    /// The tab tree, populated only when `includeTabsContent=true`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tabs: Vec<Tab>,
    /// Named ranges, keyed by name.
    ///
    /// The *stable* way to address a region: an index shifts on every
    /// insertion, a named range's name does not.
    #[serde(
        default,
        skip_serializing_if = "HashMap::is_empty",
        rename = "namedRanges"
    )]
    pub named_ranges: HashMap<String, NamedRanges>,
    /// Page headers, keyed by `segmentId`. Legacy shape only — see
    /// [`Self::resolved_tabs`].
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub headers: HashMap<String, Header>,
    /// Page footers, keyed by `segmentId`. Legacy shape only.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub footers: HashMap<String, Footer>,
    /// Footnotes, keyed by `segmentId`. Legacy shape only.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub footnotes: HashMap<String, Footnote>,
}

/// One header, footer or footnote segment, resolved and ready to flatten.
///
/// The map key Google addresses it by (a `segmentId`) is carried alongside
/// its content rather than discarded, since it is the only thing that
/// distinguishes e.g. two headers on the same tab from one another.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResolvedSegment<'a> {
    /// The segment's id — the map key it is stored under.
    pub segment_id: &'a str,
    /// The segment's structural elements, in index order.
    pub content: &'a [StructuralElement],
}

/// One tab's content, with the legacy single-`body` response normalised into
/// the same shape so callers never branch on which form arrived.
///
/// Header/footer/footnote content is resolved **lazily**, via
/// [`Self::headers`]/[`Self::footers`]/[`Self::footnotes`], rather than
/// eagerly at construction: `docs info`'s outline and the write-preview
/// corpus builders only ever read [`Self::body`], and paying the sort for
/// a footnote-heavy document they discard immediately would be pure waste.
/// Only `docs read` calls the accessors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResolvedTab<'a> {
    /// The tab's id, or `None` for a legacy single-body document.
    pub tab_id: Option<&'a str>,
    /// The tab's title, or `None` for a legacy single-body document.
    pub title: Option<&'a str>,
    /// Depth in the tab tree; `0` for a top-level tab.
    pub nesting_level: i64,
    /// The tab's body, when it has one.
    pub body: Option<&'a Body>,
    headers_map: Option<&'a HashMap<String, Header>>,
    footers_map: Option<&'a HashMap<String, Footer>>,
    footnotes_map: Option<&'a HashMap<String, Footnote>>,
    /// Named ranges belonging to this tab, including legacy responses.
    pub named_ranges: &'a HashMap<String, NamedRanges>,
}

impl<'a> ResolvedTab<'a> {
    /// The tab's page headers, resolved and sorted by `segment_id` — map
    /// iteration order is not deterministic.
    #[must_use]
    pub fn headers(&self) -> Vec<ResolvedSegment<'a>> {
        self.headers_map
            .map_or_else(Vec::new, |m| resolve_segments(m, |h| h.content.as_slice()))
    }
    /// The tab's page footers, likewise resolved and sorted.
    #[must_use]
    pub fn footers(&self) -> Vec<ResolvedSegment<'a>> {
        self.footers_map
            .map_or_else(Vec::new, |m| resolve_segments(m, |f| f.content.as_slice()))
    }
    /// The tab's footnotes, likewise resolved and sorted.
    #[must_use]
    pub fn footnotes(&self) -> Vec<ResolvedSegment<'a>> {
        self.footnotes_map
            .map_or_else(Vec::new, |m| resolve_segments(m, |f| f.content.as_slice()))
    }
}

/// Resolves one segment map into sorted [`ResolvedSegment`]s.
fn resolve_segments<'a, T>(
    map: &'a HashMap<String, T>,
    content: impl Fn(&'a T) -> &'a [StructuralElement],
) -> Vec<ResolvedSegment<'a>> {
    let mut out: Vec<ResolvedSegment<'a>> = map
        .iter()
        .map(|(id, seg)| ResolvedSegment {
            segment_id: id.as_str(),
            content: content(seg),
        })
        .collect();
    out.sort_by_key(|s| s.segment_id);
    out
}

impl Document {
    /// The document title, or `""` when absent.
    #[must_use]
    pub fn title(&self) -> &str {
        self.title.as_deref().unwrap_or("")
    }

    /// Every tab's content, depth-first through `childTabs`, falling back to
    /// the legacy top-level [`Self::body`] (and its sibling
    /// `headers`/`footers`/`footnotes` maps) as a single anonymous tab.
    ///
    /// The fallback is what makes the `tabs`-xor-`body` split invisible to
    /// callers. A document fetched without `includeTabsContent` yields
    /// exactly one `ResolvedTab` whose `tab_id` and `title` are `None` —
    /// unless the document has neither body content nor any segment, in
    /// which case there is nothing to synthesise a tab for.
    #[must_use]
    pub fn resolved_tabs(&self) -> Vec<ResolvedTab<'_>> {
        if self.tabs.is_empty() {
            if self.body.is_none()
                && self.headers.is_empty()
                && self.footers.is_empty()
                && self.footnotes.is_empty()
            {
                return Vec::new();
            }
            return vec![ResolvedTab {
                tab_id: None,
                title: None,
                nesting_level: 0,
                body: self.body.as_ref(),
                headers_map: Some(&self.headers),
                footers_map: Some(&self.footers),
                footnotes_map: Some(&self.footnotes),
                named_ranges: &self.named_ranges,
            }];
        }
        let mut out = Vec::new();
        for tab in &self.tabs {
            push_tab(tab, 0, &mut out);
        }
        out
    }
}

/// Walks one tab and its `childTabs` depth-first, parent before children.
fn push_tab<'a>(tab: &'a Tab, depth: i64, out: &mut Vec<ResolvedTab<'a>>) {
    let props = tab.tab_properties.as_ref();
    let doc_tab = tab.document_tab.as_ref();
    out.push(ResolvedTab {
        tab_id: props.and_then(|p| p.tab_id.as_deref()),
        title: props.and_then(|p| p.title.as_deref()),
        // Prefer the server's own nesting level when it sent one; fall back
        // to the walk depth, which agrees with it for every well-formed
        // response and keeps a truncated one self-consistent.
        nesting_level: props.and_then(|p| p.nesting_level).unwrap_or(depth),
        body: doc_tab.and_then(|dt| dt.body.as_ref()),
        headers_map: doc_tab.map(|dt| &dt.headers),
        footers_map: doc_tab.map(|dt| &dt.footers),
        footnotes_map: doc_tab.map(|dt| &dt.footnotes),
        named_ranges: match doc_tab {
            Some(dt) => &dt.named_ranges,
            None => empty_named_ranges(),
        },
    });
    for child in &tab.child_tabs {
        push_tab(child, depth + 1, out);
    }
}

fn empty_named_ranges() -> &'static HashMap<String, NamedRanges> {
    static EMPTY: std::sync::LazyLock<HashMap<String, NamedRanges>> =
        std::sync::LazyLock::new(HashMap::new);
    &EMPTY
}

/// One tab of a document.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Tab {
    /// This tab's identity and position.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "tabProperties"
    )]
    pub tab_properties: Option<TabProperties>,
    /// The tab's content, when it is a document tab.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "documentTab"
    )]
    pub document_tab: Option<DocumentTab>,
    /// Nested tabs, recursively.
    #[serde(default, skip_serializing_if = "Vec::is_empty", rename = "childTabs")]
    pub child_tabs: Vec<Self>,
}

/// A tab's identity and position within the tab tree.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct TabProperties {
    /// The tab's id — a required component of every Docs edit address in a
    /// multi-tab document.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "tabId")]
    pub tab_id: Option<String>,
    /// The tab's display title.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Zero-based position among its siblings.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub index: Option<i64>,
    /// Depth in the tab tree; `0` for a top-level tab.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "nestingLevel"
    )]
    pub nesting_level: Option<i64>,
    /// The parent tab's id, absent for a top-level tab.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "parentTabId"
    )]
    pub parent_tab_id: Option<String>,
}

/// The document-flavoured content of a tab.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct DocumentTab {
    /// The tab's body.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<Body>,
    /// Named ranges scoped to this tab.
    #[serde(
        default,
        skip_serializing_if = "HashMap::is_empty",
        rename = "namedRanges"
    )]
    pub named_ranges: HashMap<String, NamedRanges>,
    /// Page headers, keyed by `segmentId`.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub headers: HashMap<String, Header>,
    /// Page footers, keyed by `segmentId`.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub footers: HashMap<String, Footer>,
    /// Footnotes, keyed by `segmentId`.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub footnotes: HashMap<String, Footnote>,
}

/// A document body — the main index segment.
///
/// Headers, footers and footnotes live in their own segments, addressed by
/// `segmentId`. They are modelled as sibling maps on [`Document`] and
/// [`DocumentTab`] ([`Header`], [`Footer`], [`Footnote`]) rather than folded
/// into this type, and normalised onto [`ResolvedTab::headers`],
/// `.footers` and `.footnotes` by [`Document::resolved_tabs`] the same way
/// `body` is normalised here.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Body {
    /// The body's structural elements, in index order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub content: Vec<StructuralElement>,
}

/// One page header — a segment addressed by the map key it is stored under.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Header {
    /// The header's structural elements, in index order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub content: Vec<StructuralElement>,
}

/// One page footer — same shape as [`Header`]; Google models these as
/// distinct message types even though the field is identical, so this
/// mirrors that instead of aliasing.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Footer {
    /// The footer's structural elements, in index order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub content: Vec<StructuralElement>,
}

/// One footnote body — same shape again. The footnote's own id is the map
/// key it is stored under, not a field on this struct.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Footnote {
    /// The footnote's structural elements, in index order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub content: Vec<StructuralElement>,
}

/// One structural element: exactly one of the variant fields is present, and
/// which one is the discriminator.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct StructuralElement {
    /// Inclusive start, in UTF-16 code units. Absent means `0`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "startIndex"
    )]
    pub start_index: Option<i64>,
    /// Exclusive end, in UTF-16 code units.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "endIndex")]
    pub end_index: Option<i64>,
    /// A paragraph.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub paragraph: Option<Paragraph>,
    /// A table.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub table: Option<Table>,
    /// A table of contents.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "tableOfContents"
    )]
    pub table_of_contents: Option<TableOfContents>,
    /// A section break. Carries nothing this crate reads, so it is kept as
    /// raw JSON purely as a present/absent discriminator.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "sectionBreak"
    )]
    pub section_break: Option<serde_json::Value>,
}

impl StructuralElement {
    /// Inclusive start index, treating an absent field as `0`.
    #[must_use]
    pub fn start_index(&self) -> i64 {
        self.start_index.unwrap_or(0)
    }

    /// Exclusive end index, treating an absent field as `0`.
    #[must_use]
    pub fn end_index(&self) -> i64 {
        self.end_index.unwrap_or(0)
    }
}

/// A paragraph and its inline elements.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Paragraph {
    /// The paragraph's inline elements, in index order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub elements: Vec<ParagraphElement>,
    /// The paragraph's style, notably its `namedStyleType`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "paragraphStyle"
    )]
    pub paragraph_style: Option<ParagraphStyle>,
    /// Present when the paragraph is a list item.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bullet: Option<Bullet>,
}

impl Paragraph {
    /// The paragraph's text, concatenating every `textRun` in order.
    ///
    /// Concatenation is not optional: a paragraph with one bolded word is
    /// three text runs, and reading only the first silently truncates it.
    ///
    /// The trailing `\n` every Docs paragraph carries is **kept** here —
    /// stripping is the renderer's job, because the newline occupies one
    /// index unit and dropping it from the text without dropping it from
    /// `end_index` is what makes the two disagree.
    #[must_use]
    pub fn text(&self) -> String {
        self.elements
            .iter()
            .filter_map(|el| el.text_run.as_ref())
            .map(|run| run.content.as_str())
            .collect()
    }

    /// The paragraph's `namedStyleType` (`HEADING_1`, `NORMAL_TEXT`, …).
    #[must_use]
    pub fn named_style_type(&self) -> Option<&str> {
        self.paragraph_style
            .as_ref()
            .and_then(|style| style.named_style_type.as_deref())
    }
}

/// A paragraph's style.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ParagraphStyle {
    /// `HEADING_1`, `TITLE`, `NORMAL_TEXT`, …
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "namedStyleType"
    )]
    pub named_style_type: Option<String>,
    /// The heading's id, when this paragraph is a heading.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "headingId")]
    pub heading_id: Option<String>,
}

/// A list-item marker.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Bullet {
    /// The list this item belongs to.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "listId")]
    pub list_id: Option<String>,
    /// Nesting depth within that list.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "nestingLevel"
    )]
    pub nesting_level: Option<i64>,
}

/// One inline element of a paragraph.
///
/// Only `textRun` carries text this crate reads. The rest are modelled as
/// present/absent so an element that consumes index space without
/// contributing text — an inline image, a page break — is not mistaken for
/// nothing at all.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ParagraphElement {
    /// Inclusive start, in UTF-16 code units. Absent means `0`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "startIndex"
    )]
    pub start_index: Option<i64>,
    /// Exclusive end, in UTF-16 code units.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "endIndex")]
    pub end_index: Option<i64>,
    /// A run of text with uniform styling.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "textRun")]
    pub text_run: Option<TextRun>,
    /// An inline image or drawing. Consumes one index unit, contributes no
    /// text — so its paragraph's text is shorter than its index span, which
    /// is correct and must not be "fixed".
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "inlineObjectElement"
    )]
    pub inline_object_element: Option<InlineObjectElement>,
    /// A page break.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "pageBreak")]
    pub page_break: Option<serde_json::Value>,
    /// A column break.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "columnBreak"
    )]
    pub column_break: Option<serde_json::Value>,
    /// A horizontal rule.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "horizontalRule"
    )]
    pub horizontal_rule: Option<serde_json::Value>,
    /// A footnote reference.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "footnoteReference"
    )]
    pub footnote_reference: Option<serde_json::Value>,
    /// Auto-text such as a page number.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "autoText")]
    pub auto_text: Option<serde_json::Value>,
    /// An equation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub equation: Option<serde_json::Value>,
    /// A person mention.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub person: Option<serde_json::Value>,
    /// A rich link chip.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "richLink")]
    pub rich_link: Option<serde_json::Value>,
}

/// A run of text with uniform styling.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct TextRun {
    /// Pending insertions: unsafe to use as an edit anchor.
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        rename = "suggestedInsertionIds"
    )]
    pub suggested_insertion_ids: Vec<String>,
    /// Pending deletions: unsafe to include in an edit range.
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        rename = "suggestedDeletionIds"
    )]
    pub suggested_deletion_ids: Vec<String>,
    /// The run's text, including any trailing newline.
    #[serde(default)]
    pub content: String,
}

/// A reference to an inline object.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct InlineObjectElement {
    /// The object's id, resolvable against the document's `inlineObjects`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "inlineObjectId"
    )]
    pub inline_object_id: Option<String>,
}

/// A table.
#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
pub struct Table {
    /// Row count.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rows: Option<i64>,
    /// Column count.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub columns: Option<i64>,
    /// The table's rows.
    #[serde(default, skip_serializing_if = "Vec::is_empty", rename = "tableRows")]
    pub table_rows: Vec<TableRow>,
    /// Whether the original table contains any pending suggestion, including
    /// unmodelled nested fields. Captured before narrowing the read model;
    /// no duplicate document prose is retained or emitted.
    #[serde(skip)]
    pub has_pending_suggestions: bool,
}

pub(super) fn has_suggestions(value: &serde_json::Value) -> bool {
    match value {
        serde_json::Value::Object(fields) => fields.iter().any(|(key, value)| {
            (key.starts_with("suggested")
                && match value {
                    serde_json::Value::Array(v) => !v.is_empty(),
                    serde_json::Value::Object(v) => !v.is_empty(),
                    serde_json::Value::Null => false,
                    _ => true,
                })
                || has_suggestions(value)
        }),
        serde_json::Value::Array(values) => values.iter().any(has_suggestions),
        _ => false,
    }
}

impl<'de> Deserialize<'de> for Table {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        struct WireTable {
            #[serde(default)]
            rows: Option<i64>,
            #[serde(default)]
            columns: Option<i64>,
            #[serde(default, rename = "tableRows")]
            table_rows: Vec<TableRow>,
        }
        let raw = serde_json::Value::deserialize(deserializer)?;
        let has_pending_suggestions = has_suggestions(&raw);
        let wire: WireTable = serde_json::from_value(raw).map_err(serde::de::Error::custom)?;
        Ok(Self {
            rows: wire.rows,
            columns: wire.columns,
            table_rows: wire.table_rows,
            has_pending_suggestions,
        })
    }
}

/// One row of a table.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct TableRow {
    /// Inclusive start, in UTF-16 code units.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "startIndex"
    )]
    pub start_index: Option<i64>,
    /// Exclusive end, in UTF-16 code units.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "endIndex")]
    pub end_index: Option<i64>,
    /// The row's cells.
    #[serde(default, skip_serializing_if = "Vec::is_empty", rename = "tableCells")]
    pub table_cells: Vec<TableCell>,
}

/// One cell of a table row.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct TableCell {
    /// Inclusive start, in UTF-16 code units.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "startIndex"
    )]
    pub start_index: Option<i64>,
    /// Exclusive end, in UTF-16 code units.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "endIndex")]
    pub end_index: Option<i64>,
    /// The cell's own structural elements — where the recursion lives, since
    /// a cell may contain another table.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub content: Vec<StructuralElement>,
    /// Read-only spans used to reject merged-cell structural edits.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "tableCellStyle"
    )]
    pub table_cell_style: Option<TableCellStyle>,
}

/// Read-only cell spans; other formatting remains outside the edit model.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct TableCellStyle {
    /// Number of rows spanned by this cell.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "rowSpan")]
    pub row_span: Option<i64>,
    /// Number of columns spanned by this cell.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "columnSpan"
    )]
    pub column_span: Option<i64>,
}

/// A table of contents.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct TableOfContents {
    /// The generated entries, as structural elements.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub content: Vec<StructuralElement>,
}

/// Every named range sharing one name.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct NamedRanges {
    /// The shared name.
    #[serde(default)]
    pub name: String,
    /// The ranges carrying it.
    #[serde(default, skip_serializing_if = "Vec::is_empty", rename = "namedRanges")]
    pub named_ranges: Vec<NamedRange>,
}

/// One named range.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct NamedRange {
    /// The range's id.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "namedRangeId"
    )]
    pub named_range_id: Option<String>,
    /// The range's name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// The index spans it covers.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ranges: Vec<Range>,
}

/// An index span within one segment of one tab.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Range {
    /// The segment; empty/absent means the document body.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "segmentId")]
    pub segment_id: Option<String>,
    /// The tab; empty/absent means the first tab.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "tabId")]
    pub tab_id: Option<String>,
    /// Inclusive start, in UTF-16 code units.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "startIndex"
    )]
    pub start_index: Option<i64>,
    /// Exclusive end, in UTF-16 code units.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "endIndex")]
    pub end_index: Option<i64>,
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    fn parse(json: serde_json::Value) -> Document {
        serde_json::from_value(json).unwrap()
    }

    /// The single highest-value test in this file. Docs serialises proto3
    /// JSON, which omits zero-valued integers, so the first element of every
    /// real document has no `startIndex` key. Reading it as anything but `0`
    /// shifts every reported index.
    #[test]
    fn a_missing_start_index_means_zero() {
        let doc = parse(serde_json::json!({
            "body": {"content": [{"endIndex": 1, "sectionBreak": {}}]},
        }));
        let el = &doc.body.as_ref().unwrap().content[0];
        assert_eq!(el.start_index, None, "the key really is absent");
        assert_eq!(el.start_index(), 0, "and the accessor reads it as zero");
        assert_eq!(el.end_index(), 1);
    }

    #[test]
    fn a_present_but_empty_section_break_is_still_recognised() {
        let doc = parse(serde_json::json!({
            "body": {"content": [{"sectionBreak": {}}]},
        }));
        let el = &doc.body.as_ref().unwrap().content[0];
        assert!(el.section_break.is_some(), "present-and-empty is Some");
        assert!(el.paragraph.is_none());
    }

    #[test]
    fn an_absent_section_break_is_none() {
        let doc = parse(serde_json::json!({
            "body": {"content": [{"paragraph": {"elements": []}}]},
        }));
        assert!(doc.body.as_ref().unwrap().content[0]
            .section_break
            .is_none());
    }

    #[test]
    fn text_run_content_defaults_to_empty() {
        let run: TextRun = serde_json::from_value(serde_json::json!({})).unwrap();
        assert_eq!(run.content, "");
    }

    /// A paragraph with a bolded word is several text runs. Reading only the
    /// first silently truncates it.
    #[test]
    fn paragraph_text_joins_every_text_run_in_order() {
        let para: Paragraph = serde_json::from_value(serde_json::json!({
            "elements": [
                {"textRun": {"content": "Hello "}},
                {"textRun": {"content": "bold"}},
                {"textRun": {"content": " world\n"}},
            ],
        }))
        .unwrap();
        assert_eq!(para.text(), "Hello bold world\n");
    }

    /// An inline image consumes index space but contributes no text, so a
    /// paragraph's text is shorter than its index span. That is correct.
    #[test]
    fn paragraph_text_skips_a_non_text_element() {
        let para: Paragraph = serde_json::from_value(serde_json::json!({
            "elements": [
                {"textRun": {"content": "a"}},
                {"inlineObjectElement": {"inlineObjectId": "kix.1"}},
                {"textRun": {"content": "b\n"}},
            ],
        }))
        .unwrap();
        assert_eq!(para.text(), "ab\n");
        assert!(para.elements[1].inline_object_element.is_some());
    }

    #[test]
    fn resolved_tabs_synthesises_one_anonymous_tab_from_a_legacy_body() {
        let doc = parse(serde_json::json!({
            "title": "Legacy",
            "body": {"content": [{"endIndex": 1, "sectionBreak": {}}]},
        }));
        let tabs = doc.resolved_tabs();
        assert_eq!(tabs.len(), 1);
        assert_eq!(tabs[0].tab_id, None);
        assert_eq!(tabs[0].title, None);
        assert_eq!(tabs[0].nesting_level, 0);
        assert!(tabs[0].body.is_some());
    }

    #[test]
    fn resolved_tabs_of_a_document_with_neither_body_nor_tabs_is_empty() {
        assert!(parse(serde_json::json!({"title": "Empty"}))
            .resolved_tabs()
            .is_empty());
    }

    /// The legacy single-body shape carries its segments at the top level.
    #[test]
    fn resolved_tabs_resolves_top_level_segments_for_a_legacy_body() {
        let doc = parse(serde_json::json!({
            "body": {"content": []},
            "headers": {"h1": {"content": [{"endIndex": 1, "sectionBreak": {}}]}},
            "footers": {"f1": {"content": []}},
            "footnotes": {"fn1": {"content": []}},
        }));
        let tabs = doc.resolved_tabs();
        assert_eq!(tabs[0].headers().len(), 1);
        assert_eq!(tabs[0].headers()[0].segment_id, "h1");
        assert_eq!(tabs[0].footers().len(), 1);
        assert_eq!(tabs[0].footnotes().len(), 1);
    }

    /// A tab with none of these maps yields empty `Vec`s, not an error.
    #[test]
    fn resolved_tabs_has_empty_segments_when_the_document_has_none() {
        let doc = parse(serde_json::json!({"body": {"content": []}}));
        let tabs = doc.resolved_tabs();
        assert!(tabs[0].headers().is_empty());
        assert!(tabs[0].footers().is_empty());
        assert!(tabs[0].footnotes().is_empty());
    }

    /// A document with no `tabs` and no `body` but a populated segment map
    /// still yields a tab to hang that segment off, rather than silently
    /// discarding fetched content because the legacy fallback keyed only on
    /// `body`'s presence.
    #[test]
    fn resolved_tabs_synthesises_a_tab_for_segments_with_no_body() {
        let doc = parse(serde_json::json!({
            "headers": {"h1": {"content": [{"endIndex": 1, "sectionBreak": {}}]}},
        }));
        let tabs = doc.resolved_tabs();
        assert_eq!(tabs.len(), 1);
        assert!(tabs[0].body.is_none());
        assert_eq!(tabs[0].headers().len(), 1);
    }

    /// Segments are tab-scoped in the `tabs` shape, and resolved sorted by
    /// `segment_id` since map iteration order is not guaranteed.
    #[test]
    fn resolved_tabs_resolves_tab_scoped_segments_sorted_by_segment_id() {
        let doc = parse(serde_json::json!({
            "tabs": [{
                "tabProperties": {"tabId": "t.0"},
                "documentTab": {
                    "body": {"content": []},
                    "headers": {
                        "h2": {"content": []},
                        "h1": {"content": [{"endIndex": 1, "sectionBreak": {}}]},
                    },
                },
            }],
        }));
        let tabs = doc.resolved_tabs();
        let headers = tabs[0].headers();
        let ids: Vec<_> = headers.iter().map(|s| s.segment_id).collect();
        assert_eq!(ids, vec!["h1", "h2"]);
        assert_eq!(headers[0].content.len(), 1);
    }

    #[test]
    fn resolved_tabs_walks_child_tabs_depth_first_parent_before_children() {
        let doc = parse(serde_json::json!({
            "tabs": [
                {
                    "tabProperties": {"tabId": "t.0", "title": "One", "nestingLevel": 0},
                    "documentTab": {"body": {"content": []}},
                    "childTabs": [{
                        "tabProperties": {"tabId": "t.0.a", "title": "One A", "nestingLevel": 1},
                        "documentTab": {"body": {"content": []}},
                    }],
                },
                {
                    "tabProperties": {"tabId": "t.1", "title": "Two", "nestingLevel": 0},
                    "documentTab": {"body": {"content": []}},
                },
            ],
        }));
        let ids: Vec<_> = doc.resolved_tabs().iter().map(|t| t.tab_id).collect();
        assert_eq!(ids, vec![Some("t.0"), Some("t.0.a"), Some("t.1")]);
        assert_eq!(doc.resolved_tabs()[1].nesting_level, 1);
    }

    /// A response that omits `nestingLevel` still gets a self-consistent
    /// depth from the walk, rather than collapsing every tab to level 0.
    #[test]
    fn resolved_tabs_falls_back_to_walk_depth_when_nesting_level_is_absent() {
        let doc = parse(serde_json::json!({
            "tabs": [{
                "tabProperties": {"tabId": "t.0"},
                "childTabs": [{"tabProperties": {"tabId": "t.0.a"}}],
            }],
        }));
        let tabs = doc.resolved_tabs();
        assert_eq!(tabs[0].nesting_level, 0);
        assert_eq!(tabs[1].nesting_level, 1);
    }

    /// `tabs` wins over `body`; they never both contribute.
    #[test]
    fn tabs_take_precedence_over_a_legacy_body() {
        let doc = parse(serde_json::json!({
            "body": {"content": [{"paragraph": {"elements": [{"textRun": {"content": "legacy\n"}}]}}]},
            "tabs": [{
                "tabProperties": {"tabId": "t.0"},
                "documentTab": {"body": {"content": []}},
            }],
        }));
        let tabs = doc.resolved_tabs();
        assert_eq!(tabs.len(), 1);
        assert_eq!(tabs[0].tab_id, Some("t.0"));
    }

    #[test]
    fn nested_tables_parse_recursively() {
        let doc = parse(serde_json::json!({
            "body": {"content": [{
                "startIndex": 1, "endIndex": 40,
                "table": {
                    "rows": 1, "columns": 1,
                    "tableRows": [{"tableCells": [{"content": [{
                        "table": {"rows": 1, "columns": 1, "tableRows": [{"tableCells": [{
                            "content": [{"paragraph": {"elements": [
                                {"textRun": {"content": "deep\n"}}]}}],
                        }]}]},
                    }]}]}],
                },
            }]},
        }));
        let outer = doc.body.as_ref().unwrap().content[0]
            .table
            .as_ref()
            .unwrap();
        let inner = outer.table_rows[0].table_cells[0].content[0]
            .table
            .as_ref()
            .unwrap();
        let para = inner.table_rows[0].table_cells[0].content[0]
            .paragraph
            .as_ref()
            .unwrap();
        assert_eq!(para.text(), "deep\n");
    }

    #[test]
    fn named_ranges_parse_as_a_map_keyed_by_name() {
        let doc = parse(serde_json::json!({
            "namedRanges": {
                "intro": {
                    "name": "intro",
                    "namedRanges": [{
                        "namedRangeId": "nr.1", "name": "intro",
                        "ranges": [{"startIndex": 1, "endIndex": 20}],
                    }],
                },
            },
        }));
        let group = doc.named_ranges.get("intro").unwrap();
        assert_eq!(group.name, "intro");
        assert_eq!(group.named_ranges[0].ranges[0].end_index, Some(20));
    }

    /// A `revisionId` is present only for callers with edit access; a
    /// read-only caller sees `None`, and the write path refuses rather than
    /// falling back to an unleased write.
    #[test]
    fn a_document_without_edit_access_has_no_revision_id() {
        assert_eq!(parse(serde_json::json!({"title": "T"})).revision_id, None);
        let with = parse(serde_json::json!({"revisionId": "rev-1"}));
        assert_eq!(with.revision_id.as_deref(), Some("rev-1"));
    }

    #[test]
    fn document_tolerates_unmodelled_fields() {
        let doc = parse(serde_json::json!({
            "documentId": "d1",
            "title": "T",
            "documentStyle": {"marginTop": {"magnitude": 72.0}},
            "lists": {"kix.l1": {"listProperties": {}}},
            "inlineObjects": {"kix.i1": {}},
            "suggestionsViewMode": "PREVIEW_SUGGESTIONS_ACCEPTED",
            "body": {"content": [{
                "endIndex": 5,
                "paragraph": {
                    "elements": [{"textRun": {
                        "content": "hi\n",
                        "textStyle": {"bold": true},
                        "suggestedInsertionIds": ["s1"],
                    }}],
                    "paragraphStyle": {"namedStyleType": "NORMAL_TEXT", "direction": "LEFT_TO_RIGHT"},
                },
            }]},
        }));
        assert_eq!(doc.document_id.as_deref(), Some("d1"));
        let para = doc.body.as_ref().unwrap().content[0]
            .paragraph
            .as_ref()
            .unwrap();
        assert_eq!(para.text(), "hi\n");
        assert_eq!(para.named_style_type(), Some("NORMAL_TEXT"));
    }

    /// A `suggested*` key counts only when it carries something: an empty
    /// list or map, or an explicit null, is Docs' way of saying "none".
    /// Any scalar value there is unexpected, so it fails closed as a
    /// suggestion; keys without the prefix never count.
    #[test]
    fn has_suggestions_counts_only_non_empty_suggested_fields_at_any_depth() {
        for (value, expected) in [
            (serde_json::json!({"suggestedInsertionIds": ["s"]}), true),
            (
                serde_json::json!({"suggestedTextStyleChanges": {"s": {}}}),
                true,
            ),
            (serde_json::json!({"suggestedBold": true}), true),
            (serde_json::json!({"suggestedNote": "text"}), true),
            (serde_json::json!({"suggestedCount": 0}), true),
            (serde_json::json!({"suggestedInsertionIds": []}), false),
            (serde_json::json!({"suggestedTextStyleChanges": {}}), false),
            (serde_json::json!({"suggestedNote": null}), false),
            (serde_json::json!({"insertionIds": ["s"]}), false),
            (serde_json::json!({"notSuggested": true}), false),
            (
                serde_json::json!({"a": [{"b": {"suggestedDeletionIds": ["s"]}}]}),
                true,
            ),
            (
                serde_json::json!({"a": [{"b": {"suggestedNote": null}}]}),
                false,
            ),
            (serde_json::json!("suggestedInsertionIds"), false),
            (serde_json::json!(null), false),
        ] {
            assert_eq!(has_suggestions(&value), expected, "{value}");
        }
    }

    /// The flag is captured from the raw table, including fields the read
    /// model does not carry, and never leaks back onto the wire.
    #[test]
    fn a_table_remembers_unmodelled_suggestions_without_serialising_them() {
        let clean: Table = serde_json::from_value(serde_json::json!({
            "rows": 1,
            "columns": 1,
            "tableRows": [{"suggestedInsertionIds": []}],
        }))
        .unwrap();
        assert!(!clean.has_pending_suggestions);
        let suggested: Table = serde_json::from_value(serde_json::json!({
            "rows": 1,
            "columns": 1,
            "tableRows": [{"tableCells": [{"tableCellStyle": {"suggestedTableCellStyleChanges": {"s": {}}}}]}],
        }))
        .unwrap();
        assert!(suggested.has_pending_suggestions);
        let wire = serde_json::to_value(&suggested).unwrap();
        assert!(!wire.to_string().contains("suggested"), "{wire}");
        assert!(wire.get("has_pending_suggestions").is_none());
    }

    #[test]
    fn title_defaults_to_empty() {
        assert_eq!(parse(serde_json::json!({})).title(), "");
        assert_eq!(parse(serde_json::json!({"title": "T"})).title(), "T");
    }
}