Skip to main content

jubarte_edit/edit/
flags.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4//! `edit` and `add` by flags: each `-p WHERE` with its `--anchor`,
5//! `--content`, `--delete`, `--resolve`, `--reply`, `--before`, `--comment`
6//! and `--style` becomes one operation of an [`EditPlan`]; a `-p r12` with
7//! `--accept` or `--reject` joins the plan's `resolve_revisions`, which runs
8//! before the operations. The binary, the Python CLI and the npm CLI all
9//! build their plan here.
10
11use serde::{Deserialize, Serialize};
12
13use super::{
14    EditPlan, ExistingRevisions, HalfPoints, Operation, OperationKind, ResolveRevisions, RunFormat,
15    RunSpec, Selector, Side,
16};
17use crate::changes::ChangeFilter;
18use crate::ids::{IdError, Location, ShortId};
19
20/// One operation as the flags describe it, grouped by its `-p`.
21#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(default, deny_unknown_fields)]
23pub struct FlagOp {
24    /// The `-p` value: `p12`, `header1`, `t0.row1.cell2`, `c5`, or a long id.
25    pub at: String,
26    /// `--anchor`: text inside `at`.
27    pub anchor: Option<String>,
28    /// `--occurrence`: 1-based match of `anchor` in this group.
29    pub occurrence: Option<usize>,
30    /// `--content`: new text.
31    pub content: Option<String>,
32    /// `--delete`.
33    pub delete: bool,
34    /// `--resolve` (`edit` only).
35    pub resolve: bool,
36    /// `--accept` (`edit` only): accept the revision `at` names.
37    pub accept: bool,
38    /// `--reject` (`edit` only): reject the revision `at` names.
39    pub reject: bool,
40    /// `--strike` (`edit` only): strike another author's insertion, as our
41    /// tracked deletion inside it.
42    pub strike: bool,
43    /// `--restore` (`edit` only): restore another author's deletion, as our
44    /// tracked insertion of its words after it.
45    pub restore: bool,
46    /// `--visible` (with `--reject`): a strike or a restore, by the kind of
47    /// each revision `at` names.
48    pub visible: bool,
49    /// `--reply`: a reply to the comment `at` names.
50    pub reply: Option<String>,
51    /// `--before` (`add` only).
52    pub before: bool,
53    /// `--comment` (`add` only).
54    pub comment: bool,
55    /// `--style` values, in order.
56    pub styles: Vec<String>,
57}
58
59/// Which command the flags came with: `edit` changes what is there, `add`
60/// makes something new.
61#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(rename_all = "snake_case")]
63pub enum Verb {
64    /// `jubarte edit`.
65    Edit,
66    /// `jubarte add`.
67    Add,
68}
69
70/// A plan built from flags, and the notes to print before the view.
71#[derive(Clone, Debug, PartialEq, Eq)]
72pub struct FlagPlan {
73    /// The plan to apply.
74    pub plan: EditPlan,
75    /// `op-N: …` notes (content that keeps Markdown marks as text).
76    pub notes: Vec<String>,
77}
78
79/// The plan `ops` describe. `existing` is `--existing-revisions`; `None` is
80/// `auto`: `keep` when `source` already holds tracked changes, else the
81/// comparer path.
82///
83/// # Errors
84///
85/// The usage message when no operation is given, a flag combination fits no
86/// operation, a `--style` token is unknown, or a revision group is malformed.
87pub fn plan_from_flags(
88    verb: Verb,
89    ops: &[FlagOp],
90    author: &str,
91    date: Option<&str>,
92    existing: Option<ExistingRevisions>,
93    source: &[u8],
94) -> Result<FlagPlan, String> {
95    if ops.is_empty() {
96        return Err("no operation: give -p WHERE with its flags, or --plan".into());
97    }
98    let mut operations = Vec::with_capacity(ops.len());
99    let mut notes = Vec::new();
100    let (mut accept, mut reject) = (Vec::new(), Vec::new());
101    let mut listed: Option<Vec<crate::changes::Change>> = None;
102    for op in ops {
103        if op.occurrence.is_some() && op.anchor.is_none() {
104            return Err(format!("-p {}: --occurrence requires --anchor", op.at));
105        }
106        if op.occurrence == Some(0) {
107            return Err(format!("-p {}: --occurrence is 1-based", op.at));
108        }
109        match revision_group(verb, op)? {
110            Group::Settle { accept: true, ids } => accept.extend(ids),
111            Group::Settle { accept: false, ids } => reject.extend(ids),
112            Group::Answer { how, ids, comment } => {
113                let revision = || crate::changes::composite_id(&ids);
114                let kinds = match how {
115                    Answer::Strike => vec![OperationKind::Strike {
116                        revision: revision(),
117                        comment,
118                    }],
119                    Answer::Restore => vec![OperationKind::Restore {
120                        revision: revision(),
121                        comment,
122                    }],
123                    Answer::ByKind => {
124                        let listed = listed.get_or_insert_with(|| {
125                            crate::changes::list_changes(source).unwrap_or_default()
126                        });
127                        super::visible::reject_kinds(listed, &ids, comment)
128                    }
129                };
130                operations.extend(kinds.into_iter().map(|kind| Operation {
131                    id: None,
132                    group: None,
133                    kind,
134                }));
135            }
136            Group::Operation => {
137                let (kind, note) = flag_operation(verb, op)?;
138                operations.push(Operation {
139                    id: None,
140                    group: None,
141                    kind,
142                });
143                notes.extend(note.map(|n| format!("op-{}: {n}", operations.len())));
144            }
145        }
146    }
147    let side = |ids: Vec<String>| (!ids.is_empty()).then(|| ChangeFilter::ids(ids));
148    let resolve_revisions = (!accept.is_empty() || !reject.is_empty()).then(|| ResolveRevisions {
149        accept: side(accept),
150        reject: side(reject),
151        reject_visible: false,
152    });
153    let existing = existing.unwrap_or_else(|| {
154        if crate::changes::list_changes(source).is_ok_and(|c| !c.is_empty()) {
155            ExistingRevisions::Keep
156        } else {
157            ExistingRevisions::Refuse
158        }
159    });
160    Ok(FlagPlan {
161        plan: EditPlan {
162            schema_version: crate::inspect::SCHEMA_VERSION,
163            source_sha256: None,
164            author: author.to_string(),
165            date: date.map(str::to_string),
166            initials: None,
167            resolve_revisions,
168            removed_anchor_comments: Default::default(),
169            existing_revisions: existing,
170            operations,
171            update_fields: false,
172            rewrite_others_comments: false,
173            others: super::Others::Allow,
174        },
175        notes,
176    })
177}
178
179/// `--style` tokens: run formatting, and at most one paragraph style.
180fn styles(tokens: &[String]) -> Result<(Option<RunFormat>, Option<String>), String> {
181    let mut format = RunFormat::default();
182    let mut touched = false;
183    let mut paragraph: Option<String> = None;
184    for token in tokens {
185        let (key, value) = token
186            .split_once('=')
187            .map_or((token.as_str(), None), |(k, v)| (k, Some(v)));
188        match (key, value) {
189            ("bold", None) => format.bold = Some(true),
190            ("italic", None) => format.italic = Some(true),
191            ("underline", None) => format.underline = Some(true),
192            ("strike", None) => format.strike = Some(true),
193            ("caps", None) => format.caps = Some(true),
194            ("highlight", Some(v)) => format.highlight = Some(v.to_string()),
195            ("font", Some(v)) => format.font = Some(v.to_string()),
196            ("color", Some(v)) => format.color = Some(v.to_string()),
197            ("size", Some(v)) => {
198                let points: f64 = v
199                    .parse()
200                    .ok()
201                    .filter(|p: &f64| p.is_finite() && *p > 0.0 && *p <= 1638.0)
202                    .ok_or_else(|| format!("--style size={v}: points between 0 and 1638"))?;
203                let half = (points * 2.0).round();
204                // In range: at most 3276 half-points.
205                #[expect(
206                    clippy::cast_possible_truncation,
207                    clippy::cast_sign_loss,
208                    reason = "checked above: 0 < half <= 3276"
209                )]
210                let half = half as u32;
211                format.size_pt = Some(HalfPoints(half));
212            }
213            (_, Some(_)) => return Err(format!("--style {token}: unknown key")),
214            ("", None) => return Err("--style needs a value".into()),
215            (name, None) => {
216                if paragraph.replace(name.to_string()).is_some() {
217                    return Err("--style: one paragraph style per operation".into());
218                }
219                continue;
220            }
221        }
222        touched = true;
223    }
224    Ok((touched.then_some(format), paragraph))
225}
226
227/// `--content` as document text: Markdown escapes resolved (`\#` → `#`); a
228/// note when the view would read marks in it (emphasis, CriticMarkup, a
229/// block mark), since they are written as text.
230fn content_text(content: &str) -> (String, Option<&'static str>) {
231    let text = crate::markdown::unescape_markdown(content);
232    // The anchor drops a line's leading spaces (the view's indent); they are
233    // not a mark.
234    let marks = crate::markdown::plain_anchor(content).trim_start() != text.trim_start();
235    (
236        text,
237        marks.then_some("content keeps its Markdown marks as text; use --style for formatting"),
238    )
239}
240
241/// `c5` → 5: the comment a `-p` names.
242fn comment_number(at: &str) -> Option<u32> {
243    match crate::ids::parse_location(at) {
244        Ok(crate::ids::Location::Comment(id)) => Some(id),
245        _ => None,
246    }
247}
248
249/// The refusal of a `-p` id this group cannot take: an expired one, named
250/// with the settled spellings `keep` allows (`-p 5 --reject` → `r5`), or a
251/// settled id `-p` does not edit yet (`s0`, `p3-p7`). `None` when `at`
252/// parses, or when no settled spelling is known (the caller's own message
253/// is then the better one).
254fn expired(at: &str, keep: impl Fn(&ShortId) -> bool) -> Option<String> {
255    match crate::ids::parse_location(at) {
256        Err(e) if e.expected == crate::ids::LOCATION_NOT_YET => Some(format!("-p {e}")),
257        Err(e) if e.hint.is_some() => {
258            let hint = crate::ids::hint_where(e.hint.clone(), keep);
259            Some(format!("-p {}", IdError { hint, ..e }))
260        }
261        _ => None,
262    }
263}
264
265/// What a `-p` group does with the revisions it names.
266enum Group {
267    /// Not a revision group: an operation.
268    Operation,
269    /// `--accept` or `--reject`: the long ids join `resolve_revisions`.
270    Settle { accept: bool, ids: Vec<String> },
271    /// `--strike`, `--restore` or `--reject --visible`: one operation by
272    /// our author on the change the marks `ids` make (a visible reject:
273    /// one per kind), with `--content` as its comment.
274    Answer {
275        how: Answer,
276        ids: Vec<String>,
277        comment: Option<String>,
278    },
279}
280
281/// Which visible reject a group asks for.
282#[derive(Clone, Copy)]
283enum Answer {
284    Strike,
285    Restore,
286    /// `--reject --visible`: by each revision's kind.
287    ByKind,
288}
289
290/// What the `-p r12` group `op` asks of its revisions. Only `edit`
291/// resolves revisions.
292fn revision_group(verb: Verb, op: &FlagOp) -> Result<Group, String> {
293    let at = op.at.trim();
294    let verbs: Vec<&str> = [
295        ("accept", op.accept),
296        ("reject", op.reject),
297        ("strike", op.strike),
298        ("restore", op.restore),
299    ]
300    .into_iter()
301    .filter_map(|(name, set)| set.then_some(name))
302    .collect();
303    // Only a revision group names a change; any other group's id is
304    // refused by [`flag_operation`], with the spellings it takes.
305    if !verbs.is_empty()
306        && let Some(refused) = expired(at, |id| matches!(id, ShortId::Change { .. }))
307    {
308        return Err(refused);
309    }
310    let bad = |m: &str| Err(format!("-p {at}: {m}"));
311    let ids = match crate::ids::parse_location(at) {
312        Ok(Location::Changes(ids)) => Some(ids),
313        _ => None,
314    };
315    // A `--reply` group is an operation: off a comment it says so. It
316    // resolves no revision, so a revision flag beside it is refused, not
317    // ignored.
318    if op.reply.is_some() {
319        if !verbs.is_empty() || op.visible {
320            return bad("--reply takes no other flag");
321        }
322        return Ok(Group::Operation);
323    }
324    if verb == Verb::Add && ids.is_some() {
325        return bad(
326            "add resolves no revision; use edit -p r12 --accept, --reject, --strike or --restore",
327        );
328    }
329    if op.visible && !op.reject {
330        return bad("--visible goes with --reject");
331    }
332    let Some(ids) = ids else {
333        return match verbs.first() {
334            None => Ok(Group::Operation),
335            Some(&("accept" | "reject")) => bad("--accept and --reject take a revision (-p r12)"),
336            Some(name) => bad(&format!("--{name} takes a revision (-p r12)")),
337        };
338    };
339    if let [first, second, ..] = verbs[..] {
340        return bad(&format!("--{first} and --{second} exclude each other"));
341    }
342    let others = op.anchor.is_some()
343        || op.delete
344        || op.resolve
345        || op.before
346        || op.comment
347        || !op.styles.is_empty();
348    if others || verbs.is_empty() {
349        return bad("a revision takes --accept, --reject, --strike or --restore");
350    }
351    let how = if op.strike {
352        Some(Answer::Strike)
353    } else if op.restore {
354        Some(Answer::Restore)
355    } else {
356        op.visible.then_some(Answer::ByKind)
357    };
358    if op.content.is_some() && how.is_none() {
359        return bad(
360            "--content on a revision is the comment of --strike, --restore or --reject --visible",
361        );
362    }
363    let ids = ids.iter().map(crate::ids::ChangeId::short).collect();
364    Ok(match how {
365        Some(how) => Group::Answer {
366            how,
367            ids,
368            comment: op.content.clone(),
369        },
370        None => Group::Settle {
371            accept: op.accept,
372            ids,
373        },
374    })
375}
376
377/// The operation one `-p` group stands for, and a note for the report.
378fn flag_operation(verb: Verb, op: &FlagOp) -> Result<(OperationKind, Option<String>), String> {
379    use OperationKind as K;
380    let at = op.at.trim();
381    let bad = |m: &str| Err(format!("-p {at}: {m}"));
382    if at.is_empty() {
383        return Err("-p needs a location".into());
384    }
385    // The settled spellings this whole group takes: a reply or a
386    // resolution names a comment; a comment takes no --anchor, --style,
387    // --before or --comment (nor, under add, --delete or --resolve); a
388    // change takes --accept or --reject, never these.
389    let names_comment = op.reply.is_some() || op.resolve;
390    let comment_takes = op.anchor.is_none()
391        && op.styles.is_empty()
392        && !op.before
393        && !op.comment
394        && !(verb == Verb::Add && (op.delete || op.resolve));
395    let keep = |id: &ShortId| match id {
396        ShortId::Comment(_) => comment_takes,
397        ShortId::Change { .. } => false,
398        _ => !names_comment,
399    };
400    if let Some(refused) = expired(at, keep) {
401        return Err(refused);
402    }
403    if let Some(reply) = &op.reply {
404        let Some(comment_id) = comment_number(at) else {
405            return bad("--reply is for a comment (-p c5)");
406        };
407        if op.anchor.is_some()
408            || op.content.is_some()
409            || op.delete
410            || op.resolve
411            || op.before
412            || op.comment
413            || !op.styles.is_empty()
414        {
415            return bad("--reply takes no other flag");
416        }
417        let (text, note) = content_text(reply);
418        let note = note.map(|_| {
419            "the reply keeps its Markdown marks as text; replies take no formatting".to_string()
420        });
421        return Ok((K::ReplyComment { comment_id, text }, note));
422    }
423    if op.delete && (op.content.is_some() || op.resolve) {
424        return bad("--delete excludes --content and --resolve");
425    }
426    if op.resolve && (op.content.is_some() || op.anchor.is_some() || !op.styles.is_empty()) {
427        return bad("--resolve takes no --anchor, --content or --style");
428    }
429    if op.before && (op.anchor.is_some() || op.comment) {
430        return bad("--before is for a new paragraph, not a comment");
431    }
432    let paragraph = || Selector::Name(at.to_string());
433    let (run_format, paragraph_style) = styles(&op.styles).map_err(|m| format!("-p {at}: {m}"))?;
434    let (content, note) = match &op.content {
435        Some(c) => {
436            let (text, note) = content_text(c);
437            (Some(text), note.map(str::to_string))
438        }
439        None => (None, None),
440    };
441    let comment_id = comment_number(at);
442    let mut kind = match (verb, comment_id, &op.anchor, content) {
443        (Verb::Add, _, _, _) if op.delete || op.resolve => {
444            return bad("add takes no --delete or --resolve");
445        }
446        // Comments.
447        (_, Some(_), Some(_), _) => return bad("a comment takes no --anchor"),
448        (_, Some(_), _, _) if !op.styles.is_empty() => return bad("a comment takes no --style"),
449        (Verb::Add, Some(id), None, Some(text)) if !op.before && !op.comment && !op.delete => {
450            K::ReplyComment {
451                comment_id: id,
452                text,
453            }
454        }
455        (Verb::Add, Some(_), None, _) => return bad("a reply takes --content only"),
456        (Verb::Edit, Some(id), None, Some(text)) => K::EditComment {
457            comment_id: id,
458            text,
459        },
460        (Verb::Edit, Some(id), None, None) if op.delete => K::DeleteComment { comment_id: id },
461        (Verb::Edit, Some(id), None, None) if op.resolve => K::ResolveComment {
462            comment_id: id,
463            done: true,
464        },
465        (Verb::Edit, Some(_), None, None) => {
466            return bad("a comment takes --content, --delete or --resolve");
467        }
468        // Add.
469        (Verb::Add, None, _, Some(_))
470            if (op.anchor.is_some() || op.comment) && !op.styles.is_empty() =>
471        {
472            return bad("a comment takes no --style");
473        }
474        (Verb::Add, None, Some(anchor), Some(text)) => K::Comment {
475            paragraph: paragraph(),
476            find: Some(anchor.clone()),
477            text,
478            through: None,
479            occurrence: None,
480        },
481        (Verb::Add, None, None, Some(text)) if op.comment => K::Comment {
482            paragraph: paragraph(),
483            find: None,
484            text,
485            through: None,
486            occurrence: None,
487        },
488        (Verb::Add, None, None, Some(text)) => {
489            let format = run_format.unwrap_or_default();
490            // A new paragraph's runs carry these four; the rest would vanish.
491            if format.strike.is_some()
492                || format.caps.is_some()
493                || format.font.is_some()
494                || format.size_pt.is_some()
495                || format.color.is_some()
496            {
497                return bad(
498                    "a new paragraph takes --style bold, italic, underline, highlight=COLOR or a paragraph style",
499                );
500            }
501            K::InsertParagraph {
502                paragraph: paragraph(),
503                position: if op.before { Side::Before } else { Side::After },
504                runs: vec![RunSpec {
505                    text,
506                    bold: format.bold,
507                    italic: format.italic,
508                    underline: format.underline,
509                    highlight: format.highlight,
510                }],
511                like: None,
512                style: paragraph_style,
513                comment: None,
514            }
515        }
516        (Verb::Add, None, _, None) => return bad("add needs --content"),
517        // Edit.
518        (Verb::Edit, None, _, _) if op.resolve => {
519            return bad("--resolve is for a comment (-p c5)");
520        }
521        (Verb::Edit, None, _, _) if op.before || op.comment => {
522            return bad("--before and --comment belong to add");
523        }
524        (Verb::Edit, None, Some(anchor), Some(text)) => {
525            if paragraph_style.is_some() {
526                return bad("a paragraph style takes no --anchor");
527            }
528            inline_edit(paragraph(), anchor, text, run_format)
529                .map_err(|m| format!("-p {at}: {m}"))?
530        }
531        (Verb::Edit, None, Some(_), None) if op.delete && !op.styles.is_empty() => {
532            return bad("--delete takes no --style");
533        }
534        (Verb::Edit, None, Some(anchor), None) if op.delete => K::Delete {
535            paragraph: paragraph(),
536            find: anchor.clone(),
537            occurrence: None,
538            comment: None,
539        },
540        (Verb::Edit, None, Some(anchor), None) => match (run_format, paragraph_style) {
541            (Some(format), None) => K::FormatRun {
542                paragraph: paragraph(),
543                find: anchor.clone(),
544                format,
545                occurrence: None,
546            },
547            (_, Some(_)) => return bad("a paragraph style takes no --anchor"),
548            (None, None) => return bad("--anchor needs --content, --delete or --style"),
549        },
550        (Verb::Edit, None, None, Some(text))
551            if paragraph_style.is_none() && run_format.is_none() =>
552        {
553            K::Rewrite {
554                paragraph: paragraph(),
555                text,
556                comment: None,
557            }
558        }
559        (Verb::Edit, None, None, Some(_)) => {
560            return bad(
561                "a rewrite takes no --style: format with --anchor, or set the paragraph style in a second -p",
562            );
563        }
564        (Verb::Edit, None, None, None) if op.delete => {
565            if !op.styles.is_empty() {
566                return bad("--delete takes no --style");
567            }
568            K::DeleteParagraph {
569                paragraph: paragraph(),
570                comment: None,
571            }
572        }
573        (Verb::Edit, None, None, None) => match (run_format, paragraph_style) {
574            (None, Some(style)) => K::FormatParagraph {
575                paragraph: paragraph(),
576                style: Some(style),
577                alignment: None,
578                line_spacing: None,
579                space_before: None,
580                space_after: None,
581            },
582            (Some(_), _) => return bad("run formatting needs --anchor (the text to format)"),
583            (None, None) => return bad("edit needs --content, --delete, --resolve or --style"),
584        },
585    };
586    match &mut kind {
587        K::Replace { occurrence, .. }
588        | K::Insert { occurrence, .. }
589        | K::Delete { occurrence, .. }
590        | K::FormatRun { occurrence, .. }
591        | K::Comment { occurrence, .. } => *occurrence = op.occurrence,
592        _ => {}
593    }
594    Ok((kind, note))
595}
596
597/// A replacement that keeps the anchor at its start or end is an insertion,
598/// so the redline marks only the new words. The anchor is compared as given
599/// and without its Markdown marks (`# Fees` → `Fees`), and passed on as
600/// given, so the applier still records the normalization.
601fn inline_edit(
602    paragraph: Selector,
603    anchor: &str,
604    text: String,
605    format: Option<RunFormat>,
606) -> Result<OperationKind, String> {
607    use OperationKind as K;
608    let plain = crate::markdown::plain_anchor(anchor);
609    if text == anchor || text == plain {
610        // Same words with a style: "make the anchor bold".
611        return match format {
612            Some(format) => Ok(K::FormatRun {
613                paragraph,
614                find: anchor.to_string(),
615                format,
616                occurrence: None,
617            }),
618            None => Err("--content equals the anchor; nothing to change".into()),
619        };
620    }
621    let after = text.strip_prefix(anchor).or_else(|| {
622        text.strip_prefix(plain.as_str())
623            .filter(|_| !plain.is_empty())
624    });
625    if let Some(added) = after.filter(|a| !a.is_empty()) {
626        return Ok(K::Insert {
627            paragraph,
628            after: Some(anchor.to_string()),
629            before: None,
630            position: None,
631            text: added.to_string(),
632            format,
633            comment: None,
634            occurrence: None,
635        });
636    }
637    let before = text.strip_suffix(anchor).or_else(|| {
638        text.strip_suffix(plain.as_str())
639            .filter(|_| !plain.is_empty())
640    });
641    if let Some(added) = before.filter(|a| !a.is_empty()) {
642        return Ok(K::Insert {
643            paragraph,
644            after: None,
645            before: Some(anchor.to_string()),
646            position: None,
647            text: added.to_string(),
648            format,
649            comment: None,
650            occurrence: None,
651        });
652    }
653    Ok(K::Replace {
654        paragraph,
655        find: anchor.to_string(),
656        replacement: text,
657        format,
658        comment: None,
659        whole: false,
660        occurrence: None,
661    })
662}
663
664/// Why `--editing-mode` cannot apply `plan` to `source`: under `keep` the
665/// tracked changes `plan` does not itself accept or reject (`-p r12
666/// --accept`) stay, so the "clean" copy would still carry revisions; and a
667/// reply to a comment on a paragraph the plan deletes has no thread left in
668/// the clean copy to join.
669pub fn editing_mode_conflict(plan: &EditPlan, source: &[u8]) -> Option<String> {
670    if plan.existing_revisions == ExistingRevisions::Keep
671        && crate::edit::revisions_left(source, plan)
672    {
673        return Some(
674            "--editing-mode needs a document without tracked changes; it has some, so pass --existing-revisions accept or reject".into(),
675        );
676    }
677    let (parent, paragraph) = crate::edit::replies_on_deleted_paragraphs(source, plan)
678        .into_iter()
679        .next()?;
680    let paragraph = paragraph.unwrap_or_else(|| "its paragraph".into());
681    Some(format!(
682        "--editing-mode deletes {paragraph} outright, and c{parent}'s thread with it, so the reply to c{parent} would join nothing; drop --editing-mode to track the deletion and keep the reply on the struck text, or delete without replying"
683    ))
684}
685
686/// [`editing_mode_conflict`] for a plan as JSON, as the Python and npm CLIs
687/// hold it. A plan that does not parse conflicts with nothing here: running
688/// it reports why.
689pub fn editing_mode_conflict_json(plan: &str, source: &[u8]) -> Option<String> {
690    EditPlan::from_json(plan)
691        .ok()
692        .and_then(|plan| editing_mode_conflict(&plan, source))
693}
694
695/// `plan` with `more` recorded after it: what `--plan PLAN.json` with
696/// operation flags writes back. `None` (no plan yet) takes `more` as it is.
697/// The two must agree on the source (`source_sha256`), the author, the date
698/// and `existing_revisions`, since one plan names each once; `more`'s
699/// operations follow `plan`'s and its revision ids join `plan`'s accept and
700/// reject lists, which must select by id alone. A plan pinned to no source
701/// takes `more`'s. An error records nothing.
702///
703/// # Errors
704///
705/// The usage message when the plans disagree on the source, the author, the
706/// date or `existing_revisions`, an operation id collides, a revision is both
707/// accepted and rejected, or a recorded id would narrow a filter that selects
708/// by author or kind.
709pub(crate) fn record_into(plan: Option<EditPlan>, more: EditPlan) -> Result<EditPlan, String> {
710    let Some(mut plan) = plan else {
711        return Ok(more);
712    };
713    if let (Some(pinned), Some(source)) = (&plan.source_sha256, &more.source_sha256)
714        && pinned != source
715    {
716        return Err(format!(
717            "the plan was recorded against another document (sha256 {pinned}); this one is {source}"
718        ));
719    }
720    if plan.author.is_empty() {
721        return Err("the plan names no author, so it cannot be applied; start a new plan".into());
722    }
723    if plan.author != more.author {
724        return Err(format!(
725            "the plan's author is {:?}; pass --author {:?}, or start a new plan",
726            plan.author, plan.author
727        ));
728    }
729    if plan.date != more.date {
730        return Err(match &plan.date {
731            Some(date) => {
732                format!("the plan's date is {date}; pass --datetime {date}, or start a new plan")
733            }
734            None => {
735                "the plan takes its date when it runs; drop --datetime, or start a new plan".into()
736            }
737        });
738    }
739    if plan.existing_revisions != more.existing_revisions {
740        return Err(format!(
741            "the plan's existing_revisions is {mode}; pass --existing-revisions {mode} to match it, or start a new plan",
742            mode = existing_name(plan.existing_revisions),
743        ));
744    }
745    let before = plan.operations.len();
746    let added = before + 1..=before + more.operations.len();
747    if let Some(id) = plan
748        .operations
749        .iter()
750        .filter_map(|op| op.id.as_deref())
751        .find(|id| added.clone().any(|n| *id == format!("op-{n}")))
752    {
753        return Err(format!(
754            "the plan names an operation {id}, the id a recorded operation takes; rename it, or start a new plan"
755        ));
756    }
757    if let Some(more) = more.resolve_revisions {
758        let resolve = plan.resolve_revisions.get_or_insert_with(Default::default);
759        // The plan's reject list strikes and restores (`visible`); a
760        // recorded `--reject` joined to it would turn visible too.
761        if let Some(ids) = more.reject.as_ref().and_then(|r| r.ids.as_ref())
762            && resolve.reject_visible
763            && !more.reject_visible
764        {
765            return Err(format!(
766                "the plan's reject is visible, and a recorded --reject is silent: record -p {} --reject --visible, or start a new plan",
767                ids.join(" -p ")
768            ));
769        }
770        // Every id in its short spelling, as recorded ones are, so `r1+2`
771        // and `r1`, `r2` are the same ids; a malformed one is left for the
772        // preview to report.
773        for side in [&mut resolve.accept, &mut resolve.reject] {
774            if let Some(normal) = side.as_ref().and_then(|f| f.normalized().ok()) {
775                *side = Some(normal);
776            }
777        }
778        join_ids(&mut resolve.accept, more.accept, "accept")?;
779        join_ids(&mut resolve.reject, more.reject, "reject")?;
780        let (accept, reject) = (filter_ids(&resolve.accept), filter_ids(&resolve.reject));
781        if let Some(both) = accept.iter().find(|id| reject.contains(id)) {
782            return Err(format!("{both} is both accepted and rejected"));
783        }
784    }
785    plan.operations.extend(more.operations);
786    // A permission recorded once holds for the whole plan.
787    plan.rewrite_others_comments |= more.rewrite_others_comments;
788    if more.others.keeps() {
789        plan.others = super::Others::Keep;
790    }
791    // The merged plan is previewed against `more`'s source before it is
792    // written, so an unpinned plan may take that pin.
793    plan.source_sha256 = plan.source_sha256.or(more.source_sha256);
794    Ok(plan)
795}
796
797/// `--existing-revisions`' spelling of `mode`.
798fn existing_name(mode: ExistingRevisions) -> &'static str {
799    match mode {
800        ExistingRevisions::Keep => "keep",
801        ExistingRevisions::Accept => "accept",
802        ExistingRevisions::Reject => "reject",
803        ExistingRevisions::Refuse => "refuse",
804    }
805}
806
807/// `more`'s ids after `filter`'s, each once. A filter that also selects by
808/// author or kind, or one naming no ids (every change), would be narrowed by
809/// the ids, since a change must match every list: that is refused.
810fn join_ids(
811    filter: &mut Option<ChangeFilter>,
812    more: Option<ChangeFilter>,
813    side: &str,
814) -> Result<(), String> {
815    let Some(more) = more.and_then(|m| m.ids) else {
816        return Ok(());
817    };
818    if let Some(held) = filter.as_ref()
819        && (held.authors.is_some() || held.kinds.is_some() || held.ids.is_none())
820    {
821        return Err(format!(
822            "the plan's {side} selects revisions by author or kind, or all of them; a recorded revision id would narrow it, so start a new plan"
823        ));
824    }
825    let ids = filter
826        .get_or_insert_with(Default::default)
827        .ids
828        .get_or_insert_with(Vec::new);
829    for id in more {
830        if !ids.contains(&id) {
831            ids.push(id);
832        }
833    }
834    Ok(())
835}
836
837/// The ids `filter` names.
838fn filter_ids(filter: &Option<ChangeFilter>) -> &[String] {
839    filter
840        .as_ref()
841        .and_then(|f| f.ids.as_deref())
842        .unwrap_or_default()
843}
844
845/// `notes` (`op-N: …`, numbered within one recording) renumbered after the
846/// `before` operations the plan already held.
847pub(crate) fn renumber_notes(notes: Vec<String>, before: usize) -> Vec<String> {
848    notes
849        .into_iter()
850        .map(|note| {
851            let parsed = note
852                .strip_prefix("op-")
853                .and_then(|rest| rest.split_once(':'))
854                .and_then(|(n, rest)| Some((n.parse::<usize>().ok()?, rest)));
855            match parsed {
856                Some((n, rest)) => format!("op-{}:{rest}", n + before),
857                None => note,
858            }
859        })
860        .collect()
861}
862
863/// [`plan_from_flags`] over JSON, for the Python and npm CLIs: `verb` is
864/// `edit` or `add`, `operations` the `operations` array their parsed
865/// command carries, `existing` the `--existing-revisions` value (`auto`,
866/// `keep`, `accept`, `reject`, `refuse`). Returns the plan as JSON and the
867/// notes.
868///
869/// # Errors
870///
871/// The usage message for an unknown verb, unparsable operations, a bad
872/// `--existing-revisions` value, and every [`plan_from_flags`] failure.
873pub fn plan_from_flags_json(
874    verb: &str,
875    operations: &str,
876    author: &str,
877    date: Option<&str>,
878    existing: &str,
879    source: &[u8],
880) -> Result<(String, Vec<String>), String> {
881    let verb = match verb {
882        "edit" => Verb::Edit,
883        "add" => Verb::Add,
884        other => return Err(format!("unknown verb {other:?}: edit or add")),
885    };
886    let ops: Vec<FlagOp> =
887        serde_json::from_str(operations).map_err(|e| format!("operations: {e}"))?;
888    let existing = match existing {
889        "auto" => None,
890        "keep" => Some(ExistingRevisions::Keep),
891        "accept" => Some(ExistingRevisions::Accept),
892        "reject" => Some(ExistingRevisions::Reject),
893        "refuse" => Some(ExistingRevisions::Refuse),
894        other => {
895            return Err(format!(
896                "existing revisions {other:?}: auto, keep, accept, reject or refuse"
897            ));
898        }
899    };
900    let built = plan_from_flags(verb, &ops, author, date, existing, source)?;
901    let json = serde_json::to_string(&built.plan).map_err(|e| e.to_string())?;
902    Ok((json, built.notes))
903}
904
905#[cfg(test)]
906mod tests {
907    use super::*;
908
909    fn op(at: &str) -> FlagOp {
910        FlagOp {
911            at: at.into(),
912            ..FlagOp::default()
913        }
914    }
915
916    fn kind(verb: Verb, op: &FlagOp) -> Result<OperationKind, String> {
917        flag_operation(verb, op).map(|(k, _)| k)
918    }
919
920    /// The plan `ops` record by `author`, pinned to `sha`.
921    fn recorded(verb: Verb, ops: &[FlagOp], author: &str, sha: &str) -> EditPlan {
922        let mut plan = plan_from_flags(verb, ops, author, None, Some(ExistingRevisions::Keep), b"")
923            .unwrap()
924            .plan;
925        plan.source_sha256 = Some(sha.into());
926        plan
927    }
928
929    fn revision(at: &str, accept: bool) -> FlagOp {
930        FlagOp {
931            accept,
932            reject: !accept,
933            ..op(at)
934        }
935    }
936
937    fn rewrite(at: &str, content: &str) -> FlagOp {
938        FlagOp {
939            content: Some(content.into()),
940            ..op(at)
941        }
942    }
943
944    /// `--plan` with operation flags: the first recording is the plan, each
945    /// later one appends its operations and joins its revision ids.
946    #[test]
947    fn recording_appends_operations_and_joins_revision_ids() {
948        let first = recorded(
949            Verb::Edit,
950            &[rewrite("p1", "One."), revision("r2", true)],
951            "Ann",
952            "aa",
953        );
954        let plan = record_into(None, first.clone()).unwrap();
955        assert_eq!(plan, first);
956        let second = recorded(
957            Verb::Add,
958            &[FlagOp {
959                comment: true,
960                ..rewrite("p3", "Why?")
961            }],
962            "Ann",
963            "aa",
964        );
965        let third = recorded(
966            Verb::Edit,
967            &[revision("r2+5", true), revision("header1.r1", false)],
968            "Ann",
969            "aa",
970        );
971        let plan = record_into(Some(record_into(Some(plan), second).unwrap()), third).unwrap();
972        assert_eq!(plan.operations.len(), 2);
973        assert!(matches!(
974            plan.operations[1].kind,
975            OperationKind::Comment { .. }
976        ));
977        let resolve = plan.resolve_revisions.unwrap();
978        assert_eq!(resolve.accept.unwrap().ids.unwrap(), ["r2", "r5"]);
979        assert_eq!(resolve.reject.unwrap().ids.unwrap(), ["header1.r1"]);
980        assert_eq!(plan.source_sha256.as_deref(), Some("aa"));
981    }
982
983    /// One plan names one source, author, date and mode: a recording that
984    /// disagrees is refused and says what to pass.
985    #[test]
986    fn recording_refuses_what_the_plan_names_differently() {
987        let base = || recorded(Verb::Edit, &[rewrite("p1", "One.")], "Ann", "aa");
988        let refused = |more: EditPlan| record_into(Some(base()), more).unwrap_err();
989        assert!(
990            refused(recorded(Verb::Edit, &[rewrite("p2", "Two.")], "Ann", "bb"))
991                .starts_with("the plan was recorded against another document (sha256 aa)")
992        );
993        assert_eq!(
994            refused(recorded(Verb::Edit, &[rewrite("p2", "Two.")], "Bob", "aa")),
995            r#"the plan's author is "Ann"; pass --author "Ann", or start a new plan"#
996        );
997        let mut dated = recorded(Verb::Edit, &[rewrite("p2", "Two.")], "Ann", "aa");
998        dated.date = Some("2026-10-12T00:00:00Z".into());
999        assert_eq!(
1000            refused(dated),
1001            "the plan takes its date when it runs; drop --datetime, or start a new plan"
1002        );
1003        let mut refusing = recorded(Verb::Edit, &[rewrite("p2", "Two.")], "Ann", "aa");
1004        refusing.existing_revisions = ExistingRevisions::Refuse;
1005        assert_eq!(
1006            refused(refusing),
1007            "the plan's existing_revisions is keep; pass --existing-revisions keep to match it, or start a new plan"
1008        );
1009        let accepted = recorded(Verb::Edit, &[revision("r2", true)], "Ann", "aa");
1010        let plan = record_into(Some(base()), accepted).unwrap();
1011        assert_eq!(
1012            record_into(
1013                Some(plan),
1014                recorded(Verb::Edit, &[revision("r2", false)], "Ann", "aa")
1015            )
1016            .unwrap_err(),
1017            "r2 is both accepted and rejected"
1018        );
1019    }
1020
1021    /// pi review 06b F1, F2, F4.
1022    #[test]
1023    fn recording_pins_an_unpinned_plan_and_keeps_hand_written_meaning() {
1024        let mut unpinned = recorded(Verb::Edit, &[rewrite("p1", "One.")], "Ann", "aa");
1025        unpinned.source_sha256 = None;
1026        let more = recorded(Verb::Edit, &[rewrite("p2", "Two.")], "Ann", "bb");
1027        let plan = record_into(Some(unpinned), more).unwrap();
1028        assert_eq!(plan.source_sha256.as_deref(), Some("bb"));
1029        // An accept by author (or of everything) would be narrowed by an id.
1030        for held in [
1031            ChangeFilter {
1032                authors: Some(vec!["Ann".into()]),
1033                ..ChangeFilter::default()
1034            },
1035            ChangeFilter::default(),
1036        ] {
1037            let mut plan = recorded(Verb::Edit, &[rewrite("p1", "One.")], "Ann", "aa");
1038            plan.resolve_revisions = Some(ResolveRevisions {
1039                accept: Some(held),
1040                reject: None,
1041                reject_visible: false,
1042            });
1043            let accept = recorded(Verb::Edit, &[revision("r9", true)], "Ann", "aa");
1044            assert!(
1045                record_into(Some(plan), accept)
1046                    .unwrap_err()
1047                    .starts_with("the plan's accept selects revisions by author or kind, or all")
1048            );
1049        }
1050        // A held id that a recorded operation's position would repeat.
1051        let mut named = recorded(Verb::Edit, &[rewrite("p1", "One.")], "Ann", "aa");
1052        named.operations[0].id = Some("op-2".into());
1053        let more = recorded(Verb::Edit, &[rewrite("p2", "Two.")], "Ann", "aa");
1054        assert_eq!(
1055            record_into(Some(named), more).unwrap_err(),
1056            "the plan names an operation op-2, the id a recorded operation takes; rename it, or start a new plan"
1057        );
1058    }
1059
1060    /// #1286: a recorded `--reject` is silent, and the plan's
1061    /// reject list strikes and restores; merged, the recorded id would turn
1062    /// visible.
1063    #[test]
1064    fn a_silent_reject_is_not_recorded_into_a_visible_one() {
1065        let mut plan = recorded(Verb::Edit, &[rewrite("p1", "One.")], "Ann", "aa");
1066        plan.resolve_revisions = Some(ResolveRevisions {
1067            accept: None,
1068            reject: Some(ChangeFilter::ids(["r4"])),
1069            reject_visible: true,
1070        });
1071        let reject = recorded(Verb::Edit, &[revision("r5", false)], "Ann", "aa");
1072        assert_eq!(
1073            record_into(Some(plan.clone()), reject).unwrap_err(),
1074            "the plan's reject is visible, and a recorded --reject is silent: record -p r5 --reject --visible, or start a new plan"
1075        );
1076        // An accept still records beside it.
1077        let accept = recorded(Verb::Edit, &[revision("r6", true)], "Ann", "aa");
1078        let merged = record_into(Some(plan), accept).unwrap();
1079        let resolve = merged.resolve_revisions.unwrap();
1080        assert!(resolve.reject_visible);
1081        assert_eq!(resolve.accept.unwrap().ids.unwrap(), ["r6"]);
1082    }
1083
1084    /// pi review 06c: id spellings, string op ids, an empty author.
1085    #[test]
1086    fn recording_reads_ids_and_names_as_the_plan_spells_them() {
1087        let mut short = recorded(Verb::Edit, &[rewrite("p1", "One.")], "Ann", "aa");
1088        short.resolve_revisions = Some(ResolveRevisions {
1089            accept: Some(ChangeFilter::ids(["r1"])),
1090            reject: None,
1091            reject_visible: false,
1092        });
1093        let again = recorded(Verb::Edit, &[revision("r1", true)], "Ann", "aa");
1094        let plan = record_into(Some(short.clone()), again).unwrap();
1095        let accept = plan.resolve_revisions.unwrap().accept.unwrap().ids.unwrap();
1096        assert_eq!(accept, ["r1"]);
1097        let reject = recorded(Verb::Edit, &[revision("r1", false)], "Ann", "aa");
1098        assert_eq!(
1099            record_into(Some(short), reject).unwrap_err(),
1100            "r1 is both accepted and rejected"
1101        );
1102        let mut padded = recorded(Verb::Edit, &[rewrite("p1", "One.")], "Ann", "aa");
1103        padded.operations[0].id = Some("op-02".into());
1104        let more = recorded(Verb::Edit, &[rewrite("p2", "Two.")], "Ann", "aa");
1105        assert!(record_into(Some(padded), more).is_ok());
1106        let mut nobody = recorded(Verb::Edit, &[rewrite("p1", "One.")], "", "aa");
1107        nobody.author = String::new();
1108        let more = recorded(Verb::Edit, &[rewrite("p2", "Two.")], "", "aa");
1109        assert!(
1110            record_into(Some(nobody), more)
1111                .unwrap_err()
1112                .starts_with("the plan names no author")
1113        );
1114    }
1115
1116    #[test]
1117    fn notes_count_on_from_the_operations_the_plan_held() {
1118        assert_eq!(
1119            renumber_notes(vec!["op-1: kept as text".into(), "other".into()], 3),
1120            ["op-4: kept as text", "other"]
1121        );
1122    }
1123
1124    /// pi review av4 F5: deleting an anchor has nothing to format, with or
1125    /// without the anchor.
1126    #[test]
1127    fn delete_refuses_a_style_with_an_anchor_too() {
1128        let mut delete = op("p4");
1129        delete.anchor = Some("Fees".into());
1130        delete.delete = true;
1131        delete.styles = vec!["bold".into()];
1132        assert_eq!(
1133            kind(Verb::Edit, &delete).unwrap_err(),
1134            "-p p4: --delete takes no --style"
1135        );
1136        delete.styles = vec!["Heading2".into()];
1137        assert_eq!(
1138            kind(Verb::Edit, &delete).unwrap_err(),
1139            "-p p4: --delete takes no --style"
1140        );
1141    }
1142
1143    #[test]
1144    fn add_refuses_what_it_cannot_write() {
1145        let mut new = op("p1");
1146        new.content = Some("Pay on time.".into());
1147        for style in ["strike", "caps", "font=Calibri", "size=11", "color=FF0000"] {
1148            new.styles = vec![style.into()];
1149            let e = kind(Verb::Add, &new).unwrap_err();
1150            assert!(e.contains("a new paragraph takes --style"), "{style}: {e}");
1151        }
1152        new.styles = vec!["bold".into(), "highlight=yellow".into(), "Heading2".into()];
1153        assert!(kind(Verb::Add, &new).is_ok());
1154        let mut comment = op("p1");
1155        comment.anchor = Some("Pay".into());
1156        comment.content = Some("Why?".into());
1157        comment.styles = vec!["bold".into()];
1158        assert!(
1159            kind(Verb::Add, &comment)
1160                .unwrap_err()
1161                .contains("a comment takes no --style")
1162        );
1163        let mut delete = op("c0");
1164        delete.delete = true;
1165        assert_eq!(
1166            kind(Verb::Add, &delete).unwrap_err(),
1167            "-p c0: add takes no --delete or --resolve"
1168        );
1169    }
1170
1171    #[test]
1172    fn the_json_entry_point_reads_what_the_cli_schema_serializes() {
1173        let ops = r#"[{"at":"p0","anchor":null,"content":"**Fees**","delete":false,"resolve":false,"before":false,"comment":false,"styles":[]}]"#;
1174        let (plan, notes) = plan_from_flags_json(
1175            "edit",
1176            ops,
1177            "Ann",
1178            Some("2026-10-01T09:00:00Z"),
1179            "keep",
1180            b"",
1181        )
1182        .unwrap();
1183        let plan = EditPlan::from_json(&plan).unwrap();
1184        assert_eq!(plan.author, "Ann");
1185        assert_eq!(plan.existing_revisions, ExistingRevisions::Keep);
1186        assert_eq!(plan.operations.len(), 1);
1187        assert_eq!(
1188            notes,
1189            ["op-1: content keeps its Markdown marks as text; use --style for formatting"]
1190        );
1191        for (verb, existing) in [("move", "keep"), ("edit", "sometimes")] {
1192            assert!(plan_from_flags_json(verb, ops, "Ann", None, existing, b"").is_err());
1193        }
1194        assert!(plan_from_flags_json("edit", "{", "Ann", None, "keep", b"").is_err());
1195    }
1196
1197    #[test]
1198    fn an_anchor_kept_at_either_end_is_an_insertion() {
1199        let k = inline_edit(
1200            Selector::Name("p1".into()),
1201            "thirty",
1202            "thirty (30)".into(),
1203            None,
1204        )
1205        .unwrap();
1206        assert!(
1207            matches!(k, OperationKind::Insert { after: Some(ref a), ref text, .. } if a == "thirty" && text == " (30)")
1208        );
1209        let k = inline_edit(
1210            Selector::Name("p2".into()),
1211            "Late",
1212            "Note: Late".into(),
1213            None,
1214        )
1215        .unwrap();
1216        assert!(
1217            matches!(k, OperationKind::Insert { before: Some(ref b), ref text, .. } if b == "Late" && text == "Note: ")
1218        );
1219        let k = inline_edit(
1220            Selector::Name("p0".into()),
1221            "# Fees",
1222            "Fees * Costs".into(),
1223            None,
1224        )
1225        .unwrap();
1226        assert!(
1227            matches!(k, OperationKind::Insert { after: Some(ref a), ref text, .. } if a == "# Fees" && text == " * Costs")
1228        );
1229        let k = inline_edit(Selector::Name("p1".into()), "thirty", "sixty".into(), None).unwrap();
1230        assert!(
1231            matches!(k, OperationKind::Replace { ref replacement, .. } if replacement == "sixty")
1232        );
1233        assert!(inline_edit(Selector::Name("p1".into()), "# x", "x".into(), None).is_err());
1234    }
1235
1236    /// pi review av4 F12: the note fires whenever the content reads
1237    /// differently as Markdown, CriticMarkup and block marks included, and
1238    /// not for escaped marks or a lone `*`.
1239    #[test]
1240    fn content_notes_every_mark_the_view_would_read() {
1241        for noted in [
1242            "**bold**",
1243            "{++x++}",
1244            "{~~a~>b~~}",
1245            "# Title",
1246            "_x_",
1247            "<u>u</u>",
1248        ] {
1249            assert!(content_text(noted).1.is_some(), "{noted}");
1250        }
1251        for plain in [
1252            "\\*\\*x\\*\\*",
1253            "*italics?",
1254            "2 * 3",
1255            "snake__case",
1256            "plain",
1257            " lead",
1258            "trail ",
1259            "two\nlines",
1260            "a = b",
1261            "x - y",
1262        ] {
1263            assert!(content_text(plain).1.is_none(), "{plain}");
1264        }
1265    }
1266
1267    /// pi review av4 F8: "make thirty bold" written as `--anchor thirty
1268    /// --content thirty --style bold` formats the run instead of refusing.
1269    #[test]
1270    fn content_equal_to_the_anchor_with_a_style_formats_the_run() {
1271        let bold = RunFormat {
1272            bold: Some(true),
1273            ..RunFormat::default()
1274        };
1275        for content in ["thirty", "**thirty**"] {
1276            let k = inline_edit(
1277                Selector::Name("p1".into()),
1278                "**thirty**",
1279                content.into(),
1280                Some(bold.clone()),
1281            )
1282            .unwrap();
1283            assert!(
1284                matches!(k, OperationKind::FormatRun { ref find, ref format, .. } if find == "**thirty**" && format.bold == Some(true)),
1285                "{content}"
1286            );
1287        }
1288    }
1289
1290    #[test]
1291    fn each_flag_combination_maps_to_one_kind() {
1292        let with = |f: &dyn Fn(&mut FlagOp)| {
1293            let mut o = op("p1");
1294            f(&mut o);
1295            o
1296        };
1297        assert!(matches!(
1298            kind(Verb::Edit, &with(&|o| o.content = Some("New text.".into()))),
1299            Ok(OperationKind::Rewrite { .. })
1300        ));
1301        assert!(matches!(
1302            kind(Verb::Edit, &with(&|o| o.delete = true)),
1303            Ok(OperationKind::DeleteParagraph { .. })
1304        ));
1305        assert!(matches!(
1306            kind(
1307                Verb::Edit,
1308                &with(&|o| {
1309                    o.anchor = Some("a".into());
1310                    o.delete = true;
1311                })
1312            ),
1313            Ok(OperationKind::Delete { .. })
1314        ));
1315        assert!(matches!(
1316            kind(
1317                Verb::Edit,
1318                &with(&|o| {
1319                    o.anchor = Some("a".into());
1320                    o.styles = vec!["bold".into(), "size=10.5".into()];
1321                })
1322            ),
1323            Ok(OperationKind::FormatRun {
1324                format: RunFormat {
1325                    bold: Some(true),
1326                    size_pt: Some(HalfPoints(21)),
1327                    ..
1328                },
1329                ..
1330            })
1331        ));
1332        assert!(matches!(
1333            kind(Verb::Edit, &with(&|o| o.styles = vec!["Heading2".into()])),
1334            Ok(OperationKind::FormatParagraph { style: Some(_), .. })
1335        ));
1336        assert!(matches!(
1337            kind(
1338                Verb::Add,
1339                &with(&|o| {
1340                    o.content = Some("New".into());
1341                    o.before = true;
1342                    o.styles = vec!["Heading2".into(), "bold".into()];
1343                })
1344            ),
1345            Ok(OperationKind::InsertParagraph {
1346                position: Side::Before,
1347                style: Some(_),
1348                ..
1349            })
1350        ));
1351        assert!(matches!(
1352            kind(
1353                Verb::Add,
1354                &with(&|o| {
1355                    o.anchor = Some("a".into());
1356                    o.content = Some("Why?".into());
1357                })
1358            ),
1359            Ok(OperationKind::Comment { find: Some(_), .. })
1360        ));
1361        assert!(matches!(
1362            kind(
1363                Verb::Add,
1364                &with(&|o| {
1365                    o.comment = true;
1366                    o.content = Some("Why?".into());
1367                })
1368            ),
1369            Ok(OperationKind::Comment { find: None, .. })
1370        ));
1371        let c5 = |f: &dyn Fn(&mut FlagOp)| {
1372            let mut o = op("c5");
1373            f(&mut o);
1374            o
1375        };
1376        assert!(matches!(
1377            kind(Verb::Add, &c5(&|o| o.content = Some("Yes.".into()))),
1378            Ok(OperationKind::ReplyComment { comment_id: 5, .. })
1379        ));
1380        assert!(matches!(
1381            kind(Verb::Edit, &c5(&|o| o.content = Some("Yes.".into()))),
1382            Ok(OperationKind::EditComment { comment_id: 5, .. })
1383        ));
1384        assert!(matches!(
1385            kind(Verb::Edit, &c5(&|o| o.delete = true)),
1386            Ok(OperationKind::DeleteComment { comment_id: 5 })
1387        ));
1388        assert!(matches!(
1389            kind(Verb::Edit, &c5(&|o| o.resolve = true)),
1390            Ok(OperationKind::ResolveComment {
1391                comment_id: 5,
1392                done: true
1393            })
1394        ));
1395    }
1396
1397    #[test]
1398    fn contradictory_flags_are_usage_errors() {
1399        let cases: Vec<(Verb, FlagOp)> = vec![
1400            (Verb::Edit, op("p1")),
1401            (
1402                Verb::Edit,
1403                FlagOp {
1404                    delete: true,
1405                    content: Some("x".into()),
1406                    ..op("p1")
1407                },
1408            ),
1409            (
1410                Verb::Edit,
1411                FlagOp {
1412                    resolve: true,
1413                    ..op("p1")
1414                },
1415            ),
1416            (
1417                Verb::Edit,
1418                FlagOp {
1419                    anchor: Some("a".into()),
1420                    content: Some("b".into()),
1421                    ..op("c0")
1422                },
1423            ),
1424            (
1425                Verb::Edit,
1426                FlagOp {
1427                    content: Some("x".into()),
1428                    styles: vec!["bold".into()],
1429                    ..op("p1")
1430                },
1431            ),
1432            (
1433                Verb::Edit,
1434                FlagOp {
1435                    styles: vec!["size=big".into()],
1436                    anchor: Some("a".into()),
1437                    ..op("p1")
1438                },
1439            ),
1440            (
1441                Verb::Edit,
1442                FlagOp {
1443                    styles: vec!["A".into(), "B".into()],
1444                    ..op("p1")
1445                },
1446            ),
1447            (Verb::Add, op("p1")),
1448            (
1449                Verb::Add,
1450                FlagOp {
1451                    anchor: Some("x".into()),
1452                    content: Some("y".into()),
1453                    before: true,
1454                    ..op("p1")
1455                },
1456            ),
1457            (
1458                Verb::Add,
1459                FlagOp {
1460                    content: Some("y".into()),
1461                    before: true,
1462                    ..op("c0")
1463                },
1464            ),
1465            (
1466                Verb::Add,
1467                FlagOp {
1468                    content: Some("y".into()),
1469                    delete: true,
1470                    ..op("p1")
1471                },
1472            ),
1473            (
1474                Verb::Edit,
1475                FlagOp {
1476                    anchor: Some("same".into()),
1477                    content: Some("same".into()),
1478                    ..op("p1")
1479                },
1480            ),
1481        ];
1482        for (verb, o) in cases {
1483            assert!(flag_operation(verb, &o).is_err(), "{verb:?} {o:?}");
1484        }
1485        assert!(plan_from_flags(Verb::Edit, &[], "A", None, None, b"").is_err());
1486    }
1487
1488    #[test]
1489    fn content_escapes_resolve_and_kept_marks_get_a_note() {
1490        let (text, note) = content_text("Fees \\* Costs");
1491        assert_eq!((text.as_str(), note), ("Fees * Costs", None));
1492        let (text, note) = content_text("**Fees**");
1493        assert_eq!(text, "**Fees**");
1494        assert!(note.is_some());
1495        // A line copied from the agent view keeps its leading space as
1496        // `&#32;`: it is a space, and no mark.
1497        let (text, note) = content_text("&#32;Fees");
1498        assert_eq!((text.as_str(), note), (" Fees", None));
1499        let plan = plan_from_flags(
1500            Verb::Edit,
1501            &[FlagOp {
1502                content: Some("**Fees**".into()),
1503                ..op("p0")
1504            }],
1505            "Redline",
1506            Some("2026-10-01T09:00:00Z"),
1507            Some(ExistingRevisions::Refuse),
1508            b"",
1509        )
1510        .unwrap();
1511        assert_eq!(
1512            plan.notes,
1513            ["op-1: content keeps its Markdown marks as text; use --style for formatting"]
1514        );
1515        assert_eq!(plan.plan.author, "Redline");
1516    }
1517
1518    fn with(at: &str, set: impl Fn(&mut FlagOp)) -> FlagOp {
1519        let mut o = op(at);
1520        set(&mut o);
1521        o
1522    }
1523
1524    /// `-p r1 --accept` and `-p header1.r2 --reject` join the plan's
1525    /// `resolve_revisions` as long ids; the other groups stay operations,
1526    /// numbered among themselves.
1527    #[test]
1528    fn revisions_go_to_resolve_revisions() {
1529        let ops = [
1530            with("r1", |o| o.accept = true),
1531            with("p0", |o| o.content = Some("**x**".into())),
1532            with("header1.r2", |o| o.reject = true),
1533            with("r3+4", |o| o.accept = true),
1534        ];
1535        let built = plan_from_flags(Verb::Edit, &ops, "A", None, None, b"").unwrap();
1536        assert_eq!(
1537            built.plan.resolve_revisions,
1538            Some(ResolveRevisions {
1539                accept: Some(ChangeFilter::ids(["r1", "r3", "r4"])),
1540                reject: Some(ChangeFilter::ids(["header1.r2"])),
1541                reject_visible: false,
1542            })
1543        );
1544        assert_eq!(built.plan.operations.len(), 1);
1545        assert_eq!(
1546            built.notes,
1547            ["op-1: content keeps its Markdown marks as text; use --style for formatting"]
1548        );
1549        let only = plan_from_flags(
1550            Verb::Edit,
1551            &[with("r7", |o| o.reject = true)],
1552            "A",
1553            None,
1554            None,
1555            b"",
1556        )
1557        .unwrap();
1558        assert!(only.plan.operations.is_empty());
1559        assert_eq!(
1560            only.plan.resolve_revisions.unwrap().reject,
1561            Some(ChangeFilter::ids(["r7"]))
1562        );
1563    }
1564
1565    /// `-p r4 --strike` and `-p r5 --restore` are operations by our
1566    /// author, with `--content` as the comment on them.
1567    #[test]
1568    fn strike_and_restore_groups_are_operations() {
1569        let built = plan_from_flags(
1570            Verb::Edit,
1571            &[
1572                with("r4", |o| {
1573                    o.strike = true;
1574                    o.content = Some("No.".into());
1575                }),
1576                with("header1.r2", |o| o.restore = true),
1577            ],
1578            "A",
1579            None,
1580            None,
1581            b"",
1582        )
1583        .unwrap();
1584        assert!(built.plan.resolve_revisions.is_none());
1585        let kinds: Vec<OperationKind> = built.plan.operations.into_iter().map(|o| o.kind).collect();
1586        assert_eq!(
1587            kinds,
1588            [
1589                OperationKind::Strike {
1590                    revision: "r4".into(),
1591                    comment: Some("No.".into()),
1592                },
1593                OperationKind::Restore {
1594                    revision: "header1.r2".into(),
1595                    comment: None,
1596                },
1597            ]
1598        );
1599    }
1600
1601    #[test]
1602    fn strike_restore_and_visible_refuse_what_they_cannot_mean() {
1603        for (verb, group, want) in [
1604            (
1605                Verb::Edit,
1606                with("r4", |o| {
1607                    o.strike = true;
1608                    o.restore = true;
1609                }),
1610                "-p r4: --strike and --restore exclude each other",
1611            ),
1612            (
1613                Verb::Edit,
1614                with("r4", |o| {
1615                    o.accept = true;
1616                    o.strike = true;
1617                }),
1618                "-p r4: --accept and --strike exclude each other",
1619            ),
1620            (
1621                Verb::Edit,
1622                with("r4", |o| o.visible = true),
1623                "-p r4: --visible goes with --reject",
1624            ),
1625            (
1626                Verb::Edit,
1627                with("p0", |o| o.strike = true),
1628                "-p p0: --strike takes a revision (-p r12)",
1629            ),
1630            (
1631                Verb::Edit,
1632                with("r4", |o| {
1633                    o.strike = true;
1634                    o.anchor = Some("x".into());
1635                }),
1636                "-p r4: a revision takes --accept, --reject, --strike or --restore",
1637            ),
1638            (
1639                Verb::Edit,
1640                with("r4", |o| {
1641                    o.reject = true;
1642                    o.content = Some("No.".into());
1643                }),
1644                "-p r4: --content on a revision is the comment of --strike, --restore or --reject --visible",
1645            ),
1646            (
1647                Verb::Add,
1648                with("r4", |o| o.strike = true),
1649                "-p r4: add resolves no revision; use edit -p r12 --accept, --reject, --strike or --restore",
1650            ),
1651        ] {
1652            let got = plan_from_flags(verb, &[group], "A", None, None, b"").map(|_| ());
1653            assert_eq!(got, Err(want.to_string()));
1654        }
1655    }
1656
1657    /// `--reply` on `edit` and `add` is the reply `add -p c5 --content`
1658    /// writes.
1659    #[test]
1660    fn reply_answers_a_comment_on_edit_and_add() {
1661        let want = kind(Verb::Add, &with("c5", |o| o.content = Some("Yes.".into()))).unwrap();
1662        for verb in [Verb::Edit, Verb::Add] {
1663            assert_eq!(
1664                kind(verb, &with("c5", |o| o.reply = Some("Yes.".into()))),
1665                Ok(want.clone()),
1666                "{verb:?}"
1667            );
1668            // 0.12's `#c5` is expired, refused with the settled spelling.
1669            let refused = kind(verb, &with("#c5", |o| o.reply = Some("Yes.".into())));
1670            assert!(
1671                refused
1672                    .as_ref()
1673                    .is_err_and(|m| m.ends_with("the settled spelling is c5")),
1674                "{refused:?}"
1675            );
1676        }
1677    }
1678
1679    #[test]
1680    fn revision_and_reply_flags_pair_only_with_their_kind() {
1681        let refusal =
1682            |verb: Verb, o: FlagOp| plan_from_flags(verb, &[o], "A", None, None, b"").unwrap_err();
1683        let cases: Vec<(FlagOp, &str)> = vec![
1684            (
1685                with("p1", |o| o.accept = true),
1686                "-p p1: --accept and --reject take a revision (-p r12)",
1687            ),
1688            (
1689                with("c5", |o| o.reject = true),
1690                "-p c5: --accept and --reject take a revision (-p r12)",
1691            ),
1692            (
1693                with("r0", |o| o.content = Some("x".into())),
1694                "-p r0: a revision takes --accept, --reject, --strike or --restore",
1695            ),
1696            (
1697                with("r0", |_| {}),
1698                "-p r0: a revision takes --accept, --reject, --strike or --restore",
1699            ),
1700            (
1701                with("r0", |o| {
1702                    o.accept = true;
1703                    o.reject = true;
1704                }),
1705                "-p r0: --accept and --reject exclude each other",
1706            ),
1707            (
1708                with("r0", |o| {
1709                    o.accept = true;
1710                    o.delete = true;
1711                }),
1712                "-p r0: a revision takes --accept, --reject, --strike or --restore",
1713            ),
1714            (
1715                with("p1", |o| o.reply = Some("x".into())),
1716                "-p p1: --reply is for a comment (-p c5)",
1717            ),
1718            (
1719                with("r1", |o| o.reply = Some("x".into())),
1720                "-p r1: --reply is for a comment (-p c5)",
1721            ),
1722            (
1723                with("c5", |o| {
1724                    o.reply = Some("x".into());
1725                    o.content = Some("y".into());
1726                }),
1727                "-p c5: --reply takes no other flag",
1728            ),
1729            (
1730                with("c5", |o| {
1731                    o.reply = Some("x".into());
1732                    o.resolve = true;
1733                }),
1734                "-p c5: --reply takes no other flag",
1735            ),
1736            (
1737                with("c5", |o| {
1738                    o.reply = Some("x".into());
1739                    o.comment = true;
1740                }),
1741                "-p c5: --reply takes no other flag",
1742            ),
1743            (
1744                with("c5", |o| {
1745                    o.reply = Some("x".into());
1746                    o.accept = true;
1747                }),
1748                "-p c5: --reply takes no other flag",
1749            ),
1750            (
1751                with("c5", |o| {
1752                    o.reply = Some("x".into());
1753                    o.reject = true;
1754                }),
1755                "-p c5: --reply takes no other flag",
1756            ),
1757        ];
1758        for (o, message) in cases {
1759            assert_eq!(refusal(Verb::Edit, o), message);
1760        }
1761        assert_eq!(
1762            refusal(
1763                Verb::Add,
1764                with("c5", |o| {
1765                    o.reply = Some("x".into());
1766                    o.before = true;
1767                })
1768            ),
1769            "-p c5: --reply takes no other flag"
1770        );
1771        for o in [
1772            with("r1", |o| o.accept = true),
1773            with("r1", |o| o.content = Some("x".into())),
1774        ] {
1775            assert_eq!(
1776                refusal(Verb::Add, o.clone()),
1777                format!(
1778                    "-p {}: add resolves no revision; use edit -p r12 --accept, --reject, --strike or --restore",
1779                    o.at
1780                )
1781            );
1782        }
1783        assert_eq!(
1784            refusal(Verb::Add, with("r1", |o| o.reply = Some("x".into()))),
1785            "-p r1: --reply is for a comment (-p c5)"
1786        );
1787        assert_eq!(
1788            refusal(Verb::Add, with("c5", |o| o.accept = true)),
1789            "-p c5: --accept and --reject take a revision (-p r12)"
1790        );
1791    }
1792}
1793
1794#[cfg(test)]
1795#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1796mod flag_branch_tests {
1797    use super::*;
1798    use crate::changes::ChangeKind;
1799
1800    fn op(at: &str) -> FlagOp {
1801        FlagOp {
1802            at: at.into(),
1803            ..FlagOp::default()
1804        }
1805    }
1806
1807    fn with(at: &str, set: impl Fn(&mut FlagOp)) -> FlagOp {
1808        let mut op = op(at);
1809        set(&mut op);
1810        op
1811    }
1812
1813    fn refused(verb: Verb, op: FlagOp) -> String {
1814        plan_from_flags(verb, &[op], "A", None, Some(ExistingRevisions::Keep), b"")
1815            .expect_err("refused")
1816    }
1817
1818    fn planned(verb: Verb, op: FlagOp) -> OperationKind {
1819        let mut plan = plan_from_flags(verb, &[op], "A", None, Some(ExistingRevisions::Keep), b"")
1820            .expect("planned")
1821            .plan;
1822        assert_eq!(plan.operations.len(), 1);
1823        plan.operations.remove(0).kind
1824    }
1825
1826    #[test]
1827    fn occurrence_needs_an_anchor_and_counts_from_one() {
1828        let e = refused(Verb::Edit, with("p1", |o| o.occurrence = Some(2)));
1829        assert_eq!(e, "-p p1: --occurrence requires --anchor");
1830        let e = refused(
1831            Verb::Edit,
1832            with("p1", |o| {
1833                o.occurrence = Some(0);
1834                o.anchor = Some("x".into());
1835                o.delete = true;
1836            }),
1837        );
1838        assert_eq!(e, "-p p1: --occurrence is 1-based");
1839    }
1840
1841    #[test]
1842    fn style_sizes_outside_the_word_range_are_refused() {
1843        for size in ["0", "-3", "1639", "NaN", "inf", "big"] {
1844            let e = refused(
1845                Verb::Edit,
1846                with("p1", |o| {
1847                    o.anchor = Some("x".into());
1848                    o.styles = vec![format!("size={size}")];
1849                }),
1850            );
1851            assert_eq!(
1852                e,
1853                format!("-p p1: --style size={size}: points between 0 and 1638")
1854            );
1855        }
1856        let kind = planned(
1857            Verb::Edit,
1858            with("p1", |o| {
1859                o.anchor = Some("x".into());
1860                o.styles = vec!["size=10.5".into()];
1861            }),
1862        );
1863        assert!(
1864            matches!(kind, OperationKind::FormatRun { ref format, .. } if format.size_pt == Some(HalfPoints(21)))
1865        );
1866    }
1867
1868    #[test]
1869    fn a_reply_takes_no_revision_flag_or_paragraph_flag() {
1870        let e = refused(
1871            Verb::Edit,
1872            with("c1", |o| {
1873                o.reply = Some("ok".into());
1874                o.visible = true;
1875            }),
1876        );
1877        assert_eq!(e, "-p c1: --reply takes no other flag");
1878        for set in [
1879            (|o: &mut FlagOp| o.delete = true) as fn(&mut FlagOp),
1880            |o| o.styles = vec!["bold".into()],
1881            |o| o.content = Some("x".into()),
1882        ] {
1883            let e = refused(
1884                Verb::Edit,
1885                with("c1", |o| {
1886                    o.reply = Some("ok".into());
1887                    set(o);
1888                }),
1889            );
1890            assert_eq!(e, "-p c1: --reply takes no other flag");
1891        }
1892    }
1893
1894    #[test]
1895    fn a_revision_group_takes_only_its_verb() {
1896        for set in [
1897            (|o: &mut FlagOp| o.resolve = true) as fn(&mut FlagOp),
1898            |o| o.before = true,
1899            |o| o.comment = true,
1900            |o| o.styles = vec!["bold".into()],
1901        ] {
1902            let e = refused(
1903                Verb::Edit,
1904                with("r1", |o| {
1905                    o.accept = true;
1906                    set(o);
1907                }),
1908            );
1909            assert_eq!(
1910                e,
1911                "-p r1: a revision takes --accept, --reject, --strike or --restore"
1912            );
1913        }
1914    }
1915
1916    #[test]
1917    fn paragraph_flags_that_contradict_each_other_are_refused() {
1918        let e = refused(Verb::Edit, op("  "));
1919        assert_eq!(e, "-p needs a location");
1920        let e = refused(
1921            Verb::Edit,
1922            with("p1", |o| {
1923                o.delete = true;
1924                o.resolve = true;
1925            }),
1926        );
1927        assert_eq!(e, "-p p1: --delete excludes --content and --resolve");
1928        for set in [
1929            (|o: &mut FlagOp| o.content = Some("x".into())) as fn(&mut FlagOp),
1930            |o| o.anchor = Some("x".into()),
1931            |o| o.styles = vec!["bold".into()],
1932        ] {
1933            let e = refused(
1934                Verb::Edit,
1935                with("p1", |o| {
1936                    o.resolve = true;
1937                    set(o);
1938                }),
1939            );
1940            assert_eq!(
1941                e,
1942                "-p p1: --resolve takes no --anchor, --content or --style"
1943            );
1944        }
1945        let e = refused(
1946            Verb::Add,
1947            with("p1", |o| {
1948                o.before = true;
1949                o.comment = true;
1950                o.content = Some("x".into());
1951            }),
1952        );
1953        assert_eq!(e, "-p p1: --before is for a new paragraph, not a comment");
1954        for set in [(|o: &mut FlagOp| o.before = true) as fn(&mut FlagOp), |o| {
1955            o.comment = true;
1956        }] {
1957            let e = refused(
1958                Verb::Edit,
1959                with("p1", |o| {
1960                    o.content = Some("x".into());
1961                    set(o);
1962                }),
1963            );
1964            assert_eq!(e, "-p p1: --before and --comment belong to add");
1965        }
1966    }
1967
1968    #[test]
1969    fn comment_groups_map_to_their_comment_operation() {
1970        for set in [(|o: &mut FlagOp| o.before = true) as fn(&mut FlagOp), |o| {
1971            o.comment = true;
1972        }] {
1973            let e = flag_operation(
1974                Verb::Add,
1975                &with("c1", |o| {
1976                    o.content = Some("x".into());
1977                    set(o);
1978                }),
1979            )
1980            .expect_err("refused");
1981            assert!(e.starts_with("-p c1"), "{e}");
1982        }
1983        let kind = planned(Verb::Edit, with("c4", |o| o.resolve = true));
1984        assert!(matches!(
1985            kind,
1986            OperationKind::ResolveComment {
1987                comment_id: 4,
1988                done: true
1989            }
1990        ));
1991    }
1992
1993    #[test]
1994    fn paragraph_styles_and_run_formats_fit_only_their_operations() {
1995        let e = refused(
1996            Verb::Edit,
1997            with("p1", |o| {
1998                o.anchor = Some("x".into());
1999                o.content = Some("y".into());
2000                o.styles = vec!["Heading1".into()];
2001            }),
2002        );
2003        assert_eq!(e, "-p p1: a paragraph style takes no --anchor");
2004        for style in ["Heading1", "bold"] {
2005            let e = refused(
2006                Verb::Edit,
2007                with("p1", |o| {
2008                    o.content = Some("y".into());
2009                    o.styles = vec![style.into()];
2010                }),
2011            );
2012            assert!(e.starts_with("-p p1: a rewrite takes no --style"), "{e}");
2013        }
2014        let e = refused(
2015            Verb::Edit,
2016            with("p1", |o| {
2017                o.delete = true;
2018                o.styles = vec!["Heading1".into()];
2019            }),
2020        );
2021        assert_eq!(e, "-p p1: --delete takes no --style");
2022    }
2023
2024    fn plan(reject: Option<ChangeFilter>, visible: bool) -> EditPlan {
2025        let mut plan = plan_from_flags(
2026            Verb::Edit,
2027            &[with("p1", |o| o.content = Some("x".into()))],
2028            "A",
2029            None,
2030            Some(ExistingRevisions::Keep),
2031            b"",
2032        )
2033        .unwrap()
2034        .plan;
2035        plan.resolve_revisions = Some(ResolveRevisions {
2036            accept: None,
2037            reject,
2038            reject_visible: visible,
2039        });
2040        plan
2041    }
2042
2043    #[test]
2044    fn recording_joins_visible_rejects_and_the_others_guard() {
2045        let ids = |v: &[&str]| {
2046            Some(ChangeFilter::ids(
2047                v.iter().map(|s| s.to_string()).collect::<Vec<String>>(),
2048            ))
2049        };
2050        // A visible reject recorded into a visible plan joins it.
2051        let merged =
2052            record_into(Some(plan(ids(&["r1"]), true)), plan(ids(&["r2"]), true)).expect("joined");
2053        let reject = merged.resolve_revisions.unwrap().reject.unwrap();
2054        assert_eq!(reject.ids.unwrap(), ["r1", "r2"]);
2055        // The others guard, once recorded, holds for the plan.
2056        let mut more = plan(None, false);
2057        more.others = super::super::Others::Keep;
2058        let merged = record_into(Some(plan(None, false)), more).unwrap();
2059        assert_eq!(merged.others, super::super::Others::Keep);
2060        // A held filter by author, by kind or of every change refuses ids.
2061        for held in [
2062            ChangeFilter {
2063                ids: Some(vec!["r1".into()]),
2064                authors: Some(vec!["Bo".into()]),
2065                kinds: None,
2066            },
2067            ChangeFilter {
2068                ids: Some(vec!["r1".into()]),
2069                authors: None,
2070                kinds: Some(vec![ChangeKind::Insertion]),
2071            },
2072            ChangeFilter::default(),
2073        ] {
2074            let e = record_into(Some(plan(Some(held), false)), plan(ids(&["r2"]), false))
2075                .expect_err("narrowing");
2076            assert!(e.starts_with("the plan's reject selects revisions"), "{e}");
2077        }
2078    }
2079}