jubarte-edit 0.20.0

The edit product of the jubarte engine: edit plans as tracked changes, text diff views, capabilities and staged publication
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
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0

//! `resolve_revisions` settlement: selecting, accepting and rejecting
//! tracked changes before a plan runs, and the comments it would remove;
//! the stories the settled document is read from (`Loaded`,
//! `load_stories`); and the mapping of an admission refusal to an edit
//! error (`open_error`).

use super::*;

/// An unopenable source: admission refusals keep their own code
/// (`INPUT_LIMIT`, …), anything else is `INVALID_DOCUMENT`.
pub(super) fn open_error(error: crate::inspect::InspectError) -> EditError {
    match error {
        crate::inspect::InspectError::Admission(refused) => {
            err(refused.code(), None, refused.message)
        }
        other => err("INVALID_DOCUMENT", None, other.to_string()),
    }
}

/// A [`ChangeError`] of a `resolve_revisions` selection as the plan's error.
pub(super) fn selection_error(e: ChangeError, syntax: PlanSyntax, verb: &str) -> EditError {
    match e {
        ChangeError::UnknownChange(id) => err(
            "UNKNOWN_CHANGE",
            None,
            syntax.selection_message(format_args!("no tracked change {id}")),
        ),
        ChangeError::InvalidId(m) => err("INVALID_PLAN", None, format!("resolve_revisions: {m}")),
        ambiguous @ ChangeError::Ambiguous { .. } => err(
            "AMBIGUOUS_CHANGE",
            None,
            syntax.selection_message(ambiguous),
        ),
        part @ ChangeError::PartOfChange { .. } => err(
            "INCOMPLETE_CHANGE",
            None,
            syntax.incomplete_change(&part, verb),
        ),
        ChangeError::Package(m) => err("INVALID_DOCUMENT", None, m),
        exposed @ ChangeError::ExposedFinalMark { .. } => {
            err("EXPOSED_FINAL_MARK", None, exposed.to_string())
        }
    }
}

/// The ids of `listed` a `resolve_revisions` side selects, in document
/// order, a move's other side included.
pub(super) fn selected_ids(
    listed: &[Change],
    filter: Option<&ChangeFilter>,
    syntax: PlanSyntax,
) -> Result<Vec<String>, EditError> {
    let Some(filter) = filter else {
        return Ok(Vec::new());
    };
    let selection_error = |e| selection_error(e, syntax, "");
    let filter = &filter.normalized().map_err(selection_error)?;
    filter.check(listed).map_err(selection_error)?;
    let hit: Vec<&Change> = listed.iter().filter(|c| filter.matches(c)).collect();
    Ok(listed
        .iter()
        .filter(|c| {
            hit.iter()
                .any(|h| h.id == c.id || h.move_name.is_some() && h.move_name == c.move_name)
        })
        .map(|c| c.id.clone())
        .collect())
}

/// The ids `filter` itself selects in `listed`, before [`selected_ids`]
/// adds each move's other side: the ones a receipt names as resolved.
fn named_ids(listed: &[Change], filter: Option<&ChangeFilter>) -> Vec<String> {
    let Some(filter) = filter.and_then(|f| f.normalized().ok()) else {
        return Vec::new();
    };
    listed
        .iter()
        .filter(|c| filter.matches(c))
        .map(|c| c.id.clone())
        .collect()
}

/// Accept, then reject, the changes `resolve_revisions` selects: the new
/// source (`None` when it selects nothing) and what was resolved.
pub(super) fn resolve_selected(
    source: &[u8],
    selection: Option<&ResolveRevisions>,
    policy: RemovedAnchorComments,
    syntax: PlanSyntax,
) -> Result<(Option<Vec<u8>>, ResolvedRevisions, AnchorChanges), EditError> {
    let mut comments = AnchorChanges::default();
    let mut resolved = ResolvedRevisions::default();
    let Some(selection) = selection else {
        return Ok((None, resolved, comments));
    };
    let change_err = |e| selection_error(e, syntax, "");
    // Each side names whole changes, checked on the source: an accept can
    // join what is left (#1261).
    for (side, verb) in [
        (selection.accept.as_ref(), "accept"),
        (selection.reject.as_ref(), "reject"),
    ] {
        if let Some(side) = side {
            crate::changes::check_whole_changes(source, side)
                .map_err(|e| selection_error(e, syntax, verb))?;
        }
    }
    let listed = crate::changes::list_changes(source).map_err(change_err)?;
    let accept = selected_ids(&listed, selection.accept.as_ref(), syntax)?;
    // A visible reject settles nothing: it is lowered to operations.
    let reject = if selection.reject_visible {
        Vec::new()
    } else {
        selected_ids(&listed, selection.reject.as_ref(), syntax)?
    };
    if let Some(both) = accept.iter().find(|id| reject.contains(id)) {
        return Err(err(
            "REVISION_CONFLICT",
            None,
            format!("resolve_revisions selects {both} to accept and to reject"),
        ));
    }
    if accept.is_empty() && reject.is_empty() {
        return Ok((None, resolved, comments));
    }
    let mut bytes = source.to_vec();
    if !accept.is_empty() {
        let (document, removed, kept) = crate::changes::resolve_for_edit(
            &bytes,
            &ChangeFilter::ids(accept.clone()),
            crate::revision_processor::Resolution::Accept,
            policy == RemovedAnchorComments::Keep,
        )
        .map_err(|e| selection_error(e, syntax, "accept"))?;
        comments.extend(
            removed,
            kept,
            crate::revision_processor::Resolution::Accept,
            Some(&named_ids(&listed, selection.accept.as_ref())),
        );
        bytes = document;
        resolved.accepted = accept;
    }
    // A change the accepted ones took along is gone, not rejected.
    let left = crate::changes::list_changes(&bytes).map_err(change_err)?;
    let reject: Vec<String> = reject
        .into_iter()
        .filter(|id| left.iter().any(|c| &c.id == id))
        .collect();
    if !reject.is_empty() {
        let (document, removed, kept) = crate::changes::resolve_for_edit(
            &bytes,
            &ChangeFilter::ids(reject.clone()),
            crate::revision_processor::Resolution::Reject,
            policy == RemovedAnchorComments::Keep,
        )
        .map_err(|e| selection_error(e, syntax, "reject"))?;
        comments.extend(
            removed,
            kept,
            crate::revision_processor::Resolution::Reject,
            Some(&named_ids(&listed, selection.reject.as_ref())),
        );
        bytes = document;
        resolved.rejected = reject;
    }
    Ok((Some(bytes), resolved, comments))
}

/// The document a plan edits once `resolve_revisions` and
/// `existing_revisions` have settled the tracked changes they select.
pub(super) struct Settled {
    /// The bytes the plan edits and the redline compares against.
    pub(super) base: Vec<u8>,
    pub(super) opened: Opened,
    pub(super) resolved_revisions: ResolvedRevisions,
    pub(super) comment_changes: AnchorChanges,
    /// Settling rewrote the document: paragraphs may have merged or gone.
    pub(super) changed: bool,
}

/// Whether `author` is the plan's author. A missing or empty author is not.
pub(super) fn owns_change(author: Option<&str>, actor: &str) -> bool {
    author.is_some_and(|name| !name.is_empty() && name == actor)
}

/// One sentence for a change the guard will not accept or reject.
pub(super) fn change_not_yours(change: &Change) -> String {
    let whose = match change.author.as_deref() {
        Some(name) if !name.is_empty() => format!("{} is by {name:?}", change.id),
        _ => format!("{} names no author", change.id),
    };
    let answer = match change.kind {
        ChangeKind::Deletion => {
            format!(
                "answer it visibly (-p {} --restore), or comment on it",
                change.id
            )
        }
        ChangeKind::Insertion => {
            format!("strike it (-p {} --strike), or comment on it", change.id)
        }
        _ => "comment on it (accepting or rejecting would erase their change)".to_string(),
    };
    format!("{whose}; {answer}")
}

/// `authors` in document order, then a nameless change, as one English list.
pub(super) fn join_authors(authors: &[String], nameless: bool) -> String {
    let mut parts: Vec<String> = authors.iter().map(|name| format!("{name:?}")).collect();
    if nameless {
        parts.push("one that names no author".to_string());
    }
    match parts.as_slice() {
        [] => String::new(),
        [one] => one.clone(),
        [first, second] => format!("{first} and {second}"),
        _ => {
            let (last, rest) = parts.split_last().expect("at least three");
            format!("{} and {last}", rest.join(", "))
        }
    }
}

/// Whether settling `change` this way removes its content, and with it
/// every revision and comment anchor that content holds. Accepting a
/// deletion or a move-from, or rejecting an insertion or a move-to, does.
/// Accepting an insertion keeps the text, so a revision nested in it stays.
pub(super) fn removes_content(change: &Change, accept: bool) -> bool {
    matches!(
        (accept, change.kind, change.move_side),
        (true, ChangeKind::Deletion, _)
            | (false, ChangeKind::Insertion, _)
            | (true, ChangeKind::Move, Some(MoveSide::From))
            | (false, ChangeKind::Move, Some(MoveSide::To))
    )
}

/// The listed changes whose `inside` chain reaches `root`: settling `root`
/// so its content goes takes them along. A style record is not one.
pub(super) fn taken_along<'a>(listed: &'a [Change], root: &Change) -> Vec<&'a Change> {
    let by_id: HashMap<&str, &Change> = listed.iter().map(|c| (c.id.as_str(), c)).collect();
    let roots: HashSet<&str> = root.element_ids().collect();
    listed
        .iter()
        .filter(|change| {
            if roots.contains(change.id.as_str()) || change.id.starts_with(STYLES_STORY) {
                return false;
            }
            let mut cursor = change.inside.as_deref();
            let mut seen = HashSet::new();
            while let Some(id) = cursor {
                if !seen.insert(id) {
                    return false;
                }
                if roots.contains(id) {
                    return true;
                }
                cursor = by_id.get(id).and_then(|holder| holder.inside.as_deref());
            }
            false
        })
        .collect()
}

/// One sentence for a comment a content-removing decision would delete.
fn comment_not_yours(verb: &str, change_id: &str, comment_id: &str, author: &str) -> String {
    let whose = if author.is_empty() {
        format!("{comment_id}, which names no author")
    } else {
        format!("{comment_id}, which is by {author:?}")
    };
    format!("{verb} {change_id} would delete {whose}")
}

/// Whether `author` wrote the comment. An empty author is not the plan's.
fn owns_comment(author: &str, actor: &str) -> bool {
    !author.is_empty() && author == actor
}

/// `record` replies to `root`, walking `parent` and stopping on a cycle.
fn replies_to(
    record: &crate::comments::CommentRecord,
    root: u32,
    by_id: &HashMap<u32, &crate::comments::CommentRecord>,
) -> bool {
    let mut cursor = record.parent;
    let mut seen = HashSet::new();
    while let Some(id) = cursor {
        if !seen.insert(id) {
            return false;
        }
        if id == root {
            return true;
        }
        cursor = by_id.get(&id).and_then(|comment| comment.parent);
    }
    false
}

/// Refuse when a content-removing decision would delete a comment the plan's
/// author does not own, the comment itself or a reply in its thread. The
/// anchor's removal deletes the thread.
pub(super) fn guard_removed_comments(
    source: &[u8],
    actor: &str,
    removals: &[(&Change, bool, Vec<&Change>)],
) -> Result<(), EditError> {
    let mut held: Vec<(&str, &str, bool)> = Vec::new();
    for (change, accepting, nested) in removals {
        for id in change
            .holds_comments
            .iter()
            .chain(nested.iter().flat_map(|inner| inner.holds_comments.iter()))
        {
            if held.iter().any(|(_, have, _)| *have == id) {
                continue;
            }
            held.push((change.id.as_str(), id.as_str(), *accepting));
        }
    }
    if held.is_empty() {
        return Ok(());
    }
    let records = crate::comments::list_comments(source)
        .map_err(|e| err("INVALID_DOCUMENT", None, e.to_string()))?;
    let by_id: HashMap<u32, &crate::comments::CommentRecord> =
        records.iter().map(|record| (record.id, record)).collect();
    for (change_id, comment_id, accepting) in held {
        let Some(root) = records.iter().find(|record| record.r#ref == comment_id) else {
            continue;
        };
        let verb = if accepting { "accepting" } else { "rejecting" };
        if !owns_comment(&root.author, actor) {
            return Err(err(
                "COMMENT_NOT_YOURS",
                None,
                comment_not_yours(verb, change_id, comment_id, &root.author),
            ));
        }
        for reply in &records {
            if reply.id == root.id || !replies_to(reply, root.id, &by_id) {
                continue;
            }
            if owns_comment(&reply.author, actor) {
                continue;
            }
            return Err(err(
                "COMMENT_NOT_YOURS",
                None,
                comment_not_yours(verb, change_id, &reply.r#ref, &reply.author),
            ));
        }
    }
    Ok(())
}

/// An author the wholesale settlement would erase, in first-seen order.
pub(super) fn note_foreign(
    change: &Change,
    actor: &str,
    authors: &mut Vec<String>,
    nameless: &mut bool,
) {
    if change.id.starts_with(STYLES_STORY) || owns_change(change.author.as_deref(), actor) {
        return;
    }
    match change.author.as_deref() {
        Some(name) if !name.is_empty() => {
            if !authors.iter().any(|have: &String| have == name) {
                authors.push(name.to_string());
            }
        }
        _ => *nameless = true,
    }
}

/// The blockers a refusal names: the first [`BLOCKERS_SHOWN`] revision
/// ids, then a count of the rest (`jubarte changes` lists them all).
fn blocker_list(revisions: &[String]) -> String {
    let shown = revisions
        .iter()
        .take(BLOCKERS_SHOWN)
        .map(String::as_str)
        .collect::<Vec<_>>()
        .join(", ");
    match revisions.len().saturating_sub(BLOCKERS_SHOWN) {
        0 => shown,
        rest => format!("{shown} and {rest} more"),
    }
}

const BLOCKERS_SHOWN: usize = 20;

/// Settle `source` (opened as `probe`) as `plan` asks: accept and reject
/// what `resolve_revisions` selects, then apply `existing_revisions` to the
/// changes left.
pub(super) fn settle(
    source: &[u8],
    plan: &EditPlan,
    probe: Opened,
    syntax: PlanSyntax,
) -> Result<Settled, EditError> {
    let original = source;
    if plan.others.keeps() {
        let wholesale = match plan.existing_revisions {
            ExistingRevisions::Accept => Some("accept"),
            ExistingRevisions::Reject => Some("reject"),
            ExistingRevisions::Keep | ExistingRevisions::Refuse => None,
        };
        guard_keep_others(
            source,
            &plan.author,
            plan.resolve_revisions.as_ref(),
            wholesale,
            false,
            syntax,
        )?;
    }
    let (resolved_source, resolved_revisions, mut comment_changes) = resolve_selected(
        source,
        plan.resolve_revisions.as_ref(),
        plan.removed_anchor_comments,
        syntax,
    )?;
    let (source, probe) = match &resolved_source {
        Some(bytes) => (bytes.as_slice(), Opened::open(bytes).map_err(open_error)?),
        None => (source, probe),
    };
    // The listed changes of the body, headers, footers and notes; a style's
    // recorded formatting does not make the text tracked. A refusal names
    // those revisions: they are the blockers, and no rewrite hash is returned.
    let revisions: Vec<String> = crate::changes::changes_in(&probe.pkg)
        .into_iter()
        .filter(|c| !c.id.starts_with(STYLES_STORY))
        .map(|c| c.id)
        .collect();
    let has_revisions = !revisions.is_empty();
    let (base, opened, flattened) = match (has_revisions, plan.existing_revisions) {
        (false, _) | (true, ExistingRevisions::Keep) => (source.to_vec(), probe, false),
        (true, ExistingRevisions::Refuse) => {
            return Err(err(
                "EXISTING_REVISIONS",
                None,
                format!(
                    "the document already holds tracked changes; blockers: {}; {KEEP_REVISIONS}",
                    blocker_list(&revisions)
                ),
            ));
        }
        (true, policy) => {
            let resolution = if policy == ExistingRevisions::Accept {
                crate::revision_processor::Resolution::Accept
            } else {
                crate::revision_processor::Resolution::Reject
            };
            let (flattened, removed, kept) = crate::changes::resolve_for_edit(
                source,
                &ChangeFilter::default(),
                resolution,
                plan.removed_anchor_comments == RemovedAnchorComments::Keep,
            )
            .map_err(|e| err("INVALID_DOCUMENT", None, e.to_string()))?;
            comment_changes.extend(removed, kept, resolution, None);
            let reopened = Opened::open(&flattened).map_err(open_error)?;
            (flattened, reopened, true)
        }
    };
    let changed = resolved_source.is_some() || flattened;
    // Accepts, rejects and the global policy settle in separate passes;
    // only the settled document may not expose a final mark (#2096).
    if changed {
        crate::changes::check_exposed_final_marks(original, &base)
            .map_err(|e| selection_error(e, syntax, ""))?;
    }
    Ok(Settled {
        base,
        opened,
        resolved_revisions,
        comment_changes,
        changed,
    })
}

/// A document's stories and its addressable paragraphs.
pub(super) struct Loaded {
    /// The body first, then every header, footer and notes part.
    pub(super) stories: Vec<StoryPart>,
    /// The body's paragraphs, then each story's.
    pub(super) paragraph_nodes: Vec<NodeId>,
    /// `(story, index in that story)` per entry of `paragraph_nodes`.
    pub(super) paragraph_story: Vec<(usize, usize)>,
}

/// The body and every header, footer and notes part of `opened`, parsed
/// into its DOM, with every addressable paragraph.
pub(super) fn load_stories(opened: &mut Opened) -> Result<Loaded, EditError> {
    let mut stories = vec![StoryPart {
        id: BODY_STORY.to_string(),
        part: opened.main.clone(),
        document: opened.document,
        root: opened.body,
    }];
    for (id, _, part) in opened.story_parts() {
        let invalid = |m: String| err("INVALID_DOCUMENT", None, format!("{part}: {m}"));
        let xml = opened
            .pkg
            .part_string(&part)
            .ok_or_else(|| invalid("missing part".into()))?;
        crate::xmllinq::parse::validate_xml(&xml).map_err(|e| invalid(e.to_string()))?;
        let document = opened.dom.parse_xdocument(&xml);
        let root = opened
            .dom
            .root(document)
            .ok_or_else(|| invalid("missing XML root".into()))?;
        stories.push(StoryPart {
            id,
            part,
            document,
            root,
        });
    }
    let mut paragraph_nodes = Vec::new();
    let mut paragraph_story = Vec::new();
    for (index, story) in stories.iter().enumerate() {
        let nodes = if index == 0 {
            crate::inspect::body_paragraph_nodes(&opened.dom, story.root)
        } else {
            crate::inspect::story_paragraph_nodes(&opened.dom, story.root)
        };
        for (local, node) in nodes.into_iter().enumerate() {
            paragraph_nodes.push(node);
            paragraph_story.push((index, local));
        }
    }
    Ok(Loaded {
        stories,
        paragraph_nodes,
        paragraph_story,
    })
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod guard_branch_tests {
    use super::super::deeper_boundary_fixture::docx;
    use super::*;

    const INS: &str = r#"<w:ins w:id="1" w:author="Bo" w:date="2026-01-01T00:00:00Z"><w:r><w:t>added words</w:t></w:r></w:ins>"#;

    fn run(source: &[u8], author: &str, ops: serde_json::Value) -> Vec<u8> {
        let mut value = serde_json::json!({
            "schema_version": 1,
            "author": author,
            "date": "2026-02-02T00:00:00Z",
            "existing_revisions": "keep",
        });
        value["operations"] = ops;
        let plan = EditPlan::from_json(&value.to_string()).unwrap();
        apply_plan(source, &plan).unwrap().redline
    }

    /// Bo's insertion, Cy's comment on it, and Di's reply to the comment.
    fn threaded() -> Vec<u8> {
        let source = docx(&format!(
            "<w:p><w:r><w:t xml:space=\"preserve\">Lead </w:t></w:r>{INS}</w:p>"
        ));
        let commented = run(
            &source,
            "Cy",
            serde_json::json!([{"kind":"comment","paragraph":"p0","find":"added","text":"why?"}]),
        );
        let id = crate::comments::list_comments(&commented).unwrap()[0].id;
        run(
            &commented,
            "Di",
            serde_json::json!([{"kind":"reply_comment","comment_id":id,"text":"because"}]),
        )
    }

    fn insertion(source: &[u8]) -> Change {
        crate::changes::list_changes(source)
            .unwrap()
            .into_iter()
            .find(|c| c.kind == ChangeKind::Insertion && c.author.as_deref() == Some("Bo"))
            .expect("Bo's insertion")
    }

    #[test]
    fn removing_a_thread_needs_its_root_and_every_reply_to_be_yours() {
        let source = threaded();
        let change = insertion(&source);
        assert!(!change.holds_comments.is_empty(), "{change:?}");
        // The same comment through the change and a nested one is held once.
        let nested = vec![&change];
        let removals = [(&change, false, nested)];
        let e = guard_removed_comments(&source, "Di", &removals).unwrap_err();
        assert_eq!(e.code, "COMMENT_NOT_YOURS");
        assert!(
            e.message.starts_with("rejecting r1 would delete c"),
            "{}",
            e.message
        );
        assert!(e.message.ends_with("which is by \"Cy\""), "{}", e.message);
        // The root's author still meets the reply by another.
        let removals = [(&change, true, Vec::new())];
        let e = guard_removed_comments(&source, "Cy", &removals).unwrap_err();
        assert!(
            e.message.starts_with("accepting r1 would delete c"),
            "{}",
            e.message
        );
        assert!(e.message.ends_with("which is by \"Di\""), "{}", e.message);
        // A comment the document does not hold is not guarded.
        let mut ghost = change.clone();
        ghost.holds_comments = vec!["c99".into()];
        let removals = [(&ghost, true, Vec::new())];
        assert!(guard_removed_comments(&source, "Zed", &removals).is_ok());
    }

    #[test]
    fn a_thread_wholly_yours_is_removable() {
        let source = docx(&format!("<w:p>{INS}</w:p>"));
        let mine = run(
            &source,
            "Cy",
            serde_json::json!([{"kind":"comment","paragraph":"p0","find":"added","text":"mine"}]),
        );
        let id = crate::comments::list_comments(&mine).unwrap()[0].id;
        let mine = run(
            &mine,
            "Cy",
            serde_json::json!([{"kind":"reply_comment","comment_id":id,"text":"still mine"}]),
        );
        let change = insertion(&mine);
        let removals = [(&change, false, Vec::new())];
        assert!(guard_removed_comments(&mine, "Cy", &removals).is_ok());
    }

    fn bare(id: &str, kind: ChangeKind, author: Option<&str>) -> Change {
        let source = docx(&format!("<w:p>{INS}</w:p>"));
        let mut change = insertion(&source);
        change.id = id.into();
        change.kind = kind;
        change.author = author.map(str::to_string);
        change
    }

    #[test]
    fn foreign_authors_are_named_once_in_order_and_styles_are_no_one() {
        let mut authors = Vec::new();
        let mut nameless = false;
        for change in [
            bare("r1", ChangeKind::Insertion, Some("Bo")),
            bare("r2", ChangeKind::Insertion, Some("Bo")),
            bare("r3", ChangeKind::Deletion, Some("Me")),
            bare("styles.r4", ChangeKind::Formatting, Some("Zed")),
            bare("r5", ChangeKind::Deletion, Some("Cy")),
        ] {
            note_foreign(&change, "Me", &mut authors, &mut nameless);
        }
        assert_eq!(authors, ["Bo", "Cy"]);
        assert!(!nameless);
        note_foreign(
            &bare("r6", ChangeKind::Insertion, Some("")),
            "Me",
            &mut authors,
            &mut nameless,
        );
        assert!(nameless);
        assert_eq!(
            join_authors(&authors, nameless),
            r#""Bo", "Cy" and one that names no author"#
        );
        assert_eq!(join_authors(&[], true), "one that names no author");
        assert_eq!(
            join_authors(&["Bo".into()], true),
            r#""Bo" and one that names no author"#
        );
    }

    #[test]
    fn refusal_sentences_name_the_author_or_its_absence() {
        assert!(owns_change(Some("Me"), "Me"));
        assert!(!owns_change(Some(""), ""));
        assert!(!owns_change(None, "Me"));
        assert_eq!(
            change_not_yours(&bare("r1", ChangeKind::Insertion, Some(""))),
            "r1 names no author; strike it (-p r1 --strike), or comment on it"
        );
        assert_eq!(
            change_not_yours(&bare("r2", ChangeKind::Deletion, Some("Bo"))),
            "r2 is by \"Bo\"; answer it visibly (-p r2 --restore), or comment on it"
        );
        assert_eq!(
            comment_not_yours("accepting", "r1", "c3", ""),
            "accepting r1 would delete c3, which names no author"
        );
    }

    #[test]
    fn taken_along_follows_inside_chains_and_stops_on_cycles() {
        let root = bare("r1", ChangeKind::Insertion, Some("Bo"));
        let mut child = bare("r2", ChangeKind::Deletion, Some("Cy"));
        child.inside = Some("r1".into());
        let mut grandchild = bare("r3", ChangeKind::Deletion, Some("Cy"));
        grandchild.inside = Some("r2".into());
        let mut style = bare("styles.r4", ChangeKind::Formatting, Some("Cy"));
        style.inside = Some("r1".into());
        let mut loop_a = bare("r5", ChangeKind::Deletion, None);
        loop_a.inside = Some("r6".into());
        let mut loop_b = bare("r6", ChangeKind::Deletion, None);
        loop_b.inside = Some("r5".into());
        let mut stray = bare("r7", ChangeKind::Deletion, None);
        stray.inside = Some("r99".into());
        let listed = vec![
            root.clone(),
            child,
            grandchild,
            style,
            loop_a,
            loop_b,
            stray,
        ];
        let along: Vec<&str> = taken_along(&listed, &root)
            .iter()
            .map(|c| c.id.as_str())
            .collect();
        assert_eq!(along, ["r2", "r3"]);
    }

    #[test]
    fn an_unnormalizable_filter_names_nothing() {
        let source = docx(&format!("<w:p>{INS}</w:p>"));
        let listed = crate::changes::list_changes(&source).unwrap();
        let replacement = ChangeFilter {
            ids: None,
            authors: None,
            kinds: Some(vec![ChangeKind::Replacement]),
        };
        assert!(named_ids(&listed, Some(&replacement)).is_empty());
        assert!(named_ids(&listed, None).is_empty());
        assert_eq!(named_ids(&listed, Some(&ChangeFilter::default())), ["r1"]);
    }

    #[test]
    fn a_visible_reject_settles_nothing_before_the_plan() {
        let source = docx(&format!("<w:p>{INS}</w:p>"));
        let selection = ResolveRevisions {
            accept: None,
            reject: Some(ChangeFilter::ids(vec!["r1".to_string()])),
            reject_visible: true,
        };
        let (bytes, resolved, _) = resolve_selected(
            &source,
            Some(&selection),
            RemovedAnchorComments::default(),
            PlanSyntax::default(),
        )
        .unwrap();
        assert!(bytes.is_none());
        assert!(resolved.accepted.is_empty() && resolved.rejected.is_empty());
    }
}