Skip to main content

jubarte_edit/edit/
mod.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Guarded document editing for agents and tools.
6//!
7//! An [`EditPlan`](crate::edit::EditPlan) names exact, uniquely anchored operations against one
8//! snapshot of a DOCX (optionally bound to its SHA-256). Every operation is
9//! resolved against the untouched source first; any failure fails the whole
10//! plan and nothing is written. On success the operations are applied to a
11//! copy, comments are authored in that copy, and the existing comparer turns
12//! source plus copy into a Word tracked-changes document. The caller receives
13//! the clean copy, the redline and a per-operation [`EditReport`](crate::edit::EditReport).
14//!
15//! Text coordinates are the visible projection of [`crate::inspect`]: what
16//! `jubarte read --json` prints is what a plan anchors to. Replacement text is
17//! inserted into the run that held the anchor, so it inherits that run's
18//! formatting; the plan never carries raw OOXML.
19//!
20//! The CLI subcommand is `jubarte edit FILE [--plan PLAN.json]`; the bindings
21//! drive [`apply_plan`](crate::edit::apply_plan) /
22//! [`apply_plan_json`](crate::edit::apply_plan_json) directly.
23//! [`preview_plan`](crate::edit::preview_plan)
24//! resolves every operation and returns a report without producing the
25//! documents, for dry-run checks. Recording an edit from operation flags is
26//! in [`flags`](crate::edit::flags) / [`record`](crate::edit::record).
27
28use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
29use std::fmt;
30
31use serde::{Deserialize, Serialize};
32use unicode_segmentation::UnicodeSegmentation;
33
34use crate::changes::{Change, ChangeError, ChangeFilter, ChangeKind, MoveSide};
35
36#[doc(hidden)]
37pub use crate::inspect::SCHEMA_VERSION;
38use crate::inspect::{BODY_STORY, Opened, Piece, Projection, project_paragraph, source_sha256};
39use crate::namespaces::W;
40use crate::xmllinq::{Dom, NodeId, XNamespace};
41
42#[doc(hidden)]
43pub mod anchor;
44#[doc(hidden)]
45pub mod anchor_error;
46mod apply;
47mod comments;
48mod controls;
49pub mod flags;
50mod formatting;
51mod hint;
52mod images;
53mod locating;
54mod notes;
55mod origin;
56mod plan;
57/// One preparation path for dry run and apply: the chosen primary bytes
58/// and the checks the serialized candidate passes (V2-08).
59pub mod prepared;
60mod ranges;
61pub mod record;
62/// Caller-specific, neutral review choices for revision-blocked edits.
63pub mod refusal;
64mod replacement_order;
65pub mod resolution;
66mod rewrite;
67mod runs;
68pub(crate) mod sections;
69mod settlement;
70mod skip;
71mod structural;
72mod tracked;
73mod transaction;
74mod visible;
75mod watermark;
76mod whole;
77
78pub mod v2;
79use crate::comment_settlement::AnchorChanges;
80pub use crate::comment_settlement::{KeptComment, RemovedComment};
81pub mod v2_apply;
82
83/// `read --for-edit`: the working document, hashes and readiness (V2-10).
84pub mod for_edit;
85/// The one native-key policy (`w14:paraId`, revision `w:id`) shared by
86/// generation, application and the expectations checker for paired
87/// long IDs.
88pub(crate) mod native_keys;
89#[doc(hidden)]
90pub mod source_refs;
91/// Source-bound desired-text template generation over the for-edit view.
92pub mod template;
93
94/// Exact v2 literal-anchor candidates and selection; v1 retains its fallbacks.
95pub use anchor::{NearMatches, NearOccurrence, v2_candidates, v2_select, v2_select_all};
96/// v2 anchor selection with structured, bounded, actionable refusals.
97pub use anchor_error::{AnchorRefusal, Working, v2_resolve, v2_resolve_all};
98/// Which content control a `fill_control` operation fills.
99pub use controls::ControlSelector;
100/// The request syntax a refusal hint quotes (#1108).
101pub use hint::PlanSyntax;
102/// The shared preparation path [`apply_plan`] and [`preview_plan`] run.
103pub use prepared::{
104    CandidateChecks, PrepareOptions, PreparedEdit, PrimaryBytes, PrimaryRole, introduced_findings,
105    prepare, prepare_v2,
106};
107/// The `page_setup` operation's `page`, `margins_dxa`, `orientation` and
108/// `section` values.
109pub use sections::{CustomPage, Margins, Orientation, PageSize, Paper, SectionScope};
110/// `--skip-failed`: what was left out, and the plan to fix and run.
111pub use skip::{SkippedOperation, failed_plan_json, keep_notes};
112
113use apply::*;
114use comments::*;
115use formatting::*;
116use locating::*;
117use plan::*;
118use settlement::*;
119
120/// A versioned, portable set of operations against one document snapshot.
121#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
122#[serde(deny_unknown_fields)]
123pub struct EditPlan {
124    /// Wire schema version; must equal [`SCHEMA_VERSION`].
125    pub schema_version: u32,
126    /// SHA-256 of the source bytes; when present the plan is refused unless it
127    /// matches. Omit only when the caller owns the bytes end to end.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub source_sha256: Option<String>,
130    /// Revision and comment author.
131    pub author: String,
132    /// Revision and comment timestamp (`YYYY-MM-DDTHH:MM:SSZ`). When
133    /// omitted, everything the plan writes takes the time it is applied, in
134    /// UTC, as Word dates its changes; set it for reproducible output.
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub date: Option<String>,
137    /// Comment initials; derived from `author` when omitted.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub initials: Option<String>,
140    /// Tracked changes to accept and reject before anything else; the
141    /// changes it leaves follow `existing_revisions`.
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub resolve_revisions: Option<ResolveRevisions>,
144    /// Remove threads whose anchors disappear (default), or keep them on
145    /// empty, untracked anchors at the removed text's position.
146    #[serde(default, skip_serializing_if = "RemovedAnchorComments::is_remove")]
147    pub removed_anchor_comments: RemovedAnchorComments,
148    /// What to do when the source already holds tracked changes.
149    #[serde(default)]
150    pub existing_revisions: ExistingRevisions,
151    /// Operations in report order.
152    pub operations: Vec<Operation>,
153    /// Refresh `PAGEREF`, `REF`, `NUMPAGES`, `SEQ` and `TOC` results in the
154    /// edited copy from jubarte's layout (`crate::fields::update_fields`)
155    /// before the redline is compared.
156    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
157    pub update_fields: bool,
158    /// Accepted and ignored. Deleting, resolving or rewording another
159    /// author's comment is allowed unless [`Others::Keep`] is set. The
160    /// field stays so a plan that still names it parses.
161    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
162    pub rewrite_others_comments: bool,
163    /// When `keep`, refuse to erase another author's change
164    /// (`CHANGE_NOT_YOURS`) or comment (`COMMENT_NOT_YOURS`). The default
165    /// `allow` permits both. Restore, strike, a comment and a reply stay
166    /// allowed either way.
167    #[serde(default, skip_serializing_if = "Others::is_allow")]
168    pub others: Others,
169}
170
171/// Whether a plan may erase markup another author wrote.
172///
173/// Another author is anyone other than the plan's `author` (the CLI's
174/// `--author`, `Jubarte` when that is left out). A change or comment that
175/// names no author is not the plan's.
176#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
177#[serde(rename_all = "snake_case")]
178pub enum Others {
179    /// Accepting, rejecting, deleting and resolving another author's
180    /// markup is allowed.
181    #[default]
182    Allow,
183    /// Refuse those. Restore, strike, a comment and a reply stay allowed.
184    Keep,
185}
186
187impl Others {
188    /// The guard is on: do not erase another author's markup.
189    fn keeps(self) -> bool {
190        self == Self::Keep
191    }
192
193    fn is_allow(&self) -> bool {
194        *self == Self::Allow
195    }
196}
197
198/// Treatment of comment anchors removed by a plan's revision settlement.
199#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
200#[serde(rename_all = "snake_case")]
201pub enum RemovedAnchorComments {
202    /// Follow Word: remove the thread and report it.
203    #[default]
204    Remove,
205    /// Keep the thread on an empty, untracked anchor.
206    Keep,
207}
208impl RemovedAnchorComments {
209    fn is_remove(&self) -> bool {
210        *self == Self::Remove
211    }
212}
213
214/// The tracked changes a plan accepts and rejects before it edits, as
215/// Word's Accept / Reject This Change (see [`crate::changes`]). Each side
216/// is a [`ChangeFilter`]; left out, it resolves nothing. No change may be
217/// selected by both (`REVISION_CONFLICT`); both sides of a move count as
218/// one change.
219#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
220#[serde(from = "ResolveRevisionsWire", into = "ResolveRevisionsWire")]
221pub struct ResolveRevisions {
222    /// Changes to accept.
223    pub accept: Option<ChangeFilter>,
224    /// Changes to reject (after the accepted ones).
225    pub reject: Option<ChangeFilter>,
226    /// `reject.visible`: reject them visibly instead, as our tracked
227    /// changes (a `strike` of each insertion, a `restore` of each
228    /// deletion) that Reject takes back. Needs `existing_revisions` `keep`.
229    pub reject_visible: bool,
230}
231
232/// [`ResolveRevisions`] as plans write it: `visible` inside `reject`.
233#[derive(Serialize, Deserialize)]
234#[serde(deny_unknown_fields)]
235struct ResolveRevisionsWire {
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    accept: Option<ChangeFilter>,
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    reject: Option<RejectWire>,
240}
241
242/// A [`ChangeFilter`] with `visible`.
243#[derive(Serialize, Deserialize)]
244#[serde(deny_unknown_fields)]
245struct RejectWire {
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    ids: Option<Vec<String>>,
248    #[serde(default, skip_serializing_if = "Option::is_none")]
249    authors: Option<Vec<String>>,
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    kinds: Option<Vec<ChangeKind>>,
252    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
253    visible: bool,
254}
255
256impl From<ResolveRevisionsWire> for ResolveRevisions {
257    fn from(wire: ResolveRevisionsWire) -> Self {
258        let reject_visible = wire.reject.as_ref().is_some_and(|r| r.visible);
259        Self {
260            accept: wire.accept,
261            reject: wire.reject.map(|r| ChangeFilter {
262                ids: r.ids,
263                authors: r.authors,
264                kinds: r.kinds,
265            }),
266            reject_visible,
267        }
268    }
269}
270
271impl From<ResolveRevisions> for ResolveRevisionsWire {
272    fn from(selection: ResolveRevisions) -> Self {
273        Self {
274            accept: selection.accept,
275            reject: selection.reject.map(|r| RejectWire {
276                ids: r.ids,
277                authors: r.authors,
278                kinds: r.kinds,
279                visible: selection.reject_visible,
280            }),
281        }
282    }
283}
284
285/// Where a source paragraph id went when the plan's revisions were settled.
286#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
287pub struct ParagraphMove {
288    /// The id in the source (`p12`).
289    pub from: String,
290    /// The id in the output, or `null` when the paragraph is gone with its
291    /// text. A paragraph merged with others maps to the merged one.
292    pub to: Option<String>,
293}
294
295/// Another author's insertion the plan split to edit inside it (#1136):
296/// its source id and the ids its pieces carry in the redline.
297#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
298pub struct RevisionSplit {
299    /// The insertion's id in the source (`r3`).
300    pub from: String,
301    /// Its pieces' ids in the redline, in id order (`r3`, `r9`).
302    pub to: Vec<String>,
303}
304
305/// The changes `resolve_revisions` resolved, by id.
306#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
307pub struct ResolvedRevisions {
308    /// Accepted changes.
309    #[serde(default, skip_serializing_if = "Vec::is_empty")]
310    pub accepted: Vec<String>,
311    /// Rejected changes (a change an accepted one took along is not listed).
312    #[serde(default, skip_serializing_if = "Vec::is_empty")]
313    pub rejected: Vec<String>,
314}
315
316impl ResolvedRevisions {
317    /// Whether no change was accepted or rejected.
318    pub fn is_empty(&self) -> bool {
319        self.accepted.is_empty() && self.rejected.is_empty()
320    }
321}
322
323/// Policy for a source that already contains tracked changes.
324#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
325#[serde(rename_all = "snake_case")]
326pub enum ExistingRevisions {
327    /// Fail with `EXISTING_REVISIONS` (default).
328    #[default]
329    Refuse,
330    /// Accept them first; the plan then edits that accepted base.
331    Accept,
332    /// Reject them first; the plan then edits that rejected base.
333    Reject,
334    /// Leave them tracked; the plan's edits become new revisions beside them
335    /// (direct emission; no compare).
336    Keep,
337}
338
339/// One operation. `id` defaults to `op-N` (1-based) in the report.
340#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
341pub struct Operation {
342    #[serde(default, skip_serializing_if = "Option::is_none")]
343    /// Caller-chosen operation id echoed in the report.
344    pub id: Option<String>,
345    #[serde(default, skip_serializing_if = "Option::is_none")]
346    /// Operations sharing a group stand or fall together under
347    /// `--skip-failed` ([`PrepareOptions::skip_failed`]); without it a
348    /// group changes nothing.
349    pub group: Option<String>,
350    #[serde(flatten)]
351    /// The operation.
352    pub kind: OperationKind,
353}
354
355/// The supported operation kinds (wire tag `kind`).
356#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
357#[serde(tag = "kind", rename_all = "snake_case")]
358pub enum OperationKind {
359    /// Replace exactly one occurrence of `find` in the paragraph.
360    Replace {
361        /// Paragraph to edit; must match exactly one.
362        paragraph: Selector,
363        /// Exact text to locate; must occur exactly once.
364        find: String,
365        /// Replacement text (may be empty); `\t` writes a tab, `\n` a line break.
366        replacement: String,
367        #[serde(default, skip_serializing_if = "Option::is_none")]
368        /// Formatting of the replacement on top of the replaced run's.
369        format: Option<RunFormat>,
370        #[serde(
371            default,
372            deserialize_with = "blank_is_none",
373            skip_serializing_if = "Option::is_none"
374        )]
375        /// Comment text anchored to the changed text; blank is none.
376        comment: Option<String>,
377        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
378        /// Show the change as all of `find` deleted, then all of
379        /// `replacement` inserted, instead of Word Compare's word-level diff.
380        whole: bool,
381        #[serde(default, skip_serializing_if = "Option::is_none")]
382        #[schemars(range(min = 1))]
383        /// Which hit of a repeated anchor to use (1-based); required when
384        /// the anchor occurs more than once.
385        occurrence: Option<usize>,
386    },
387    /// Insert `text` after/before exactly one occurrence of an anchor, or at
388    /// the paragraph's start/end. Exactly one of `after`, `before`,
389    /// `position` must be given.
390    #[schemars(extend("oneOf" = exactly_one(&["after", "before", "position"])))]
391    Insert {
392        /// Paragraph to edit; must match exactly one.
393        paragraph: Selector,
394        #[serde(default, skip_serializing_if = "Option::is_none")]
395        /// Insert right after this unique anchor text.
396        after: Option<String>,
397        #[serde(default, skip_serializing_if = "Option::is_none")]
398        /// Insert right before this unique anchor text.
399        before: Option<String>,
400        #[serde(default, skip_serializing_if = "Option::is_none")]
401        /// Insert at the paragraph start or end.
402        position: Option<Edge>,
403        /// Text to insert; `\t` writes a tab, `\n` a line break.
404        text: String,
405        #[serde(default, skip_serializing_if = "Option::is_none")]
406        /// Formatting of the new text on top of the neighbouring run's.
407        format: Option<RunFormat>,
408        #[serde(
409            default,
410            deserialize_with = "blank_is_none",
411            skip_serializing_if = "Option::is_none"
412        )]
413        /// Comment text anchored to the changed text; blank is none.
414        comment: Option<String>,
415        #[serde(default, skip_serializing_if = "Option::is_none")]
416        #[schemars(range(min = 1))]
417        /// Which hit of a repeated anchor to use (1-based); required when
418        /// the anchor occurs more than once.
419        occurrence: Option<usize>,
420    },
421    /// Delete exactly one occurrence of `find`.
422    Delete {
423        /// Paragraph to edit; must match exactly one.
424        paragraph: Selector,
425        /// Exact text to delete; must occur exactly once.
426        find: String,
427        #[serde(default, skip_serializing_if = "Option::is_none")]
428        #[schemars(range(min = 1))]
429        /// Which hit of a repeated anchor to use (1-based); required when
430        /// the anchor occurs more than once.
431        occurrence: Option<usize>,
432        #[serde(
433            default,
434            deserialize_with = "blank_is_none",
435            skip_serializing_if = "Option::is_none"
436        )]
437        /// Comment on the deleted text, blank is none. It is in the redline
438        /// only: the clean copy no longer holds the text.
439        comment: Option<String>,
440    },
441    /// Comment on exactly one occurrence of `find`, or on the whole paragraph.
442    /// The range may cross tabs, symbols, hyperlinks, fields, content
443    /// controls and revisions: a comment edits nothing.
444    #[schemars(extend("x-jubarte-targets" = ["body", "table_cell"]))]
445    Comment {
446        /// Paragraph to edit; must match exactly one.
447        paragraph: Selector,
448        #[serde(default, skip_serializing_if = "Option::is_none")]
449        /// Text to anchor the comment to; whole paragraph when omitted.
450        find: Option<String>,
451        /// The comment, plain text; each `\n` starts a new comment paragraph.
452        text: String,
453        #[serde(default, skip_serializing_if = "Option::is_none")]
454        /// Last paragraph of a range from the start of `paragraph` to the
455        /// end of this one (same story, not before `paragraph`); `find`
456        /// must be left out.
457        through: Option<Selector>,
458        #[serde(default, skip_serializing_if = "Option::is_none")]
459        #[schemars(range(min = 1))]
460        /// Which hit of a repeated anchor to use (1-based); required when
461        /// the anchor occurs more than once.
462        occurrence: Option<usize>,
463    },
464    /// Insert a new paragraph next to the anchor paragraph, copying its
465    /// paragraph properties (never its section break or revision marks), or
466    /// those of `like`.
467    InsertParagraph {
468        /// Paragraph to edit; must match exactly one.
469        paragraph: Selector,
470        #[serde(default)]
471        /// Which side of the anchor paragraph.
472        position: Side,
473        /// Runs of the new paragraph, in order.
474        runs: Vec<RunSpec>,
475        #[serde(default, skip_serializing_if = "Option::is_none")]
476        /// Paragraph whose properties and run formatting the new paragraph
477        /// copies instead of the anchor's: a plain paragraph inserted after a
478        /// list item, for one.
479        like: Option<Selector>,
480        #[serde(default, skip_serializing_if = "Option::is_none")]
481        /// Paragraph style id to set instead of the anchor's.
482        style: Option<String>,
483        #[serde(
484            default,
485            deserialize_with = "blank_is_none",
486            skip_serializing_if = "Option::is_none"
487        )]
488        /// Comment text anchored to the changed text; blank is none.
489        comment: Option<String>,
490    },
491    /// Delete a whole paragraph, mark included.
492    DeleteParagraph {
493        /// Paragraph to delete; must match exactly one.
494        paragraph: Selector,
495        #[serde(
496            default,
497            deserialize_with = "blank_is_none",
498            skip_serializing_if = "Option::is_none"
499        )]
500        /// Comment on the deleted text, blank is none. It is in the redline
501        /// only: the clean copy has no paragraph to hold it.
502        comment: Option<String>,
503    },
504    /// Change a paragraph's style, alignment or spacing; the redline records
505    /// the old properties (`w:pPrChange`). At least one field besides
506    /// `paragraph`.
507    #[schemars(extend("anyOf" = at_least_one(&["style", "alignment", "line_spacing", "space_before", "space_after"])))]
508    FormatParagraph {
509        /// Paragraph to format; must match exactly one.
510        paragraph: Selector,
511        #[serde(default, skip_serializing_if = "Option::is_none")]
512        /// Paragraph style, by id (`Heading1`) or name (`heading 1`).
513        style: Option<String>,
514        #[serde(default, skip_serializing_if = "Option::is_none")]
515        /// Horizontal alignment.
516        alignment: Option<Alignment>,
517        #[serde(default, skip_serializing_if = "Option::is_none")]
518        /// Line spacing as a multiple of single spacing (`1.5`, `2`).
519        line_spacing: Option<LineSpacing>,
520        #[serde(default, skip_serializing_if = "Option::is_none")]
521        /// Space before the paragraph, in points.
522        space_before: Option<Points>,
523        #[serde(default, skip_serializing_if = "Option::is_none")]
524        /// Space after the paragraph, in points.
525        space_after: Option<Points>,
526    },
527    /// Join the paragraph with the one right after it. The first's text moves
528    /// to the start of the second, whose paragraph properties (and section
529    /// break) survive, as when Word accepts a deleted paragraph mark. The
530    /// redline deletes the first paragraph's mark.
531    MergeParagraphs {
532        /// First paragraph; the next paragraph must follow it directly.
533        paragraph: Selector,
534        #[serde(default, skip_serializing_if = "Option::is_none")]
535        /// Plain text placed between the two (for example `" "`).
536        separator: Option<String>,
537    },
538    /// Make the paragraph read as `text`: the engine applies the smallest
539    /// word-level edits, so unchanged words keep their runs and formatting,
540    /// and new words take the formatting of the run before them. A tab or a
541    /// line break the paragraph has may be written as a space and stays; a
542    /// `\t` or `\n` in `text` writes one. Symbols stay where they are and
543    /// may be left out of `text`.
544    Rewrite {
545        /// Paragraph to rewrite; must match exactly one.
546        paragraph: Selector,
547        /// The paragraph's new text, plain.
548        text: String,
549        #[serde(
550            default,
551            deserialize_with = "blank_is_none",
552            skip_serializing_if = "Option::is_none"
553        )]
554        /// Comment on the rewritten paragraph, blank is none.
555        comment: Option<String>,
556    },
557    /// Reply to comment `comment_id`, as the plan's author; the reply is
558    /// anchored on the same range. Word threads are one level deep, so a
559    /// reply to a reply joins the thread's first comment.
560    ReplyComment {
561        /// `w:id` of the comment replied to (`jubarte comments` lists them):
562        /// a number, or `"c27"`.
563        #[serde(deserialize_with = "crate::ids::comment_id_de")]
564        #[schemars(with = "crate::ids::RawCommentId")]
565        comment_id: u32,
566        /// Reply text; `\n` starts a new line.
567        text: String,
568    },
569    /// Resolve comment `comment_id` and its replies (`done: false` opens
570    /// them again).
571    ResolveComment {
572        /// `w:id` of the comment: a number, or `"c27"`.
573        #[serde(deserialize_with = "crate::ids::comment_id_de")]
574        #[schemars(with = "crate::ids::RawCommentId")]
575        comment_id: u32,
576        #[serde(default = "resolve_done")]
577        /// Resolved (default) or open.
578        done: bool,
579    },
580    /// Replace the text of comment `comment_id`; its id, author, date and
581    /// thread stay.
582    EditComment {
583        /// `w:id` of the comment: a number, or `"c27"`.
584        #[serde(deserialize_with = "crate::ids::comment_id_de")]
585        #[schemars(with = "crate::ids::RawCommentId")]
586        comment_id: u32,
587        /// New text; `\n` starts a new line.
588        text: String,
589    },
590    /// Remove comment `comment_id`, its replies, their range markers and
591    /// references.
592    DeleteComment {
593        /// `w:id` of the comment: a number, or `"c27"`.
594        #[serde(deserialize_with = "crate::ids::comment_id_de")]
595        #[schemars(with = "crate::ids::RawCommentId")]
596        comment_id: u32,
597    },
598    /// Reject another author's insertion visibly: our tracked deletion of
599    /// its words, nested inside it, so Word shows it struck under our name
600    /// and Reject of our change gives it back. Needs `existing_revisions`
601    /// `keep`.
602    #[schemars(extend("x-jubarte-keep-only" = true))]
603    Strike {
604        /// The insertion, as `changes` lists it (`r366`, `header1.r3`): every
605        /// insertion mark of a change of several (`r10+11`), a replacement's
606        /// insertion only.
607        revision: String,
608        #[serde(
609            default,
610            deserialize_with = "blank_is_none",
611            skip_serializing_if = "Option::is_none"
612        )]
613        /// Comment on the struck words; blank is none.
614        comment: Option<String>,
615    },
616    /// Reject another author's deletion visibly: their deletion stays, and
617    /// our tracked insertion right after it holds a copy of its words,
618    /// formatting included. Needs `existing_revisions` `keep`.
619    #[schemars(extend("x-jubarte-keep-only" = true))]
620    Restore {
621        /// The deletion, as `changes` lists it (`r12`, `header1.r3`): every
622        /// deletion mark of a change of several (`r12+13`), a replacement's
623        /// deletion only.
624        revision: String,
625        #[serde(
626            default,
627            deserialize_with = "blank_is_none",
628            skip_serializing_if = "Option::is_none"
629        )]
630        /// Comment on the restored words; blank is none.
631        comment: Option<String>,
632    },
633    /// Insert a table next to the anchor paragraph. Each cell holds one
634    /// paragraph in the anchor's paragraph style; the redline shows the
635    /// rows inserted. Body paragraphs outside tables only.
636    #[schemars(extend("x-jubarte-targets" = ["body"]))]
637    InsertTable {
638        /// Anchor paragraph; must match exactly one.
639        paragraph: Selector,
640        #[serde(default)]
641        /// Which side of the anchor paragraph.
642        position: Side,
643        /// Cell text, row by row; every row has the same number of cells.
644        rows: Vec<Vec<String>>,
645        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
646        /// Mark the first row as a header row that repeats on each page.
647        header_row: bool,
648        #[serde(default, skip_serializing_if = "Option::is_none")]
649        #[schemars(inner(range(min = 1, max = structural::MAX_WIDTH_DXA)))]
650        /// Column widths in twentieths of a point; the text width split
651        /// evenly when omitted.
652        widths_dxa: Option<Vec<u32>>,
653        #[serde(default, skip_serializing_if = "Option::is_none")]
654        /// Table style, by id or name; `TableGrid` (added when the document
655        /// lacks it) when omitted.
656        style: Option<String>,
657    },
658    /// Make the paragraphs a list: each gets direct numbering at `level`,
659    /// and `ListParagraph` when it has no style. The redline records each
660    /// paragraph's old properties (`w:pPrChange`).
661    #[schemars(extend("x-jubarte-targets" = ["body", "table_cell"]))]
662    List {
663        /// Paragraphs to number, each selector matching exactly one; body
664        /// only.
665        paragraphs: Vec<Selector>,
666        #[serde(default)]
667        /// Bullets, decimal numbers or lowercase letters.
668        kind_of_list: ListKind,
669        #[serde(default)]
670        #[schemars(range(min = 0, max = 8))]
671        /// List level, 0 (outermost) to 8.
672        level: u32,
673        #[serde(default = "default_true")]
674        /// Start a new list (true), or continue the list of the nearest
675        /// numbered paragraph before the first one, in that list's format.
676        restart: bool,
677    },
678    /// Write Word's own text watermark (Insert > Watermark) into every
679    /// default header, creating a header where the first section has none.
680    /// One per document. It is header content, not a tracked change: the
681    /// clean copy and the redline both carry it.
682    Watermark {
683        #[schemars(length(min = 1, max = watermark::MAX_TEXT))]
684        /// The watermark text, plain, 1 to 64 characters.
685        text: String,
686        #[serde(default, skip_serializing_if = "Option::is_none")]
687        /// Fill colour, six hex digits (default `C0C0C0`).
688        color: Option<String>,
689        #[serde(default, skip_serializing_if = "Option::is_none")]
690        /// Diagonal at 315 degrees (default); `false` lays it horizontal.
691        diagonal: Option<bool>,
692        #[serde(default, skip_serializing_if = "Option::is_none")]
693        /// Font family (default `Calibri`).
694        font: Option<String>,
695    },
696    /// Fill one content control (`w:sdt`) in the body with exactly one of
697    /// `text`, `choice`, `checked` or `date`. The control keeps its
698    /// properties; its content becomes the value.
699    #[schemars(extend("x-jubarte-keep" = false), extend("oneOf" = exactly_one(&["text", "choice", "checked", "date"])))]
700    FillControl {
701        /// The control: `"p3.cc0"` / `"cc1"`, `{"id"}`, `{"tag"}` or `{"alias"}`;
702        /// must match exactly one.
703        control: ControlSelector,
704        #[serde(default, skip_serializing_if = "Option::is_none")]
705        /// Plain text, for text, rich-text and combo-box controls.
706        text: Option<String>,
707        #[serde(default, skip_serializing_if = "Option::is_none")]
708        /// A list item's value or display text, for drop-down and combo-box
709        /// controls; the display text is written.
710        choice: Option<String>,
711        #[serde(default, skip_serializing_if = "Option::is_none")]
712        /// Checkbox state.
713        checked: Option<bool>,
714        #[serde(default, skip_serializing_if = "Option::is_none")]
715        /// `YYYY-MM-DD`, for date controls; written in the control's format.
716        date: Option<String>,
717    },
718    /// Change the run formatting of one occurrence of existing text; the
719    /// redline records the old formatting (`w:rPrChange`).
720    FormatRun {
721        /// Paragraph to format; must match exactly one.
722        paragraph: Selector,
723        /// Exact text to format.
724        find: String,
725        /// Formatting to set; fields not given stay as they are.
726        format: RunFormat,
727        #[serde(default, skip_serializing_if = "Option::is_none")]
728        #[schemars(range(min = 1))]
729        /// Which occurrence of `find` (1-based) when it occurs more than once.
730        occurrence: Option<usize>,
731    },
732    /// Insert a footnote whose reference mark follows one occurrence of
733    /// `after`; the note goes in the footnotes part, created when absent.
734    #[schemars(extend("x-jubarte-targets" = ["body", "table_cell"]), extend("x-jubarte-keep" = false))]
735    InsertFootnote {
736        /// Body paragraph to edit; must match exactly one.
737        paragraph: Selector,
738        /// The reference mark goes right after this anchor text.
739        after: String,
740        /// Plain text of the note.
741        text: String,
742        #[serde(default, skip_serializing_if = "Option::is_none")]
743        #[schemars(range(min = 1))]
744        /// Which occurrence of `after` (1-based) when it occurs more than once.
745        occurrence: Option<usize>,
746    },
747    /// Insert a paragraph holding one inline picture next to the anchor
748    /// paragraph. PNG, JPEG, GIF, BMP or TIFF.
749    #[schemars(extend("x-jubarte-targets" = ["body", "table_cell"]), extend("x-jubarte-keep" = false))]
750    InsertImage {
751        /// Body paragraph the picture goes next to; must match exactly one.
752        paragraph: Selector,
753        #[serde(default)]
754        /// Which side of the anchor paragraph.
755        position: Side,
756        /// The picture file, base64-encoded.
757        image_base64: String,
758        #[serde(default, skip_serializing_if = "Option::is_none")]
759        /// The picture's media type; checked against its bytes when given.
760        content_type: Option<String>,
761        #[serde(default, skip_serializing_if = "Option::is_none")]
762        #[schemars(range(min = 1, max = images::MAX_WIDTH_EMU))]
763        /// Width in EMU (914400 per inch); the height keeps the aspect
764        /// ratio. Default: the pixel size at 96 dpi, at most 6.5 inches.
765        width_emu: Option<u64>,
766        #[serde(default, skip_serializing_if = "Option::is_none")]
767        /// Alternative text (`wp:docPr descr`).
768        alt: Option<String>,
769    },
770    /// Set the page size, orientation and margins of the last section or of
771    /// every section; the redline records the old ones (`w:sectPrChange`).
772    /// At least one of `page`, `orientation`, `margins_dxa`.
773    #[schemars(extend("x-jubarte-keep" = false), extend("anyOf" = at_least_one(&["page", "orientation", "margins_dxa"])))]
774    PageSetup {
775        #[serde(default)]
776        /// `last` (default) or `all`.
777        section: SectionScope,
778        #[serde(default, skip_serializing_if = "Option::is_none")]
779        /// `letter`, `a4`, or `{"width_dxa", "height_dxa"}`.
780        page: Option<PageSize>,
781        #[serde(default, skip_serializing_if = "Option::is_none")]
782        /// `portrait` or `landscape`.
783        orientation: Option<Orientation>,
784        #[serde(default, skip_serializing_if = "is_default_margins")]
785        /// Margins to change, in twentieths of a point.
786        margins_dxa: Margins,
787    },
788    /// Insert a table of contents next to the anchor paragraph: a `TOC \o
789    /// "1-{levels}" \h \z \u` field, after an optional title paragraph
790    /// styled `TOCHeading`. Its entries are written when the plan sets
791    /// `update_fields`; otherwise the field is empty until Word updates it.
792    #[schemars(extend("x-jubarte-targets" = ["body", "table_cell"]))]
793    InsertToc {
794        /// Paragraph to insert next to; must match exactly one, in the body.
795        paragraph: Selector,
796        #[serde(default)]
797        /// Which side of the anchor paragraph.
798        position: Side,
799        #[serde(default = "default_toc_levels")]
800        #[schemars(range(min = 1, max = 9))]
801        /// Heading levels listed, 1 to 9 (default 3).
802        levels: u8,
803        #[serde(default, skip_serializing_if = "Option::is_none")]
804        /// Title paragraph above the TOC (`"Contents"`).
805        title: Option<String>,
806    },
807    /// Replace one occurrence of `find` with one full block
808    /// (U+2588) per character, untracked: the clean copy and the redline
809    /// both show the blocks and neither keeps the text. The plan is refused
810    /// with `REDACTION_LEAK` when the text still occurs anywhere in either
811    /// output, and with `REDACTION_INCOMPLETE` when a part uses an encoding
812    /// the scan does not certify. The report never repeats the text.
813    Redact {
814        /// Paragraph to redact in; must match exactly one.
815        paragraph: Selector,
816        /// Exact text to remove.
817        find: String,
818        #[serde(default, skip_serializing_if = "Option::is_none")]
819        #[schemars(range(min = 1))]
820        /// Which occurrence of `find` (1-based) when it occurs more than once.
821        occurrence: Option<usize>,
822    },
823    /// Write document settings into `word/settings.xml` in schema order:
824    /// Track Changes, update fields on open, editing restrictions. Settings
825    /// are not revisions: the clean copy and the redline both carry them.
826    /// One per plan; a setting left out stays as it is.
827    #[schemars(extend("anyOf" = at_least_one(&["track_revisions", "update_fields", "protection"])))]
828    Settings {
829        #[serde(default, skip_serializing_if = "Option::is_none")]
830        /// Turn Track Changes on (`w:trackRevisions`) or off.
831        track_revisions: Option<bool>,
832        #[serde(default, skip_serializing_if = "Option::is_none")]
833        /// Ask Word to update fields on open (`w:updateFields`), or not. The
834        /// plan's own `update_fields` writes jubarte's results instead.
835        update_fields: Option<bool>,
836        #[serde(default, skip_serializing_if = "Option::is_none")]
837        /// Restrict editing (`w:documentProtection`); `edit: none` lifts it.
838        protection: Option<crate::settings::Protection>,
839    },
840}
841
842fn default_toc_levels() -> u8 {
843    3
844}
845
846fn is_default_margins(margins: &Margins) -> bool {
847    *margins == Margins::default()
848}
849
850fn resolve_done() -> bool {
851    true
852}
853
854fn default_true() -> bool {
855    true
856}
857
858/// The numbering of a [`OperationKind::List`].
859#[derive(
860    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
861)]
862#[serde(rename_all = "snake_case")]
863pub enum ListKind {
864    #[default]
865    /// `•`, `◦`, `▪` by level.
866    Bullet,
867    /// `1.`, `2.`, ...
868    Decimal,
869    /// `a.`, `b.`, ...
870    LowerLetter,
871}
872
873impl ListKind {
874    fn format(self) -> crate::markdown::xml::ListFormat {
875        use crate::markdown::xml::ListFormat;
876        match self {
877            Self::Bullet => ListFormat::Bullet,
878            Self::Decimal => ListFormat::Decimal,
879            Self::LowerLetter => ListFormat::LowerLetter,
880        }
881    }
882
883    fn name(self) -> &'static str {
884        match self {
885            Self::Bullet => "bullet",
886            Self::Decimal => "decimal",
887            Self::LowerLetter => "lower_letter",
888        }
889    }
890}
891
892/// Line spacing, stored as `w:line` (240 = single); JSON is the multiple.
893#[derive(Clone, Copy, Debug, PartialEq, Eq, schemars::JsonSchema)]
894#[schemars(transparent)]
895pub struct LineSpacing(#[schemars(with = "f64", range(min = 0.25, max = 10.0))] pub u32);
896
897impl Serialize for LineSpacing {
898    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
899        s.serialize_f64(f64::from(self.0) / 240.0)
900    }
901}
902
903impl<'de> Deserialize<'de> for LineSpacing {
904    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
905        let multiple = f64::deserialize(d)?;
906        if !(0.25..=10.0).contains(&multiple) {
907            return Err(serde::de::Error::custom(format!(
908                "line_spacing {multiple} is outside 0.25..=10"
909            )));
910        }
911        Ok(Self((multiple * 240.0).round() as u32))
912    }
913}
914
915/// A length stored in twips (1/20 pt); JSON is points.
916#[derive(Clone, Copy, Debug, PartialEq, Eq, schemars::JsonSchema)]
917#[schemars(transparent)]
918pub struct Points(#[schemars(with = "f64", range(min = 0.0, max = 1584.0))] pub u32);
919
920impl Serialize for Points {
921    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
922        s.serialize_f64(f64::from(self.0) / 20.0)
923    }
924}
925
926impl<'de> Deserialize<'de> for Points {
927    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
928        let points = f64::deserialize(d)?;
929        if !(0.0..=1584.0).contains(&points) {
930            return Err(serde::de::Error::custom(format!(
931                "spacing {points}pt is outside 0..=1584"
932            )));
933        }
934        Ok(Self((points * 20.0).round() as u32))
935    }
936}
937
938/// Paragraph spacing changes for [`OperationKind::FormatParagraph`].
939#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
940#[doc(hidden)]
941pub struct Spacing {
942    line: Option<LineSpacing>,
943    before: Option<Points>,
944    after: Option<Points>,
945}
946
947/// Paragraph alignment for [`OperationKind::FormatParagraph`].
948#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
949#[serde(rename_all = "snake_case")]
950pub enum Alignment {
951    /// Left (start) aligned.
952    Left,
953    /// Centered.
954    Center,
955    /// Right (end) aligned.
956    Right,
957    /// Justified.
958    Justify,
959}
960
961impl Alignment {
962    /// The `w:jc` value Word writes.
963    fn jc(self) -> &'static str {
964        match self {
965            Self::Left => "left",
966            Self::Center => "center",
967            Self::Right => "right",
968            Self::Justify => "both",
969        }
970    }
971}
972
973/// Run formatting for inserted or replacement text. Fields not given keep
974/// the neighbouring run's formatting.
975#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
976#[serde(deny_unknown_fields)]
977pub struct RunFormat {
978    #[serde(default, skip_serializing_if = "Option::is_none")]
979    /// Set or clear bold.
980    pub bold: Option<bool>,
981    #[serde(default, skip_serializing_if = "Option::is_none")]
982    /// Set or clear italic.
983    pub italic: Option<bool>,
984    #[serde(default, skip_serializing_if = "Option::is_none")]
985    /// Set or clear single underline.
986    pub underline: Option<bool>,
987    #[serde(default, skip_serializing_if = "Option::is_none")]
988    /// Highlight color name (`yellow`, ...) or `none`.
989    pub highlight: Option<String>,
990    #[serde(default, skip_serializing_if = "Option::is_none")]
991    /// Font name, set for every script (`w:rFonts`).
992    pub font: Option<String>,
993    #[serde(default, skip_serializing_if = "Option::is_none")]
994    /// Font size in points, rounded to half points.
995    pub size_pt: Option<HalfPoints>,
996    #[serde(default, skip_serializing_if = "Option::is_none")]
997    /// Text colour as six hex digits (`FF0000`) or `auto`.
998    pub color: Option<String>,
999    #[serde(default, skip_serializing_if = "Option::is_none")]
1000    /// Set or clear single strikethrough.
1001    pub strike: Option<bool>,
1002    #[serde(default, skip_serializing_if = "Option::is_none")]
1003    /// Set or clear all caps.
1004    pub caps: Option<bool>,
1005}
1006
1007/// A font size stored in half points (`w:sz`); JSON is points.
1008#[derive(Clone, Copy, Debug, PartialEq, Eq, schemars::JsonSchema)]
1009#[schemars(transparent)]
1010pub struct HalfPoints(#[schemars(with = "f64", range(min = 0.0, max = 1638.0))] pub u32);
1011
1012impl Serialize for HalfPoints {
1013    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1014        s.serialize_f64(f64::from(self.0) / 2.0)
1015    }
1016}
1017
1018impl<'de> Deserialize<'de> for HalfPoints {
1019    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1020        let points = f64::deserialize(d)?;
1021        if !points.is_finite() || !(0.0..=1638.0).contains(&points) {
1022            return Err(serde::de::Error::custom(format!(
1023                "size_pt {points} is outside 0..=1638"
1024            )));
1025        }
1026        Ok(Self((points * 2.0).round() as u32))
1027    }
1028}
1029
1030/// Paragraph edge for an insertion without a text anchor.
1031#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
1032#[serde(rename_all = "snake_case")]
1033pub enum Edge {
1034    /// Paragraph start.
1035    Start,
1036    /// Paragraph end.
1037    End,
1038}
1039
1040/// Side of the anchor paragraph for [`OperationKind::InsertParagraph`].
1041#[derive(
1042    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
1043)]
1044#[serde(rename_all = "snake_case")]
1045pub enum Side {
1046    /// Before the anchor paragraph.
1047    Before,
1048    #[default]
1049    /// After the anchor paragraph.
1050    After,
1051}
1052
1053/// Paragraph selector; every form must match exactly one paragraph. Ids
1054/// are the agent view's (`p3`, `header1`, `header1.p1`, `footnotes.p2`,
1055/// `t0.row1.cell2`, `t0.row1.cell2.p1`); the old `body:p:3` is refused,
1056/// naming its settled spelling, and the report prints the same ids
1057/// ([`crate::ids::paragraph_id`]). The other forms search
1058/// the body unless they carry a `story` (`header1`, `footnotes`, ...).
1059///
1060/// Ids, short ids and indexes name the source's paragraphs, the ones the
1061/// plan's author read, even when `resolve_revisions` or `existing_revisions`
1062/// settles changes first; the text forms search the settled text. An edit
1063/// anchored on text follows a paragraph into the one it merged with, and so
1064/// does a whole-paragraph edit when that paragraph has no other source; a
1065/// whole-paragraph edit of a paragraph merged with others, or of a vanished
1066/// one, is refused.
1067#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
1068#[serde(untagged, deny_unknown_fields)]
1069pub enum Selector {
1070    /// `"p12"`, the same as `{"id": "p12"}`.
1071    Name(String),
1072    /// `{"id": "p12"}`.
1073    Id {
1074        /// `p12`, `header1.p1`, `t0.row1.cell2`.
1075        id: String,
1076    },
1077    /// `{"index": 12}`.
1078    Index {
1079        /// Zero-based index in the story.
1080        index: usize,
1081        #[serde(default, skip_serializing_if = "Option::is_none")]
1082        /// Story to search; the body when omitted.
1083        story: Option<String>,
1084    },
1085    /// `{"starts_with": "..."}`; unique prefix match.
1086    StartsWith {
1087        /// Unique paragraph text prefix.
1088        starts_with: String,
1089        #[serde(default, skip_serializing_if = "Option::is_none")]
1090        /// Story to search; the body when omitted.
1091        story: Option<String>,
1092    },
1093    /// `{"contains": "..."}`; unique substring match.
1094    Contains {
1095        /// Unique paragraph text substring.
1096        contains: String,
1097        #[serde(default, skip_serializing_if = "Option::is_none")]
1098        /// Story to search; the body when omitted.
1099        story: Option<String>,
1100    },
1101}
1102
1103/// A run of an inserted paragraph. Formatting not given is inherited from the
1104/// anchor paragraph's first run.
1105#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
1106#[serde(deny_unknown_fields)]
1107pub struct RunSpec {
1108    /// Run text.
1109    pub text: String,
1110    #[serde(default, skip_serializing_if = "Option::is_none")]
1111    /// Set or clear bold.
1112    pub bold: Option<bool>,
1113    #[serde(default, skip_serializing_if = "Option::is_none")]
1114    /// Set or clear italic.
1115    pub italic: Option<bool>,
1116    #[serde(default, skip_serializing_if = "Option::is_none")]
1117    /// Set or clear single underline.
1118    pub underline: Option<bool>,
1119    #[serde(default, skip_serializing_if = "Option::is_none")]
1120    /// Highlight color name (`yellow`, ...) or `none`.
1121    pub highlight: Option<String>,
1122}
1123
1124impl RunSpec {
1125    /// The run's formatting toggles.
1126    pub fn format(&self) -> RunFormat {
1127        RunFormat {
1128            bold: self.bold,
1129            italic: self.italic,
1130            underline: self.underline,
1131            highlight: self.highlight.clone(),
1132            ..RunFormat::default()
1133        }
1134    }
1135}
1136
1137/// A paragraph an anchor does occur in, named by the `ANCHOR_NOT_FOUND`
1138/// that refused it elsewhere (#1889): the id the views print and a
1139/// bounded excerpt of the paragraph's text. A suggestion to read and
1140/// re-address, never a retarget (#957).
1141#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1142pub struct AnchorCandidate {
1143    /// Paragraph id as the views print it (`p53`, `header1.p1`).
1144    pub at: String,
1145    /// A grapheme-safe excerpt around the match, with ellipses at cuts.
1146    pub ctx: String,
1147}
1148
1149/// Outcome of one operation.
1150#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1151pub struct EditOutcome {
1152    /// Operation id (`op-N` when the plan gave none).
1153    pub id: String,
1154    /// Operation kind.
1155    pub kind: String,
1156    /// `ok`, `failed`, or `skipped` (not reached because an earlier
1157    /// operation failed the plan).
1158    pub status: String,
1159    #[serde(default, skip_serializing_if = "Option::is_none")]
1160    /// Resolved paragraph id.
1161    pub paragraph: Option<String>,
1162    /// Anchor occurrences found (1 on success).
1163    pub matches: usize,
1164    /// `before {old→new} after`, `{+inserted}`, `{-deleted}`.
1165    #[serde(default, skip_serializing_if = "Option::is_none")]
1166    pub context: Option<String>,
1167    #[serde(default, skip_serializing_if = "Option::is_none")]
1168    /// Comment id written for this operation.
1169    pub comment_id: Option<u32>,
1170    #[serde(default, skip_serializing_if = "Option::is_none")]
1171    /// The anchor as the plan wrote it, when it matched only without its
1172    /// Markdown marks, or only as it reads: a space for a non-breaking
1173    /// one, straight quotes for curly ones, `-` for a non-breaking hyphen,
1174    /// zero-width characters left out.
1175    pub anchor_given: Option<String>,
1176    #[serde(default, skip_serializing_if = "Option::is_none")]
1177    /// The paragraph's text actually matched in that case.
1178    pub anchor_read_as: Option<String>,
1179    /// Report-only whitespace occurrences when the literal anchor was refused.
1180    #[serde(default, skip_serializing_if = "Option::is_none")]
1181    pub near: Option<NearMatches>,
1182    /// Paragraphs the anchor does occur in when the named paragraph does
1183    /// not hold it (#1889); empty on every other outcome.
1184    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1185    pub candidates: Vec<AnchorCandidate>,
1186    #[serde(default, skip_serializing_if = "Option::is_none")]
1187    /// Error code when failed.
1188    pub code: Option<String>,
1189    #[serde(default, skip_serializing_if = "Option::is_none")]
1190    /// Error message when failed; on an `ok` operation, a note that it
1191    /// could not be shown as asked (a `whole` replacement kept word-level).
1192    pub message: Option<String>,
1193}
1194
1195/// The redline's changes by kind, as `jubarte changes` lists them.
1196#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1197pub struct RevisionCounts {
1198    /// Insertions.
1199    pub inserted: usize,
1200    /// Deletions.
1201    pub deleted: usize,
1202    /// Moves.
1203    pub moved: usize,
1204    /// Formatting changes: run, paragraph, section, table and style
1205    /// properties.
1206    pub format_changed: usize,
1207    /// Replacements: a deletion and the insertion that replaces it, listed
1208    /// as one change ([`ChangeKind::Replacement`]).
1209    #[serde(default)]
1210    pub replaced: usize,
1211    /// All changes, each logical change once (#1261: a change of several
1212    /// marks, or a replacement, counts one): the sum of the counts above.
1213    pub total: usize,
1214}
1215
1216impl RevisionCounts {
1217    /// The counts of `changes`, one per listed change.
1218    fn from_changes<'a>(changes: impl IntoIterator<Item = &'a Change>) -> Self {
1219        let mut counts = Self::default();
1220        for change in changes {
1221            let slot = match change.kind {
1222                ChangeKind::Insertion => &mut counts.inserted,
1223                ChangeKind::Deletion => &mut counts.deleted,
1224                ChangeKind::Move => &mut counts.moved,
1225                ChangeKind::Formatting => &mut counts.format_changed,
1226                ChangeKind::Replacement => &mut counts.replaced,
1227            };
1228            *slot += 1;
1229            counts.total += 1;
1230        }
1231        counts
1232    }
1233}
1234
1235/// Paragraph count before and after.
1236#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1237pub struct ParagraphDelta {
1238    /// Before the plan.
1239    pub from: usize,
1240    /// After the plan.
1241    pub to: usize,
1242}
1243
1244/// What happened, per operation and overall.
1245#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1246pub struct EditReport {
1247    /// Wire schema version; must equal [`SCHEMA_VERSION`].
1248    pub schema_version: u32,
1249    /// Every operation succeeded.
1250    pub ok: bool,
1251    /// SHA-256 of the bytes handed in.
1252    pub source_sha256: String,
1253    /// SHA-256 of the base the plan edited. It differs from `source_sha256`
1254    /// when existing revisions were flattened first, and when a repeated
1255    /// permission id was normalized on a revision-free source.
1256    pub base_sha256: String,
1257    /// The plan carried a `source_sha256` that was verified.
1258    pub guarded: bool,
1259    /// Revision and comment author.
1260    pub author: String,
1261    /// Revision and comment timestamp used.
1262    pub date: String,
1263    /// Policy that was applied.
1264    pub existing_revisions: ExistingRevisions,
1265    /// Changes `resolve_revisions` accepted and rejected.
1266    #[serde(default, skip_serializing_if = "ResolvedRevisions::is_empty")]
1267    pub resolved_revisions: ResolvedRevisions,
1268    /// Threads removed with the settled text, in source comment ids.
1269    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1270    pub removed_comments: Vec<RemovedComment>,
1271    /// Threads the clean copy drops that the redline still carries, in
1272    /// source comment ids. Editing mode publishes that copy, so its
1273    /// receipt names these. Suggesting mode keeps them on the redline.
1274    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1275    pub clean_removed_comments: Vec<RemovedComment>,
1276    /// Threads moved onto empty anchors by opt-in settlement, excluding
1277    /// comments and replies subsequently deleted by the plan.
1278    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1279    pub kept_comments: Vec<KeptComment>,
1280    /// Source paragraph ids that name another paragraph once the plan's
1281    /// revisions are settled (`resolve_revisions`, `existing_revisions`
1282    /// accept or reject), in source order. Operations still address the
1283    /// source's ids; the output documents carry these.
1284    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1285    pub paragraph_ids: Vec<ParagraphMove>,
1286    /// Other authors' insertions the redline splits, by source id.
1287    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1288    pub split_revisions: Vec<RevisionSplit>,
1289    /// Body paragraph count before and after.
1290    pub paragraphs: ParagraphDelta,
1291    /// One outcome per operation, in plan order.
1292    pub operations: Vec<EditOutcome>,
1293    /// Comments written by this plan.
1294    pub comments_added: usize,
1295    /// Zero until the redline exists (a preview never compares).
1296    pub revisions: RevisionCounts,
1297    /// Fields whose results `update_fields` wrote into the clean copy.
1298    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1299    #[cfg(feature = "render")]
1300    pub fields: Vec<crate::fields::FieldUpdate>,
1301    /// Operations `--skip-failed` left out (status `skipped`); `ok` is
1302    /// false whenever one was.
1303    #[serde(default, skip_serializing_if = "is_zero")]
1304    pub skipped: usize,
1305    /// What the plan said that jubarte read another way (`anchor` read as
1306    /// `find`, …): the CLI prints each as a `note:` line.
1307    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1308    pub notes: Vec<String>,
1309    /// SHA-256 of the document written, set by whoever writes it (the
1310    /// CLI): the bytes a follow-up plan binds to.
1311    #[serde(default, skip_serializing_if = "Option::is_none")]
1312    pub output_sha256: Option<String>,
1313}
1314
1315fn is_zero(n: &usize) -> bool {
1316    *n == 0
1317}
1318
1319impl EditReport {
1320    /// JSON lines an agent can append to its own log: `load`, one `op` per
1321    /// operation, `summary`.
1322    pub fn to_jsonl(&self) -> String {
1323        let mut out = String::new();
1324        let mut push = |v: serde_json::Value| {
1325            out.push_str(&v.to_string());
1326            out.push('\n');
1327        };
1328        let mut load = serde_json::json!({
1329            "ev": "load",
1330            "sha256": self.source_sha256,
1331            "base_sha256": self.base_sha256,
1332            "guarded": self.guarded,
1333            "paras": self.paragraphs.from,
1334            "author": self.author,
1335            "date": self.date,
1336            "existing_revisions": self.existing_revisions,
1337        });
1338        if !self.resolved_revisions.is_empty() {
1339            load.as_object_mut().expect("object").insert(
1340                "resolved_revisions".into(),
1341                serde_json::to_value(&self.resolved_revisions).expect("serializes"),
1342            );
1343        }
1344        if !self.paragraph_ids.is_empty() {
1345            load.as_object_mut().expect("object").insert(
1346                "paragraph_ids".into(),
1347                serde_json::to_value(&self.paragraph_ids).expect("serializes"),
1348            );
1349        }
1350        push(load);
1351        for (i, op) in self.operations.iter().enumerate() {
1352            let mut v = serde_json::json!({
1353                "ev": "op",
1354                "i": i + 1,
1355                "id": op.id,
1356                "op": op.kind,
1357                "status": op.status,
1358                "matches": op.matches,
1359            });
1360            let map = v.as_object_mut().expect("object");
1361            if let Some(p) = &op.paragraph {
1362                map.insert("at".into(), p.clone().into());
1363            }
1364            if let Some(c) = &op.context {
1365                map.insert("ctx".into(), c.clone().into());
1366            }
1367            if let Some(c) = op.comment_id {
1368                map.insert("comment_id".into(), c.into());
1369            }
1370            if let Some(given) = &op.anchor_given {
1371                map.insert("anchor_given".into(), given.clone().into());
1372            }
1373            if let Some(read_as) = &op.anchor_read_as {
1374                map.insert("anchor_read_as".into(), read_as.clone().into());
1375            }
1376            if let Some(near) = &op.near {
1377                map.insert(
1378                    "near".into(),
1379                    serde_json::to_value(near).expect("near serializes"),
1380                );
1381            }
1382            if !op.candidates.is_empty() {
1383                map.insert(
1384                    "candidates".into(),
1385                    serde_json::to_value(&op.candidates).expect("candidates serialize"),
1386                );
1387            }
1388            if let Some(c) = &op.code {
1389                map.insert("code".into(), c.clone().into());
1390            }
1391            if let Some(m) = &op.message {
1392                map.insert("message".into(), m.clone().into());
1393            }
1394            push(v);
1395        }
1396        let failed = self
1397            .operations
1398            .iter()
1399            .filter(|o| o.status == "failed")
1400            .count();
1401        let ok = self.operations.iter().filter(|o| o.status == "ok").count();
1402        // Under --skip-failed the operations that passed landed: partial.
1403        let status = match (self.ok, self.skipped) {
1404            (true, _) => "ok",
1405            (false, 0) => "failed",
1406            (false, _) if ok > 0 => "partial",
1407            (false, _) => "failed",
1408        };
1409        let mut ops = serde_json::json!({"ok": ok, "failed": failed});
1410        if self.skipped > 0 {
1411            ops["skipped"] = self.skipped.into();
1412        }
1413        let mut summary = serde_json::json!({
1414            "ev": "summary",
1415            "status": status,
1416            "ops": ops,
1417            "paras": {"from": self.paragraphs.from, "to": self.paragraphs.to,
1418                      "d": self.paragraphs.to as i64 - self.paragraphs.from as i64},
1419            "revs": self.revisions,
1420            "comments": {"added": self.comments_added},
1421            "removed_comments": self.removed_comments,
1422            "kept_comments": self.kept_comments,
1423        });
1424        if !self.split_revisions.is_empty() {
1425            summary.as_object_mut().expect("object").insert(
1426                "split_revisions".into(),
1427                serde_json::to_value(&self.split_revisions).expect("serializes"),
1428            );
1429        }
1430        if let Some(digest) = &self.output_sha256 {
1431            summary["output_sha256"] = digest.clone().into();
1432        }
1433        if !self.notes.is_empty() {
1434            summary["notes"] = self.notes.clone().into();
1435        }
1436        if !self.clean_removed_comments.is_empty() {
1437            summary["clean_removed_comments"] =
1438                serde_json::to_value(&self.clean_removed_comments).expect("serializes");
1439        }
1440        push(summary);
1441        out
1442    }
1443}
1444
1445/// Clean copy, redline and report.
1446#[derive(Clone, Debug, PartialEq, Eq)]
1447pub struct EditResult {
1448    /// The edited document without tracked changes.
1449    pub clean: Vec<u8>,
1450    /// Source compared against the clean copy: Word tracked changes.
1451    pub redline: Vec<u8>,
1452    /// Per-operation outcomes and totals.
1453    pub report: EditReport,
1454}
1455
1456#[cfg(test)]
1457thread_local! {
1458    static COMMENT_MARK_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1459}
1460
1461/// Stable engine code for comment mapping conflicts, independent of prose.
1462const COMMENT_ANCHOR_CONFLICT: &str = "COMMENT_ANCHOR_CONFLICT";
1463
1464/// Why a plan was refused. `outcomes` lists every operation's status so the
1465/// caller can see which anchors resolved before the failure.
1466#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1467pub struct EditError {
1468    /// Stable error code (`STALE_SOURCE`, `AMBIGUOUS_ANCHOR`, ...).
1469    pub code: String,
1470    #[serde(default, skip_serializing_if = "Option::is_none")]
1471    /// Operation id that failed, when one did.
1472    pub operation: Option<String>,
1473    /// Human-readable detail.
1474    pub message: String,
1475    #[serde(default)]
1476    /// Status of every operation at the time of failure.
1477    pub outcomes: Vec<EditOutcome>,
1478    /// Report-only whitespace occurrences; never used to resolve an operation.
1479    #[serde(default, skip_serializing_if = "Option::is_none")]
1480    pub near: Option<Box<NearMatches>>,
1481    /// Blocking revision identities and both review choices, when applicable.
1482    #[serde(
1483        default,
1484        skip_serializing_if = "<[refusal::RevisionRefusal]>::is_empty"
1485    )]
1486    pub revision_refusals: Box<[refusal::RevisionRefusal]>,
1487}
1488
1489impl fmt::Display for EditError {
1490    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1491        match &self.operation {
1492            Some(op) => write!(f, "{} ({op}): {}", self.code, self.message),
1493            None => write!(f, "{}: {}", self.code, self.message),
1494        }
1495    }
1496}
1497
1498impl std::error::Error for EditError {}
1499
1500/// The prefix of a style's change id (`styles.r0`, as `changes` lists it):
1501/// a style's recorded formatting does not make the text tracked (#1885).
1502const STYLES_STORY: &str = "styles.";
1503
1504/// What an `EXISTING_REVISIONS` refusal, and a guard that would erase
1505/// every tracked change, tells the caller to write instead.
1506const KEEP_REVISIONS: &str = concat!(
1507    r#"add "existing_revisions": "keep" to the plan "#,
1508    "(it keeps every tracked change, yours and theirs; accept and reject resolve them all first)"
1509);
1510
1511/// Whether `source` still carries a tracked change of its text (body,
1512/// headers, footers, notes; a style's recorded formatting is not one) once
1513/// `plan`'s `resolve_revisions` has accepted and rejected what it selects.
1514/// A selection that does not resolve is the plan's error, reported when it
1515/// runs; here it leaves every change in place.
1516fn revisions_left(source: &[u8], plan: &EditPlan) -> bool {
1517    let resolved = resolve_selected(
1518        source,
1519        plan.resolve_revisions.as_ref(),
1520        plan.removed_anchor_comments,
1521        PlanSyntax::V1,
1522    )
1523    .ok()
1524    .and_then(|(bytes, _, _)| bytes);
1525    crate::changes::list_changes(resolved.as_deref().unwrap_or(source))
1526        .is_ok_and(|changes| changes.iter().any(|c| !c.id.starts_with(STYLES_STORY)))
1527}
1528
1529/// The replies `plan` makes to a comment on a paragraph it deletes, each
1530/// as the parent's id and the deleted paragraph's id. Tracked, the reply
1531/// sits on the struck text; untracked, as `--editing-mode` publishes the
1532/// edit, the paragraph and the thread are gone and the reply lands nowhere.
1533/// A plan that does not resolve names none here: running it reports why.
1534pub fn replies_on_deleted_paragraphs(source: &[u8], plan: &EditPlan) -> Vec<(u32, Option<String>)> {
1535    let Ok(lowered) = visible::lower(source, plan, PlanSyntax::V1) else {
1536        return Vec::new();
1537    };
1538    let plan = lowered.as_ref().unwrap_or(plan);
1539    let Ok(tx) = resolved(source, plan, PlanSyntax::V1) else {
1540        return Vec::new();
1541    };
1542    (0..plan.operations.len())
1543        .filter_map(|op| tx.reply_on_deleted(op))
1544        .map(|(parent, by)| (parent, tx.outcomes[by].paragraph.clone()))
1545        .collect()
1546}
1547
1548/// Refuse to erase another author's tracked change when the plan keeps
1549/// others' markup (`CHANGE_NOT_YOURS`). A style's recorded formatting is
1550/// not one (#1885). A visible reject settles nothing, so it is not one
1551/// either. `wholesale` is `"accept"` or `"reject"` when `existing_revisions`
1552/// would resolve every change the selection leaves.
1553///
1554/// A decision that removes content is also refused when a revision nested
1555/// inside it, or a comment anchor it holds, belongs to someone else
1556/// (`COMMENT_NOT_YOURS` for the comment). Comment-body revisions are listed
1557/// as `comments.rN` (#1706), so a comment-only file holds tracked changes.
1558/// `settle_comment_bodies` still loads that part when a settlement resolves
1559/// it and the listing has no other text change.
1560fn guard_keep_others(
1561    source: &[u8],
1562    author: &str,
1563    selection: Option<&ResolveRevisions>,
1564    wholesale: Option<&str>,
1565    settle_comment_bodies: bool,
1566    syntax: PlanSyntax,
1567) -> Result<(), EditError> {
1568    if selection.is_none() && wholesale.is_none() {
1569        return Ok(());
1570    }
1571    let listed =
1572        crate::changes::list_changes(source).map_err(|e| selection_error(e, syntax, ""))?;
1573    if let Some(selection) = selection {
1574        let accept = selected_ids(&listed, selection.accept.as_ref(), syntax)?;
1575        let reject = if selection.reject_visible {
1576            Vec::new()
1577        } else {
1578            selected_ids(&listed, selection.reject.as_ref(), syntax)?
1579        };
1580        let mut removals = Vec::new();
1581        for (id, accepting) in accept
1582            .iter()
1583            .map(|id| (id, true))
1584            .chain(reject.iter().map(|id| (id, false)))
1585        {
1586            let Some(change) = listed.iter().find(|c| &c.id == id) else {
1587                continue;
1588            };
1589            if change.id.starts_with(STYLES_STORY) {
1590                continue;
1591            }
1592            if !owns_change(change.author.as_deref(), author) {
1593                return Err(err("CHANGE_NOT_YOURS", None, change_not_yours(change)));
1594            }
1595            if !removes_content(change, accepting) {
1596                continue;
1597            }
1598            let nested = taken_along(&listed, change);
1599            if let Some(foreign) = nested
1600                .iter()
1601                .find(|inner| !owns_change(inner.author.as_deref(), author))
1602            {
1603                return Err(err("CHANGE_NOT_YOURS", None, change_not_yours(foreign)));
1604            }
1605            removals.push((change, accepting, nested));
1606        }
1607        guard_removed_comments(source, author, &removals)?;
1608    }
1609    let Some(policy) = wholesale else {
1610        return Ok(());
1611    };
1612    // Comment-body revisions are in `listed` as `comments.rN` (#1706).
1613    // Also count the comments part when this settlement resolves it and
1614    // the listing has not already got a text change (a style-only file).
1615    let comment_changes =
1616        if settle_comment_bodies || listed.iter().any(|c| !c.id.starts_with(STYLES_STORY)) {
1617            let opened = Opened::open(source).map_err(open_error)?;
1618            crate::changes::comment_changes_in(&opened.pkg)
1619        } else {
1620            Vec::new()
1621        };
1622    let mut authors = Vec::new();
1623    let mut nameless = false;
1624    for change in listed.iter().chain(&comment_changes) {
1625        note_foreign(change, author, &mut authors, &mut nameless);
1626    }
1627    if authors.is_empty() && !nameless {
1628        return Ok(());
1629    }
1630    Err(err(
1631        "CHANGE_NOT_YOURS",
1632        None,
1633        format!(
1634            r#""existing_revisions": "{policy}" would erase changes by {}; {KEEP_REVISIONS}"#,
1635            join_authors(&authors, nameless)
1636        ),
1637    ))
1638}
1639
1640/// The paragraph id ([`crate::ids::paragraph_id`]) each of `ids` names in
1641/// `docx`, as `edit -p` reads it on a document without tracked changes to
1642/// settle: `p3` and `header1.p1` as given, `header1.p0` → `header1`,
1643/// `t0.row1.cell2[.p1]` → that cell's paragraph (`p40`). An id that names
1644/// no table cell or story of `docx`, or is no paragraph id, gives its `Err`
1645/// message, as `edit -p` does; the old `body:p:3` gives its settled
1646/// spelling. A body or story index is not checked against the paragraph
1647/// count.
1648pub fn paragraph_ids(docx: &[u8], ids: &[&str]) -> Result<Vec<Result<String, String>>, EditError> {
1649    let mut opened = Opened::open(docx).map_err(open_error)?;
1650    let Loaded {
1651        stories,
1652        paragraph_nodes,
1653        paragraph_story,
1654    } = load_stories(&mut opened)?;
1655    let resolver = origin::Ids {
1656        dom: &opened.dom,
1657        body: opened.body,
1658        story_ids: stories.iter().map(|s| s.id.as_str()).collect(),
1659        paragraph_nodes: &paragraph_nodes,
1660        paragraph_story: &paragraph_story,
1661    };
1662    Ok(ids
1663        .iter()
1664        .map(|id| match resolver.paragraph_id(id) {
1665            Some(found) => found,
1666            None => match id.rsplit_once(":p:") {
1667                Some((story, n)) if n.parse::<usize>().is_ok() => {
1668                    if resolver.story_ids.contains(&story) {
1669                        Ok(id.to_string())
1670                    } else {
1671                        Err(format!(
1672                            "unknown story {story:?}; this document has {}",
1673                            resolver.story_ids.join(", ")
1674                        ))
1675                    }
1676                }
1677                Some(_) => Err(format!("unknown paragraph id {id}")),
1678                None => Err(format!("{id} is not a paragraph id")),
1679            },
1680        })
1681        .collect())
1682}
1683
1684impl From<crate::comment_settlement::SettlementError> for EditError {
1685    fn from(error: crate::comment_settlement::SettlementError) -> Self {
1686        err(&error.code, None, error.message)
1687    }
1688}
1689
1690fn err(code: &str, operation: Option<&str>, message: impl Into<String>) -> EditError {
1691    EditError {
1692        code: code.to_string(),
1693        operation: operation.map(str::to_string),
1694        message: message.into(),
1695        outcomes: Vec::new(),
1696        near: None,
1697        revision_refusals: Box::default(),
1698    }
1699}
1700
1701/// The legacy dispatcher contract, derived from its typed Serde operations.
1702/// Native, Python and WASM all dispatch through `apply_plan_json` / `apply_plan`.
1703/// The parser's key gate and capability discovery share these exact field facts.
1704pub(crate) fn operation_schemas() -> &'static [serde_json::Value] {
1705    static SCHEMAS: std::sync::LazyLock<Vec<serde_json::Value>> = std::sync::LazyLock::new(|| {
1706        let settings = schemars::generate::SchemaSettings::draft2020_12()
1707            .with(|s| s.inline_subschemas = true)
1708            .for_deserialize();
1709        let common = settings
1710            .clone()
1711            .into_generator()
1712            .into_root_schema_for::<Operation>();
1713        let common = serde_json::to_value(common).expect("common schema serializes");
1714        let schema = settings
1715            .into_generator()
1716            .into_root_schema_for::<OperationKind>();
1717        let value = serde_json::to_value(schema).expect("operation schema serializes");
1718        let mut variants = value["oneOf"]
1719            .as_array()
1720            .expect("tagged operation variants")
1721            .clone();
1722        for variant in &mut variants {
1723            variant["properties"]["id"] = common["properties"]["id"].clone();
1724            variant["properties"]["group"] = common["properties"]["group"].clone();
1725            // A failed plan's note; read and ignored.
1726            variant["properties"]["why"] = serde_json::json!({
1727                "type": "string",
1728                "description": "Why `--skip-failed` left this operation out; ignored."
1729            });
1730            // Closed as `check_operation_keys` is: a key outside these
1731            // properties (besides the flattened `id`) is an error, not a
1732            // silently ignored extra.
1733            variant["additionalProperties"] = serde_json::json!(false);
1734        }
1735        variants
1736    });
1737    &SCHEMAS
1738}
1739
1740/// Names accepted by the common v1 dispatcher, in the legacy manifest order.
1741pub fn dispatched_operation_kinds() -> Vec<String> {
1742    operation_schemas()
1743        .iter()
1744        .map(|schema| {
1745            schema["properties"]["kind"]["const"]
1746                .as_str()
1747                .expect("operation tag")
1748                .to_string()
1749        })
1750        .collect()
1751}
1752
1753/// The operation answers another author's revision beside it, so it runs
1754/// only when the plan keeps revisions (`strike`, `restore`).
1755pub(crate) fn operation_needs_keep(kind: &str) -> bool {
1756    operation_schemas()
1757        .iter()
1758        .find(|s| s["properties"]["kind"]["const"] == kind)
1759        .is_some_and(|s| s["x-jubarte-keep-only"] == true)
1760}
1761
1762pub(crate) fn operation_supports_keep(kind: &str) -> bool {
1763    operation_schemas()
1764        .iter()
1765        .find(|s| s["properties"]["kind"]["const"] == kind)
1766        .is_some_and(|s| s["x-jubarte-keep"] != false)
1767}
1768
1769/// Apply a plan given as JSON: [`EditPlan::from_json_with_notes`], then
1770/// [`apply_plan`]; the report's `notes` name each field read as another.
1771///
1772/// # Errors
1773///
1774/// `INVALID_PLAN` and `UNSUPPORTED_SCHEMA` from parsing the plan, and every
1775/// error [`apply_plan`] reports.
1776pub fn apply_plan_json(source: &[u8], plan_json: &str) -> Result<EditResult, EditError> {
1777    apply_plan_json_with(source, plan_json, &PrepareOptions::default())
1778}
1779
1780/// [`apply_plan_json`] with the shared preparation's options:
1781/// `require_change` and `exact_text` reach the JSON callers the CLI
1782/// already exposes.
1783///
1784/// # Errors
1785///
1786/// As [`apply_plan_json`], plus `NO_CHANGES_REQUESTED` under
1787/// [`PrepareOptions::require_change`] and the [`PrepareOptions::exact_text`]
1788/// form of `POSTCONDITION_FAILED`.
1789pub fn apply_plan_json_with(
1790    source: &[u8],
1791    plan_json: &str,
1792    options: &PrepareOptions,
1793) -> Result<EditResult, EditError> {
1794    let (plan, mut notes) = EditPlan::from_json_with_notes(plan_json)?;
1795    let mut result = prepared::prepare(source, &plan, options)?.result;
1796    notes.append(&mut result.report.notes);
1797    result.report.notes = notes;
1798    Ok(result)
1799}
1800
1801/// Resolve and apply the plan; compare source and copy into a redline.
1802/// Text replacements use Word's typing order: deletion before insertion.
1803/// The public document comparer retains Word Compare's insertion-first order.
1804///
1805/// Nothing is written: the clean copy, the redline and the report are
1806/// returned in memory for the caller (the CLI) to write.
1807///
1808/// # Errors
1809///
1810/// `STALE_SOURCE` when `source` mismatches the plan's `source_sha256`, and
1811/// `UNSUPPORTED_SCHEMA` when its `schema_version` differs; `INVALID_PLAN`
1812/// when the plan itself is invalid (an empty author, `update_fields` with
1813/// kept revisions); `UNSUPPORTED_PACKAGE` for a signed or macro-bearing
1814/// source. `INVALID_DOCUMENT` when the source cannot be read; the admission
1815/// code (`INPUT_LIMIT`, …) when it is refused before parsing.
1816/// `EXISTING_REVISIONS`, `REVISION_CONFLICT`, `UNKNOWN_CHANGE` and
1817/// `AMBIGUOUS_CHANGE` while settling revisions; `ANCHOR_NOT_FOUND`,
1818/// `AMBIGUOUS_ANCHOR`, `INVALID_EDIT`, `UNKNOWN_STYLE`, `UNKNOWN_COMMENT`,
1819/// `COMMENT_NOT_YOURS`, `LOCKED_CONTROL`, `COMMENT_NOT_IN_BODY`,
1820/// `PARAGRAPH_RESOLVED`, `OVERLAPPING_EDITS`, `UNSUPPORTED_STRUCTURE` and
1821/// `UNSUPPORTED_IMAGE`
1822/// while resolving and applying operations; `UNSUPPORTED` for a `settings`
1823/// operation with a protection password. `FIELDS_FAILED` when field
1824/// results cannot be refreshed, `COMPARE_FAILED` when the redline cannot be
1825/// compared, `PACKAGE_WRITE` when it cannot be packaged, and
1826/// `REDACTION_LEAK` when redacted text still occurs in an output.
1827pub fn apply_plan(source: &[u8], plan: &EditPlan) -> Result<EditResult, EditError> {
1828    prepared::prepare(source, plan, &PrepareOptions::default()).map(|p| p.result)
1829}
1830
1831/// `update_fields` refreshes the clean copy the comparer reads. Under
1832/// `existing_revisions: "keep"` the redline replays the edits instead, so a
1833/// refreshed clean copy would no longer be the accepted redline.
1834fn check_update_fields(plan: &EditPlan) -> Result<(), EditError> {
1835    if plan.update_fields && plan.existing_revisions == ExistingRevisions::Keep {
1836        return Err(err(
1837            "INVALID_PLAN",
1838            None,
1839            "update_fields cannot be combined with existing_revisions \"keep\"; refresh the fields with `jubarte convert FILE --update-fields -o OUT.docx` after accepting or rejecting the kept changes",
1840        ));
1841    }
1842    Ok(())
1843}
1844
1845/// Resolve every operation and run the plan's checks, without applying
1846/// it: what `add --plan` runs on each recorded operation, so recording a
1847/// long plan never re-applies it.
1848pub fn check_plan(source: &[u8], plan: &EditPlan) -> Result<(), EditError> {
1849    check_plan_quoting(source, plan, PlanSyntax::V1)
1850}
1851
1852/// [`check_plan`], its refusals quoting their routes in `syntax`: the
1853/// flags `add --plan` records come back as flags.
1854pub fn check_plan_quoting(
1855    source: &[u8],
1856    plan: &EditPlan,
1857    syntax: PlanSyntax,
1858) -> Result<(), EditError> {
1859    let lowered = visible::lower(source, plan, syntax)?;
1860    resolved(source, lowered.as_ref().unwrap_or(plan), syntax).map(|_| ())
1861}
1862
1863fn resolved<'a>(
1864    source: &'a [u8],
1865    plan: &'a EditPlan,
1866    syntax: PlanSyntax,
1867) -> Result<Transaction<'a>, EditError> {
1868    check_update_fields(plan)?;
1869    let mut tx = Transaction::start_quoting(source, plan, syntax)?;
1870    tx.resolve()?;
1871    tracked::check(&tx)?;
1872    tx.emits_directly()?;
1873    Ok(tx)
1874}
1875
1876/// Resolve every operation without producing documents.
1877pub fn preview_plan(source: &[u8], plan: &EditPlan) -> Result<EditReport, EditError> {
1878    preview_plan_with(source, plan, &PrepareOptions::default())
1879}
1880
1881/// [`preview_plan`] with the shared preparation's options: the dry run
1882/// prepares and checks the same serialized candidate as an apply and stops
1883/// before publication.
1884pub fn preview_plan_with(
1885    source: &[u8],
1886    plan: &EditPlan,
1887    options: &PrepareOptions,
1888) -> Result<EditReport, EditError> {
1889    // One preparation, resolved once: the dry run's report is the apply's
1890    // own report — outcomes (comment ids among them), paragraphs, revisions
1891    // and comments_added all come from the produced candidate. `fields`
1892    // keeps its v1 dry-run meaning: a preview never publishes the clean
1893    // copy the refreshes land in, so it reports none.
1894    let report = prepared::prepare(source, plan, options)?.result.report;
1895    #[cfg(feature = "render")]
1896    let report = EditReport {
1897        fields: Vec::new(),
1898        ..report
1899    };
1900    Ok(report)
1901}
1902
1903/// The comparer's redline holds this edit's changes only: all of them.
1904fn revision_counts(redline: &[u8]) -> RevisionCounts {
1905    RevisionCounts::from_changes(&crate::changes::list_logical_changes(redline).unwrap_or_default())
1906}
1907
1908/// A text edit scheduled on one paragraph, in source projection bytes.
1909#[derive(Clone, Debug)]
1910struct ScheduledEdit {
1911    start: usize,
1912    end: usize,
1913    /// Index of the operation in the plan.
1914    op: usize,
1915    replacement: String,
1916    attach_before: bool,
1917    comment: Option<String>,
1918    format: Option<RunFormat>,
1919}
1920
1921/// A resolved operation, in source coordinates (bytes of the projection).
1922#[derive(Clone, Debug)]
1923#[doc(hidden)]
1924pub enum Resolved {
1925    Text {
1926        para: usize,
1927        start: usize,
1928        end: usize,
1929        /// Replacement text (may be empty); `\t` writes a tab, `\n` a line break.
1930        replacement: String,
1931        /// Comment text anchored to the changed text.
1932        comment: Option<String>,
1933        /// `Insert` attaches to the preceding run when true.
1934        attach_before: bool,
1935        /// Formatting of the new text.
1936        format: Option<RunFormat>,
1937    },
1938    CommentRange {
1939        para: usize,
1940        start: usize,
1941        end: usize,
1942        /// The comment, plain text; each `\n` starts a new comment paragraph.
1943        text: String,
1944    },
1945    DeleteParagraph {
1946        para: usize,
1947    },
1948    FormatParagraph {
1949        para: usize,
1950        /// Resolved style id.
1951        style: Option<String>,
1952        alignment: Option<Alignment>,
1953        spacing: Spacing,
1954    },
1955    MergeParagraphs {
1956        para: usize,
1957        next: usize,
1958        separator: String,
1959        /// A `strike` of another author's inserted mark: under keep, our
1960        /// deletion joins their insertion in the mark.
1961        strike: bool,
1962    },
1963    InsertParagraph {
1964        anchor: usize,
1965        side: Side,
1966        /// Runs of the new paragraph, in order.
1967        runs: Vec<RunSpec>,
1968        /// The paragraph whose properties it copies.
1969        like: usize,
1970        /// Paragraph style id to set instead of the anchor's.
1971        style: Option<String>,
1972        /// Comment text anchored to the changed text.
1973        comment: Option<String>,
1974        /// `insert_toc`: the paragraphs are the TOC field (and its title),
1975        /// not `runs`.
1976        toc: Option<TocSpec>,
1977        /// A `restore` of another author's deleted mark: the new paragraph
1978        /// keeps `like`'s mark formatting too, as the break it gives back.
1979        keep_mark: bool,
1980    },
1981    InsertTable {
1982        anchor: usize,
1983        side: Side,
1984        rows: Vec<Vec<String>>,
1985        header_row: bool,
1986        /// One width per column, in twentieths of a point.
1987        widths: Vec<u32>,
1988        /// Resolved table style id.
1989        style: String,
1990        /// The style's definition must be added to the styles part.
1991        add_style: bool,
1992    },
1993    List {
1994        /// Paragraphs to number, in plan order.
1995        paras: Vec<usize>,
1996        kind: ListKind,
1997        level: u32,
1998        /// The `w:numId` to continue, or a new list when `None`.
1999        join: Option<String>,
2000        /// The document's "List Paragraph" style id, for unstyled items.
2001        style: String,
2002        /// That style's definition must be added to the styles part.
2003        add_style: bool,
2004    },
2005    /// A comment from the start of `para` to the end of `last`.
2006    CommentSpan {
2007        para: usize,
2008        last: usize,
2009        /// Comment text.
2010        text: String,
2011    },
2012    /// A reply to, resolution, edit or deletion of an existing comment.
2013    Thread {
2014        op: ThreadOp,
2015        /// Stories whose markers the operation adds to or removes.
2016        stories: Vec<usize>,
2017        /// Paragraph holding the target comment's reference, when found.
2018        anchor: Option<usize>,
2019    },
2020    FillControl {
2021        /// Index into `Transaction::controls`.
2022        control: usize,
2023        /// The paragraphs it spans (or the one holding it).
2024        paragraphs: Vec<usize>,
2025        /// The control holds paragraphs rather than runs.
2026        block: bool,
2027        value: controls::FillValue,
2028    },
2029    FormatRun {
2030        para: usize,
2031        start: usize,
2032        end: usize,
2033        format: RunFormat,
2034    },
2035    InsertFootnote {
2036        para: usize,
2037        /// Projection offset the reference mark follows.
2038        at: usize,
2039        text: String,
2040    },
2041    InsertImage {
2042        anchor: usize,
2043        side: Side,
2044        picture: crate::markdown::Picture,
2045    },
2046    PageSetup {
2047        targets: sections::Targets,
2048    },
2049    /// The comment of a `strike` or a `delete`, on the words `[start, end)`
2050    /// of `para` (source offsets) it deletes: anchored before they are
2051    /// deleted, in the redline only, as a commented paragraph deletion's.
2052    StrikeComment {
2053        para: usize,
2054        start: usize,
2055        end: usize,
2056    },
2057    /// A `restore`: plain copies of deletion `wid`'s runs right after it
2058    /// (projection offset `at`), inserted as ours in the redline.
2059    Restore {
2060        para: usize,
2061        /// The deletion's `w:id`.
2062        wid: String,
2063        at: usize,
2064        /// The copies' text, as the projection reads it.
2065        text: String,
2066        /// Comment text anchored on the copies.
2067        comment: Option<String>,
2068    },
2069}
2070
2071/// What a thread operation does to an existing comment.
2072#[derive(Clone, Debug)]
2073#[doc(hidden)]
2074pub enum ThreadOp {
2075    Reply { parent: u32, text: String },
2076    Resolve { id: u32, done: bool },
2077    Edit { id: u32, text: String },
2078    Delete { id: u32 },
2079}
2080
2081impl ThreadOp {
2082    /// The existing comment the operation acts on.
2083    fn target(&self) -> u32 {
2084        match self {
2085            ThreadOp::Reply { parent: id, .. }
2086            | ThreadOp::Resolve { id, .. }
2087            | ThreadOp::Edit { id, .. }
2088            | ThreadOp::Delete { id } => *id,
2089        }
2090    }
2091}
2092
2093/// A comment of another author a thread operation changes. With
2094/// [`Others::Keep`] it is refused (`COMMENT_NOT_YOURS`); otherwise the
2095/// report notes it (#1264, #1846, #1892).
2096#[derive(Clone, Debug)]
2097#[doc(hidden)]
2098pub struct OthersComment {
2099    /// The comment changed.
2100    comment: u32,
2101    /// Its author; `""` when it names none.
2102    author: String,
2103    change: OthersChange,
2104}
2105
2106#[derive(Clone, Copy, Debug)]
2107enum OthersChange {
2108    Reword,
2109    Delete,
2110    Resolve,
2111    Reopen,
2112    /// A reply deleted with the plan author's own comment, the root given.
2113    DeletedWith(u32),
2114}
2115
2116impl OthersComment {
2117    /// The refusal: reply, or resolve your own thread when a delete would
2118    /// take their reply. `reply` and `resolve` are spelled for the plan's
2119    /// syntax. Accepting the rewrite flag does not change this.
2120    fn refusal(&self, reply: &str, resolve: &str) -> String {
2121        let (comment, author) = (self.comment, &self.author);
2122        if let OthersChange::DeletedWith(root) = self.change {
2123            let whose = if author.is_empty() {
2124                "a reply that names no author".to_string()
2125            } else {
2126                format!("a reply by {author:?}")
2127            };
2128            return format!(
2129                "deleting c{root} deletes c{comment}, {whose}; resolve c{root} instead ({resolve})"
2130            );
2131        }
2132        format!("{}; reply instead ({reply})", self.whose())
2133    }
2134
2135    /// The report's note when the operation changed another author's comment.
2136    fn note(&self) -> String {
2137        let named = !self.author.is_empty();
2138        let what = match (self.change, named) {
2139            (OthersChange::Reword, true) => "their words were changed under their name".into(),
2140            (OthersChange::Reword, false) => "its words were changed".into(),
2141            (OthersChange::Delete, true) => "their comment was deleted".into(),
2142            (OthersChange::Resolve, true) => "their comment was resolved".into(),
2143            (OthersChange::Reopen, true) => "their comment was reopened".into(),
2144            (OthersChange::Delete, false) => "it was deleted".into(),
2145            (OthersChange::Resolve, false) => "it was resolved".into(),
2146            (OthersChange::Reopen, false) => "it was reopened".into(),
2147            (OthersChange::DeletedWith(root), true) => {
2148                format!("their reply was deleted with c{root}")
2149            }
2150            (OthersChange::DeletedWith(root), false) => format!("it was deleted with c{root}"),
2151        };
2152        format!("{}; {what}", self.whose())
2153    }
2154
2155    /// `c5 is by "Bob"`, or `c5 names no author`.
2156    fn whose(&self) -> String {
2157        if self.author.is_empty() {
2158            format!("c{} names no author", self.comment)
2159        } else {
2160            format!("c{} is by {:?}", self.comment, self.author)
2161        }
2162    }
2163}
2164
2165/// A resolved `insert_toc`.
2166#[derive(Clone, Debug)]
2167#[doc(hidden)]
2168pub struct TocSpec {
2169    levels: u8,
2170    title: Option<String>,
2171}
2172
2173/// What resolving an operation gives: its resolved form and outcome, or the
2174/// error with the outcome so far.
2175type Resolution<T> = Result<(T, EditOutcome), Box<(EditError, EditOutcome)>>;
2176
2177/// The text a comment covers: from `start` in paragraph `first` to `end` in
2178/// paragraph `last` (projection offsets; global paragraph indexes).
2179#[derive(Clone, Copy, Debug)]
2180struct Covered {
2181    first: usize,
2182    start: usize,
2183    last: usize,
2184    end: usize,
2185}
2186
2187#[doc(hidden)]
2188pub struct Transaction<'p> {
2189    pub plan: &'p EditPlan,
2190    pub revision_refusal: std::cell::RefCell<Option<refusal::RevisionRefusal>>,
2191    pub source_sha256: String,
2192    pub base: Vec<u8>,
2193    pub base_sha256: String,
2194    pub resolved_revisions: ResolvedRevisions,
2195    pub removed_comments: Vec<RemovedComment>,
2196    pub kept_comments: Vec<KeptComment>,
2197    /// The plan's date, else the time it is applied.
2198    pub date: String,
2199    pub initials: String,
2200    pub opened: Opened,
2201    /// The body first, then every header, footer and notes part.
2202    pub stories: Vec<StoryPart>,
2203    /// Every addressable paragraph: the body's, then each story's.
2204    pub paragraph_nodes: Vec<NodeId>,
2205    /// `(story, index in that story)` per entry of `paragraph_nodes`.
2206    pub paragraph_story: Vec<(usize, usize)>,
2207    pub projections: Vec<Projection>,
2208    /// Candidate lookup uses the fixed v1 normalization ladder against these
2209    /// immutable projections. Within a transaction the anchor therefore keys
2210    /// both the search text and its normalization, including empty results.
2211    pub anchor_candidate_cache: std::cell::RefCell<HashMap<String, (Vec<AnchorCandidate>, usize)>>,
2212    /// The source's paragraphs and where they went, when settling
2213    /// revisions rewrote the document.
2214    pub origin: Option<origin::Origin>,
2215    pub outcomes: Vec<EditOutcome>,
2216    pub resolved: Vec<(usize, Resolved)>,
2217    /// `(paragraph, start, end)` a `replace` names, by operation, where
2218    /// its diff wrote only some of it: other operations conflict with the
2219    /// whole range, its kept words too.
2220    pub claims: BTreeMap<usize, (usize, usize, usize)>,
2221    /// While an operation naming `cN.text` resolves: `N` and the span of
2222    /// its paragraph's projection the comment covers. Anchors are looked
2223    /// up there only.
2224    pub anchor_window: std::cell::Cell<Option<(u32, usize, usize)>>,
2225    /// The request syntax refusals quote (#1108).
2226    pub syntax: PlanSyntax,
2227    pub comments: Vec<(u32, String)>,
2228    /// `(comment id, operation)` of each commented paragraph deletion.
2229    pub deletion_comments: Vec<(u32, usize)>,
2230    /// Ids new comments take, last first, before `next_comment_id`.
2231    pub preset_comment_ids: Vec<u32>,
2232    /// One past the highest source comment id; u64 so it cannot overflow.
2233    pub next_comment_id: u64,
2234    pub comments_added: usize,
2235    /// Helper bookmarks around `whole` replacements, one per operation.
2236    pub whole_marks: Vec<whole::Mark>,
2237    /// `w:abstractNum` and `w:num` elements new lists add.
2238    pub new_numbering: (Vec<String>, Vec<String>),
2239    /// Style definitions the edits need (`ListParagraph`).
2240    pub needed_styles: std::collections::BTreeSet<String>,
2241    /// The source's comment part family; taken when the parts are written.
2242    pub family: Option<crate::comments::CommentFamily>,
2243    /// Comment replied to, by the reply's new id.
2244    pub reply_parents: BTreeMap<u32, u32>,
2245    /// Another author's comments a thread operation changes, by outcome
2246    /// index. The report notes each one. `rewrite_others_comments` does
2247    /// not decide that.
2248    pub rewritten: Vec<(usize, OthersComment)>,
2249    /// The plan's watermark, written into the default headers at finish.
2250    pub watermark: Option<watermark::Spec>,
2251    /// The body's content controls, in document order.
2252    pub controls: Vec<NodeId>,
2253    /// What `inspect` reports for each of `controls`.
2254    pub control_records: Vec<crate::inspect::ContentControl>,
2255    /// The footnotes story when `insert_footnote` added notes to it.
2256    pub notes_story: Option<usize>,
2257    /// The plan's settings, written into the settings part at finish.
2258    pub settings: Option<crate::settings::SettingsRequest>,
2259    /// The story indices `finish` last wrote, body included: the
2260    /// serialized-stories check compares each one's DOM against the bytes.
2261    pub written_stories: std::collections::BTreeSet<usize>,
2262    /// The ids `apply` gives the records it copies onto the retained
2263    /// fragments of a split run: none a source record uses, so the copy of
2264    /// another author's formatting history collides with nothing (#1656).
2265    pub revision_ids: RevisionCounter,
2266    /// Every revision id the source and its settled base use. An id the
2267    /// settling removed never names a new record in the same report.
2268    pub used_revision_ids: HashSet<u64>,
2269}
2270
2271/// The body, or a header, footer or notes part, parsed into the plan's DOM.
2272#[doc(hidden)]
2273pub struct StoryPart {
2274    /// `body`, or the part's file stem (`header1`, `footnotes`).
2275    id: String,
2276    /// Package part name.
2277    part: String,
2278    document: NodeId,
2279    root: NodeId,
2280}
2281
2282pub(crate) fn kind_name(kind: &OperationKind) -> &'static str {
2283    match kind {
2284        OperationKind::Replace { .. } => "replace",
2285        OperationKind::Insert { .. } => "insert",
2286        OperationKind::Delete { .. } => "delete",
2287        OperationKind::Comment { .. } => "comment",
2288        OperationKind::InsertParagraph { .. } => "insert_paragraph",
2289        OperationKind::DeleteParagraph { .. } => "delete_paragraph",
2290        OperationKind::FormatParagraph { .. } => "format_paragraph",
2291        OperationKind::MergeParagraphs { .. } => "merge_paragraphs",
2292        OperationKind::Rewrite { .. } => "rewrite",
2293        OperationKind::ReplyComment { .. } => "reply_comment",
2294        OperationKind::ResolveComment { .. } => "resolve_comment",
2295        OperationKind::EditComment { .. } => "edit_comment",
2296        OperationKind::DeleteComment { .. } => "delete_comment",
2297        OperationKind::InsertTable { .. } => "insert_table",
2298        OperationKind::List { .. } => "list",
2299        OperationKind::Watermark { .. } => "watermark",
2300        OperationKind::FillControl { .. } => "fill_control",
2301        OperationKind::FormatRun { .. } => "format_run",
2302        OperationKind::InsertFootnote { .. } => "insert_footnote",
2303        OperationKind::InsertImage { .. } => "insert_image",
2304        OperationKind::PageSetup { .. } => "page_setup",
2305        OperationKind::InsertToc { .. } => "insert_toc",
2306        OperationKind::Redact { .. } => "redact",
2307        OperationKind::Settings { .. } => "settings",
2308        OperationKind::Strike { .. } => "strike",
2309        OperationKind::Restore { .. } => "restore",
2310    }
2311}
2312
2313/// One output's revision ids (#1656). The edit's own records and the
2314/// copies a split makes of a source record come from one counter: above
2315/// every id the source uses, and inside Word's signed 32-bit range once it
2316/// runs out ([`crate::revision_processor::RevisionIds`]).
2317#[doc(hidden)]
2318pub struct RevisionCounter {
2319    ids: crate::revision_processor::RevisionIds,
2320    /// The id of the record each copy was made from, by the copy's id.
2321    copied_from: HashMap<u64, u64>,
2322    /// The ids of the records the edit writes: its own changes. A copy of
2323    /// a source record is not one.
2324    own: BTreeSet<u64>,
2325}
2326
2327impl Default for RevisionCounter {
2328    fn default() -> Self {
2329        Self::new(HashSet::new())
2330    }
2331}
2332
2333impl RevisionCounter {
2334    /// A counter that never hands out one of `used`.
2335    pub(super) fn new(used: HashSet<u64>) -> Self {
2336        Self {
2337            ids: crate::revision_processor::RevisionIds::from_used(used),
2338            copied_from: HashMap::new(),
2339            own: BTreeSet::new(),
2340        }
2341    }
2342
2343    /// An id for a record the edit writes.
2344    pub(super) fn allocate(&mut self) -> u64 {
2345        let id = self.ids.allocate();
2346        self.own.insert(id);
2347        id
2348    }
2349
2350    /// An id for a copy of the record that had id `of`: the edit's own
2351    /// change when it copies one of the edit's own records, a copy of a
2352    /// source record otherwise.
2353    fn copy(&mut self, of: Option<u64>) -> u64 {
2354        let id = if of.is_some_and(|id| self.own.contains(&id)) {
2355            self.allocate()
2356        } else {
2357            self.ids.allocate()
2358        };
2359        if let Some(of) = of {
2360            self.copied_from.insert(id, of);
2361        }
2362        id
2363    }
2364
2365    /// The record `id` is a copy of, through copies of copies; `id` itself
2366    /// when it is no copy. A copy takes an id no record had, so the chain
2367    /// ends.
2368    fn original(&self, mut id: u64) -> u64 {
2369        while let Some(&of) = self.copied_from.get(&id) {
2370            id = of;
2371        }
2372        id
2373    }
2374
2375    /// The ids of the records the edit wrote, copies of source records
2376    /// excluded.
2377    pub(super) fn own(&self) -> &BTreeSet<u64> {
2378        &self.own
2379    }
2380}
2381
2382#[cfg(test)]
2383#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2384#[path = "tests/tests.rs"]
2385mod tests;
2386#[cfg(test)]
2387thread_local! {
2388    static CANDIDATE_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2389}
2390
2391// Reuse the repository's existing, entirely in-memory package fixture.
2392#[cfg(test)]
2393#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2394#[path = "../../../../tests/common/docx.rs"]
2395mod deeper_boundary_fixture;
2396
2397#[cfg(test)]
2398#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2399#[path = "tests/deeper_boundary_tests.rs"]
2400mod deeper_boundary_tests;
2401
2402#[cfg(test)]
2403#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2404mod jsonl_branch_tests {
2405    use super::deeper_boundary_fixture::{docx, para};
2406    use super::*;
2407
2408    fn lines(report: &EditReport) -> Vec<serde_json::Value> {
2409        report
2410            .to_jsonl()
2411            .lines()
2412            .map(|l| serde_json::from_str(l).unwrap())
2413            .collect()
2414    }
2415
2416    #[test]
2417    fn a_skipped_run_with_landed_operations_reports_partial() {
2418        let plan = EditPlan::from_json(
2419            &serde_json::json!({
2420                "schema_version": 1,
2421                "author": "Ed",
2422                "date": "2026-02-02T00:00:00Z",
2423                "operations": [
2424                    {"kind": "replace", "paragraph": "p0", "find": "one", "replacement": "1"},
2425                    {"kind": "replace", "paragraph": "p0", "find": "two", "replacement": "2"},
2426                ],
2427            })
2428            .to_string(),
2429        )
2430        .unwrap();
2431        let mut report = apply_plan(&docx(&para("one two")), &plan).unwrap().report;
2432        report.ok = false;
2433        report.skipped = 1;
2434        report.operations[1].status = "failed".into();
2435        report.operations[1].near = Some(anchor::NearMatches {
2436            total: 0,
2437            occurrences: Vec::new(),
2438        });
2439        report.clean_removed_comments.push(RemovedComment {
2440            id: "c3".into(),
2441            author: "Bo".into(),
2442            replies: Vec::new(),
2443            why: "anchor removed".into(),
2444            decision: None,
2445        });
2446        let out = lines(&report);
2447        let summary = out.last().unwrap();
2448        assert_eq!(summary["status"], "partial");
2449        assert_eq!(summary["ops"]["skipped"], 1);
2450        assert_eq!(summary["clean_removed_comments"][0]["id"], "c3");
2451        assert!(out.iter().any(|l| l.get("near").is_some()), "{out:?}");
2452        // Nothing landed: failed.
2453        report.operations[0].status = "failed".into();
2454        assert_eq!(lines(&report).last().unwrap()["status"], "failed");
2455    }
2456}
2457
2458#[cfg(test)]
2459#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2460mod keep_others_branch_tests {
2461    use super::deeper_boundary_fixture::{docx, para};
2462    use super::*;
2463
2464    fn selection(json: serde_json::Value) -> ResolveRevisions {
2465        serde_json::from_value(json).unwrap()
2466    }
2467
2468    #[test]
2469    fn a_wholesale_policy_names_nameless_changes_and_passes_clean_sources() {
2470        let plain = docx(&para("Plain."));
2471        assert!(
2472            guard_keep_others(&plain, "Ed", None, Some("accept"), false, PlanSyntax::V1).is_ok()
2473        );
2474        let nameless = docx(
2475            r#"<w:p><w:r><w:t xml:space="preserve">Kept </w:t></w:r><w:ins w:id="1" w:date="2026-01-01T00:00:00Z"><w:r><w:t>added</w:t></w:r></w:ins></w:p>"#,
2476        );
2477        let e = guard_keep_others(&nameless, "Ed", None, Some("accept"), false, PlanSyntax::V1)
2478            .unwrap_err();
2479        assert_eq!(e.code, "CHANGE_NOT_YOURS");
2480        assert!(
2481            e.message
2482                .contains(r#""existing_revisions": "accept" would erase"#),
2483            "{}",
2484            e.message
2485        );
2486    }
2487
2488    #[test]
2489    fn a_visible_reject_leaves_the_reject_ids_to_the_strike() {
2490        let source = docx(
2491            r#"<w:p><w:r><w:t xml:space="preserve">Kept </w:t></w:r><w:ins w:id="1" w:author="Bo" w:date="2026-01-01T00:00:00Z"><w:r><w:t>added</w:t></w:r></w:ins></w:p>"#,
2492        );
2493        let visible = selection(serde_json::json!({"reject": {"ids": ["r1"], "visible": true}}));
2494        assert!(visible.reject_visible);
2495        assert!(
2496            guard_keep_others(&source, "Ed", Some(&visible), None, false, PlanSyntax::V1).is_ok()
2497        );
2498        let silent = selection(serde_json::json!({"reject": {"ids": ["r1"]}}));
2499        let e = guard_keep_others(&source, "Ed", Some(&silent), None, false, PlanSyntax::V1)
2500            .unwrap_err();
2501        assert_eq!(e.code, "CHANGE_NOT_YOURS");
2502    }
2503
2504    #[test]
2505    fn colon_ids_need_a_known_story_and_a_number() {
2506        let source = docx(&para("Plain."));
2507        let got = paragraph_ids(&source, &["body:p:0", "body:p:x", "nowhere:p:1"]).unwrap();
2508        assert!(
2509            got[0]
2510                .as_ref()
2511                .unwrap_err()
2512                .ends_with("the settled spelling is p0"),
2513            "{got:?}"
2514        );
2515        assert!(
2516            got[1]
2517                .as_ref()
2518                .unwrap_err()
2519                .starts_with("body:p:x: -p takes"),
2520            "{got:?}"
2521        );
2522        assert!(
2523            got[2].as_ref().unwrap_err().starts_with("unknown story"),
2524            "{got:?}"
2525        );
2526    }
2527}