Skip to main content

jubarte_edit/edit/
v2.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Source-bound PlanV2 text-and-review requests, separate from the legacy
6//! [`super::EditPlan`] contract. This module parses requests; it neither
7//! applies them nor authorizes an edit merely because parsing succeeded.
8//!
9//! [`PlanV2::from_json`] checks the production [`SCHEMA_JSON`] contract,
10//! including cross-field rules and timestamp values. Source binding, ID
11//! grammar/type/identity, scope, selected-decision conflicts, working hashes,
12//! correspondence and operation composition require the source compiler.
13//! In particular, two nonempty IDs are not evidence that they name one entity.
14
15use std::collections::BTreeSet;
16
17use serde::{Deserialize, Deserializer, Serialize};
18
19use super::{Edge, EditError, ExistingRevisions, Side};
20use crate::namespaces::W;
21use crate::xmllinq::{Dom, NodeId};
22
23/// Production Draft 2020-12 schema for this library's text-and-review profile.
24/// Consumers must enable `date-time` format assertions.
25pub const SCHEMA_JSON: &str = include_str!("../../schemas/edit-plan-v2.schema.json");
26/// Exact logical text codec version, fixed by PlanV2.
27pub const TEXT_CODEC_VERSION: u32 = 1;
28
29/// An explicit request against one immutable original DOCX snapshot.
30///
31/// Use [`Self::from_json`] for strict parsing or [`Self::validate`] after
32/// constructing/modifying a value. Serde deserialization alone checks wire
33/// types and unknown fields, while `validate` also checks scalar and
34/// cross-field constraints. No defaults are inferred for required fields.
35#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(deny_unknown_fields)]
37pub struct PlanV2 {
38    /// Wire version, exactly 2.
39    #[serde(deserialize_with = "integer")]
40    pub schema_version: u64,
41    /// Mandatory original-source byte binding.
42    pub source: Source,
43    /// New-edit tracking and treatment of remaining revisions.
44    pub policy: Policy,
45    /// Original-source decisions applied before the remaining-revision policy.
46    pub resolve_revisions: RevisionDecisions,
47    /// Opt-in empty comment anchors when settled text disappears.
48    #[serde(
49        default,
50        deserialize_with = "present",
51        skip_serializing_if = "Option::is_none"
52    )]
53    pub removed_anchor_comments: Option<super::RemovedAnchorComments>,
54    /// Accepted and ignored. Deleting, resolving or rewording another
55    /// author's comment is allowed unless [`super::Others::Keep`] is set.
56    #[serde(
57        default,
58        deserialize_with = "present",
59        skip_serializing_if = "Option::is_none"
60    )]
61    pub rewrite_others_comments: Option<bool>,
62    /// When `keep`, refuse to erase another author's markup. Absent or
63    /// `allow` permits it. `rewrite_others_comments` is accepted and ignored.
64    #[serde(
65        default,
66        deserialize_with = "present",
67        skip_serializing_if = "Option::is_none"
68    )]
69    pub others: Option<super::Others>,
70    /// Attribution for new revisions and comments; contains a non-whitespace character.
71    pub author: String,
72    /// Timezone-bearing RFC 3339 timestamp, retaining its supplied offset.
73    pub date: String,
74    /// Direct content/review-operation scope; revision decisions never expand it.
75    pub scope: Scope,
76    /// Typed requests in array order. Empty is valid, including review-only plans.
77    pub operations: Vec<Operation>,
78    /// Immutable observations of the original source, never executable edits.
79    #[serde(
80        default,
81        deserialize_with = "present",
82        skip_serializing_if = "Option::is_none"
83    )]
84    pub source_context: Option<Vec<SourceContext>>,
85    /// Generation observations; these do not grant permission or prove completeness.
86    #[serde(
87        default,
88        deserialize_with = "present",
89        skip_serializing_if = "Option::is_none"
90    )]
91    pub coverage: Option<Coverage>,
92}
93
94/// SHA-256 binding to the exact original package bytes, independent of paths.
95#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(deny_unknown_fields)]
97pub struct Source {
98    /// Exactly 64 lowercase hexadecimal characters.
99    pub sha256: String,
100}
101
102/// Tracking concerns new changes only; selected decisions run first.
103#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(deny_unknown_fields)]
105pub struct Policy {
106    /// Whether newly written body edits are tracked.
107    #[serde(deserialize_with = "string_enum")]
108    pub track: Track,
109    /// Treatment of revisions left after selected decisions. `Refuse` is global.
110    #[serde(deserialize_with = "string_enum")]
111    pub existing_revisions: ExistingRevisions,
112    /// Effective working projection used for exact literal anchors and hashes.
113    #[serde(deserialize_with = "string_enum")]
114    pub text_view: TextView,
115}
116
117/// Tracking policy for newly requested edits.
118#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(rename_all = "snake_case")]
120pub enum Track {
121    /// Record new edits as revisions.
122    On,
123    /// Make supported new edits directly, preserving old history as policy requires.
124    Off,
125}
126
127/// The initial profile supports the final logical working projection only.
128#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
129#[serde(rename_all = "snake_case")]
130pub enum TextView {
131    /// Insertions included, deletions excluded, with no review/display markup.
132    Final,
133}
134
135/// Exactly the established short/long pair, with no third representation.
136///
137/// Parsing checks shape and nonempty strings, as the schema specifies.
138/// The source ID codec/resolver must check grammar, entity type and that both
139/// halves identify the SAME entity in the hash-bound original source. It must
140/// not fall back to either half when the pair disagrees.
141#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
142#[serde(deny_unknown_fields)]
143pub struct Target {
144    /// Snapshot-relative short ID supplied by a reader/generator.
145    pub short_id: String,
146    /// Corresponding long ID, including the contract's `j:short` form when needed.
147    pub long_id: String,
148}
149
150/// Original-source logical revision selections. Alias/dependency expansion
151/// and disjointness checks belong to source resolution, not syntactic parsing.
152#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
153#[serde(deny_unknown_fields)]
154pub struct RevisionDecisions {
155    /// Unique explicit selections to accept.
156    pub accept: Vec<Target>,
157    /// Unique explicit selections to reject.
158    pub reject: Vec<Target>,
159}
160
161/// Direct body/review-operation authority, frozen on the original source.
162#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
163#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
164pub enum Scope {
165    /// All source entities, subject to actual operation support.
166    All {},
167    /// Nonempty unique pairs; descendants require the compiled source model.
168    Selected {
169        /// Explicit source targets.
170        targets: Vec<Target>,
171    },
172}
173
174/// A new comment on the verified nonempty result of its owning operation.
175/// An unchanged text component does not cancel this explicit request.
176#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
177#[serde(deny_unknown_fields)]
178pub struct AttachedComment {
179    /// Nonempty plain text, using plan attribution.
180    pub text: String,
181}
182
183/// Typed requests in the text-and-review profile.
184///
185/// Literal occurrences are 1-based and count overlapping start positions.
186/// All active ranges resolve on one working baseline, not intermediate edits.
187/// Conflict detection, comment mapping and exact effects require preparation.
188#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
189#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
190pub enum Operation {
191    /// Replace one exact literal range; empty `text` deletes only that range.
192    Replace {
193        /// Original paragraph reference.
194        target: Target,
195        /// Nonempty exact literal anchor.
196        find: String,
197        /// Exact replacement characters.
198        text: String,
199        /// Explicit 1-based match when an anchor repeats.
200        #[serde(
201            default,
202            deserialize_with = "present_integer",
203            skip_serializing_if = "Option::is_none"
204        )]
205        occurrence: Option<u64>,
206        /// Comment on the nonempty resulting replacement.
207        #[serde(
208            default,
209            deserialize_with = "present",
210            skip_serializing_if = "Option::is_none"
211        )]
212        attached_comment: Option<AttachedComment>,
213    },
214    /// Insert nonempty characters at exactly one declared working-text position.
215    Insert {
216        /// Original paragraph reference.
217        target: Target,
218        /// Exact inserted characters, including tabs and soft breaks.
219        text: String,
220        /// Insert before this nonempty exact literal.
221        #[serde(
222            default,
223            deserialize_with = "present",
224            skip_serializing_if = "Option::is_none"
225        )]
226        before_text: Option<String>,
227        /// Insert after this nonempty exact literal.
228        #[serde(
229            default,
230            deserialize_with = "present",
231            skip_serializing_if = "Option::is_none"
232        )]
233        after_text: Option<String>,
234        /// Insert at a paragraph edge; excludes anchors and occurrence.
235        #[serde(
236            default,
237            deserialize_with = "present_string_enum",
238            skip_serializing_if = "Option::is_none"
239        )]
240        edge: Option<Edge>,
241        /// Explicit match of a literal anchor; forbidden with `edge`.
242        #[serde(
243            default,
244            deserialize_with = "present_integer",
245            skip_serializing_if = "Option::is_none"
246        )]
247        occurrence: Option<u64>,
248        /// Comment on the inserted text.
249        #[serde(
250            default,
251            deserialize_with = "present",
252            skip_serializing_if = "Option::is_none"
253        )]
254        attached_comment: Option<AttachedComment>,
255    },
256    /// Delete one literal range. Whole-paragraph deletion is a separate kind.
257    Delete {
258        /// Original paragraph reference.
259        target: Target,
260        /// Nonempty exact literal anchor.
261        find: String,
262        /// Explicit 1-based literal match.
263        #[serde(
264            default,
265            deserialize_with = "present_integer",
266            skip_serializing_if = "Option::is_none"
267        )]
268        occurrence: Option<u64>,
269    },
270    /// Exact desired paragraph text with a mandatory working-basis guard.
271    Rewrite {
272        /// Original paragraph; requires verified one-to-one working correspondence.
273        target: Target,
274        /// SHA-256 of the effective working paragraph text after selected
275        /// accept/reject decisions, checked before unchanged classification.
276        before_sha256: String,
277        /// Desired exact characters. Empty retains the structural paragraph mark.
278        text: String,
279        /// Comment on the complete nonempty resulting paragraph.
280        #[serde(
281            default,
282            deserialize_with = "present",
283            skip_serializing_if = "Option::is_none"
284        )]
285        attached_comment: Option<AttachedComment>,
286    },
287    /// Insert a structural paragraph beside an existing anchor in its container.
288    InsertParagraph {
289        /// Original existing anchor paragraph.
290        target: Target,
291        /// Explicit side; same-side requests retain array order.
292        #[serde(deserialize_with = "string_enum")]
293        position: Side,
294        /// Exact paragraph characters; empty paragraphs are meaningful.
295        text: String,
296        /// Comment on the complete nonempty inserted paragraph.
297        #[serde(
298            default,
299            deserialize_with = "present",
300            skip_serializing_if = "Option::is_none"
301        )]
302        attached_comment: Option<AttachedComment>,
303    },
304    /// Explicit structural paragraph deletion, subject to container/tracking support.
305    DeleteParagraph {
306        /// Original paragraph reference.
307        target: Target,
308    },
309    /// New comment on a paragraph, exact literal, or same-story paragraph range.
310    Comment {
311        /// Original start paragraph.
312        target: Target,
313        /// Nonempty plain comment text.
314        text: String,
315        /// Nonempty literal; excludes `through`.
316        #[serde(
317            default,
318            deserialize_with = "present",
319            skip_serializing_if = "Option::is_none"
320        )]
321        find: Option<String>,
322        /// Requires `find`.
323        #[serde(
324            default,
325            deserialize_with = "present_integer",
326            skip_serializing_if = "Option::is_none"
327        )]
328        occurrence: Option<u64>,
329        /// Inclusive original end paragraph; every covered paragraph must be in scope.
330        #[serde(
331            default,
332            deserialize_with = "present",
333            skip_serializing_if = "Option::is_none"
334        )]
335        through: Option<Target>,
336    },
337    /// Reply to a surviving original comment; sibling replies retain array order.
338    ReplyComment {
339        /// Existing original comment.
340        target: Target,
341        /// Nonempty plain reply text.
342        text: String,
343    },
344    /// Explicit final thread state, applied after compatible replies.
345    ResolveComment {
346        /// Existing original comment in the affected thread.
347        target: Target,
348        /// True resolves the thread; false reopens it.
349        done: bool,
350    },
351    /// Replace a comment body, preserving its recorded attribution.
352    EditComment {
353        /// Existing original comment.
354        target: Target,
355        /// Nonempty replacement comment text.
356        text: String,
357    },
358    /// Explicit removal; conflicts with mutations of the affected comment/thread.
359    DeleteComment {
360        /// Existing original comment.
361        target: Target,
362        /// Root removal with replies requires explicit inclusion.
363        include_replies: bool,
364    },
365    /// Reject another author's insertion visibly. The target names that revision.
366    Strike {
367        /// The insertion, as `changes` lists it.
368        target: Target,
369    },
370    /// Reject another author's deletion visibly. The target names that revision.
371    Restore {
372        /// The deletion, as `changes` lists it.
373        target: Target,
374    },
375}
376
377/// Kind of immutable original-source observation.
378#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
379#[serde(rename_all = "snake_case")]
380pub enum ContextKind {
381    /// Original final logical paragraph text.
382    Paragraph,
383    /// Original comment body.
384    Comment,
385    /// Unsupported region under a real containing source target.
386    Opaque,
387}
388
389/// Removing an observation requests no edit. Supplied text must later be
390/// verified against the original source, independently of revision decisions.
391#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
392#[serde(deny_unknown_fields)]
393pub struct SourceContext {
394    /// Observation kind.
395    #[serde(deserialize_with = "string_enum")]
396    pub kind: ContextKind,
397    /// Real original source target (or containing target for an opaque region).
398    pub target: Target,
399    /// Required for paragraph/comment observations; optional for opaque regions.
400    #[serde(
401        default,
402        deserialize_with = "present",
403        skip_serializing_if = "Option::is_none"
404    )]
405    pub text: Option<String>,
406    /// Nonempty unique nonempty reason codes.
407    pub reason_codes: Vec<String>,
408}
409
410/// Generator observations, never a substitute for recomputed constraints.
411#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
412#[serde(deny_unknown_fields)]
413pub struct Coverage {
414    /// Whether traversal completed.
415    pub traversal_complete: bool,
416    /// Whether all represented text was inventoried.
417    pub text_complete: bool,
418    /// Count of eligible paragraphs.
419    #[serde(deserialize_with = "integer")]
420    pub eligible_paragraphs: u64,
421    /// Conditional paragraphs, a subset of eligible paragraphs; checked against source later.
422    #[serde(
423        default,
424        deserialize_with = "present_integer",
425        skip_serializing_if = "Option::is_none"
426    )]
427    pub conditional_paragraphs: Option<u64>,
428    /// Count of read-only context paragraphs.
429    #[serde(deserialize_with = "integer")]
430    pub context_paragraphs: u64,
431    /// Count of opaque regions.
432    #[serde(deserialize_with = "integer")]
433    pub opaque_regions: u64,
434}
435
436// Optional means absent, never explicit JSON null. Serde's default Option
437// deserializer would otherwise accept null in disagreement with the schema.
438fn present<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Option<T>, D::Error> {
439    T::deserialize(d).map(Some)
440}
441
442// JSON Schema's integer type includes 1.0 and 1e0, unlike serde's u64.
443// Above 2^53 the f64 representation collapses and the author's intent is
444// lost, so a float spelling is accepted only while it is exact.
445fn integer<'de, D: Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
446    let n = serde_json::Number::deserialize(d)?;
447    if let Some(n) = n.as_u64() {
448        return Ok(n);
449    }
450    if let Some(n) = n.as_f64() {
451        if !(0.0..9_007_199_254_740_992.0).contains(&n) || n.fract() != 0.0 {
452            return Err(serde::de::Error::custom(
453                "expected an unsigned 64-bit integer; an integer written with a fraction or exponent must be below 2^53; write it as a plain integer",
454            ));
455        }
456        return Ok(n as u64);
457    }
458    Err(serde::de::Error::custom(
459        "expected an unsigned 64-bit integer",
460    ))
461}
462// Serde's externally tagged unit enums also accept {"on": null}; the
463// production schema permits only strings. Keep legacy enum behavior intact.
464fn string_enum<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<T, D::Error> {
465    let value = String::deserialize(d)?;
466    T::deserialize(serde::de::value::StringDeserializer::<D::Error>::new(value))
467}
468fn present_string_enum<'de, D: Deserializer<'de>, T: Deserialize<'de>>(
469    d: D,
470) -> Result<Option<T>, D::Error> {
471    string_enum(d).map(Some)
472}
473fn present_integer<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
474    integer(d).map(Some)
475}
476fn invalid(message: impl Into<String>) -> EditError {
477    super::err("INVALID_PLAN", None, message)
478}
479
480/// Fields one operation kind takes, in the order an unknown-field message lists them.
481fn operation_fields(kind: &str) -> Option<&'static [&'static str]> {
482    let fields: &[&str] = match kind {
483        "replace" => &["attached_comment", "find", "occurrence", "target", "text"],
484        "insert" => &[
485            "after_text",
486            "attached_comment",
487            "before_text",
488            "edge",
489            "occurrence",
490            "target",
491            "text",
492        ],
493        "delete" => &["find", "occurrence", "target"],
494        "rewrite" => &["attached_comment", "before_sha256", "target", "text"],
495        "insert_paragraph" => &["attached_comment", "position", "target", "text"],
496        "delete_paragraph" => &["target"],
497        "comment" => &["find", "occurrence", "target", "text", "through"],
498        "reply_comment" => &["target", "text"],
499        "resolve_comment" => &["done", "target"],
500        "edit_comment" => &["target", "text"],
501        "delete_comment" => &["include_replies", "target"],
502        "strike" | "restore" => &["target"],
503        _ => return None,
504    };
505    Some(fields)
506}
507
508/// A first-version name for `target`.
509fn v1_target_name(key: &str) -> Option<&'static str> {
510    match key {
511        "paragraph" | "paragraphs" | "anchor" => Some("target"),
512        _ => None,
513    }
514}
515
516/// An operation field this version does not take, named the way a
517/// first-version plan's unknown field is named.
518fn check_operation_fields(plan: &serde_json::Value) -> Result<(), EditError> {
519    let Some(operations) = plan.get("operations").and_then(serde_json::Value::as_array) else {
520        return Ok(());
521    };
522    for (i, operation) in operations.iter().enumerate() {
523        let Some(map) = operation.as_object() else {
524            continue;
525        };
526        let Some(kind) = map.get("kind").and_then(serde_json::Value::as_str) else {
527            continue;
528        };
529        let Some(fields) = operation_fields(kind) else {
530            continue;
531        };
532        let Some(key) = map
533            .keys()
534            .find(|key| key.as_str() != "kind" && !fields.contains(&key.as_str()))
535        else {
536            continue;
537        };
538        let label = format!("op-{}", i + 1);
539        let meant = v1_target_name(key).filter(|name| fields.contains(name));
540        let message = format!("{kind}: {}", super::unknown_field(key, fields, meant));
541        return Err(super::err("INVALID_PLAN", Some(&label), message));
542    }
543    Ok(())
544}
545
546fn unsupported(version: u64) -> EditError {
547    super::err(
548        "UNSUPPORTED_SCHEMA",
549        None,
550        format!("schema_version {version} is not supported (expected 2)"),
551    )
552}
553
554fn require(condition: bool, message: &str) -> Result<(), EditError> {
555    if condition {
556        Ok(())
557    } else {
558        Err(invalid(message))
559    }
560}
561fn hash(value: &str) -> bool {
562    value.len() == 64
563        && value
564            .bytes()
565            .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
566}
567fn unique<T: Ord>(values: &[T]) -> bool {
568    values.iter().collect::<BTreeSet<_>>().len() == values.len()
569}
570impl Target {
571    fn validate(&self) -> Result<(), EditError> {
572        require(
573            !self.short_id.is_empty() && !self.long_id.is_empty(),
574            "target requires nonempty short_id and long_id",
575        )
576    }
577}
578fn targets(values: &[Target]) -> Result<(), EditError> {
579    require(unique(values), "target array contains duplicates")?;
580    for target in values {
581        target.validate()?;
582    }
583    Ok(())
584}
585fn occurrence(value: Option<u64>) -> Result<(), EditError> {
586    require(value != Some(0), "occurrence must be at least 1")
587}
588fn attachment(text: &str, comment: Option<&AttachedComment>) -> Result<(), EditError> {
589    if let Some(comment) = comment {
590        require(
591            !text.is_empty(),
592            "attached_comment requires nonempty resulting text",
593        )?;
594        require(
595            !comment.text.is_empty(),
596            "attached_comment.text must be nonempty",
597        )?;
598    }
599    Ok(())
600}
601
602impl PlanV2 {
603    /// Parse strictly with stable [`EditError`] codes: `INVALID_PLAN` for
604    /// malformed JSON, unknown/missing fields, invalid values or incompatible
605    /// field combinations; `UNSUPPORTED_SCHEMA` for another integer version.
606    /// Successful parsing does not verify this request against source bytes.
607    pub fn from_json(json: &str) -> Result<Self, EditError> {
608        let json = super::without_byte_order_mark(json);
609        let plan: Self = match serde_json::from_str(json) {
610            Ok(plan) => plan,
611            // Only a plan serde refuses is read again, to name the field
612            // the way a first-version plan's unknown field is named. Another
613            // version is refused as such before v2's fields apply to it.
614            Err(e) => {
615                if let Ok(value) = serde_json::from_str::<serde_json::Value>(json) {
616                    if let Some(version) = value
617                        .get("schema_version")
618                        .and_then(serde_json::Value::as_u64)
619                        .filter(|&version| version != 2)
620                    {
621                        return Err(unsupported(version));
622                    }
623                    check_operation_fields(&value)?;
624                }
625                return Err(invalid(e.to_string()));
626            }
627        };
628        plan.validate()?;
629        Ok(plan)
630    }
631
632    /// Validate the production request contract after constructing/modifying a
633    /// value. This performs no source resolution and no document mutation.
634    pub fn validate(&self) -> Result<(), EditError> {
635        if self.schema_version != 2 {
636            return Err(unsupported(self.schema_version));
637        }
638        require(
639            hash(&self.source.sha256),
640            "source.sha256 must be 64 lowercase hexadecimal characters",
641        )?;
642        require(
643            self.author.chars().any(|c| !is_author_whitespace(c)),
644            "author must contain a non-whitespace character",
645        )?;
646        require(
647            timestamp(&self.date),
648            "date must be a valid timezone-bearing RFC 3339 timestamp",
649        )?;
650        targets(&self.resolve_revisions.accept)?;
651        targets(&self.resolve_revisions.reject)?;
652        if let Scope::Selected { targets: selected } = &self.scope {
653            require(!selected.is_empty(), "selected scope must be nonempty")?;
654            targets(selected)?;
655        }
656        if let Some(context) = &self.source_context {
657            for item in context {
658                item.target.validate()?;
659                require(
660                    item.kind == ContextKind::Opaque || item.text.is_some(),
661                    "paragraph/comment context requires text",
662                )?;
663                require(
664                    !item.reason_codes.is_empty()
665                        && item.reason_codes.iter().all(|s| !s.is_empty())
666                        && unique(&item.reason_codes),
667                    "reason_codes must be nonempty, unique, nonempty strings",
668                )?;
669            }
670        }
671        for (index, operation) in self.operations.iter().enumerate() {
672            operation.validate().map_err(|mut e| {
673                e.operation = Some(format!("/operations/{index}"));
674                e
675            })?;
676        }
677        Ok(())
678    }
679
680    /// Serialize without changing desired characters, attribution or array order.
681    /// Call [`Self::validate`] first if fields have been modified directly.
682    pub fn to_json(&self) -> String {
683        serde_json::to_string_pretty(self).expect("PlanV2 serializes")
684    }
685}
686
687impl Operation {
688    /// Original source reference shared by every operation kind.
689    pub fn target(&self) -> &Target {
690        match self {
691            Self::Replace { target, .. }
692            | Self::Insert { target, .. }
693            | Self::Delete { target, .. }
694            | Self::Rewrite { target, .. }
695            | Self::InsertParagraph { target, .. }
696            | Self::DeleteParagraph { target }
697            | Self::Comment { target, .. }
698            | Self::ReplyComment { target, .. }
699            | Self::ResolveComment { target, .. }
700            | Self::EditComment { target, .. }
701            | Self::DeleteComment { target, .. }
702            | Self::Strike { target }
703            | Self::Restore { target } => target,
704        }
705    }
706    fn validate(&self) -> Result<(), EditError> {
707        self.target().validate()?;
708        match self {
709            Self::Replace { text, .. }
710            | Self::Rewrite { text, .. }
711            | Self::Insert { text, .. }
712            | Self::InsertParagraph { text, .. } => check_payload_text(text, false)?,
713            _ => {}
714        }
715        match self {
716            Self::Rewrite {
717                before_sha256,
718                text,
719                attached_comment,
720                ..
721            } => {
722                require(
723                    hash(before_sha256),
724                    "before_sha256 must be 64 lowercase hexadecimal characters",
725                )?;
726                attachment(text, attached_comment.as_ref())?;
727            }
728            Self::Replace {
729                find,
730                text,
731                occurrence: selected,
732                attached_comment,
733                ..
734            } => {
735                require(!find.is_empty(), "find must be nonempty")?;
736                occurrence(*selected)?;
737                attachment(text, attached_comment.as_ref())?;
738            }
739            Self::Delete {
740                find,
741                occurrence: selected,
742                ..
743            } => {
744                require(!find.is_empty(), "find must be nonempty")?;
745                occurrence(*selected)?;
746            }
747            Self::Insert {
748                text,
749                before_text,
750                after_text,
751                edge,
752                occurrence: selected,
753                attached_comment,
754                ..
755            } => {
756                require(!text.is_empty(), "insert.text must be nonempty")?;
757                require(
758                    usize::from(before_text.is_some())
759                        + usize::from(after_text.is_some())
760                        + usize::from(edge.is_some())
761                        == 1,
762                    "insert requires exactly one of before_text, after_text or edge",
763                )?;
764                require(
765                    before_text.as_ref().is_none_or(|s| !s.is_empty())
766                        && after_text.as_ref().is_none_or(|s| !s.is_empty()),
767                    "insertion anchors must be nonempty",
768                )?;
769                require(
770                    edge.is_none() || selected.is_none(),
771                    "edge excludes occurrence",
772                )?;
773                occurrence(*selected)?;
774                attachment(text, attached_comment.as_ref())?;
775            }
776            Self::InsertParagraph {
777                text,
778                attached_comment,
779                ..
780            } => attachment(text, attached_comment.as_ref())?,
781            Self::Comment {
782                text,
783                find,
784                occurrence: selected,
785                through,
786                ..
787            } => {
788                require(!text.is_empty(), "comment.text must be nonempty")?;
789                require(
790                    find.is_none() || through.is_none(),
791                    "comment find and through are mutually exclusive",
792                )?;
793                require(
794                    selected.is_none() || find.is_some(),
795                    "comment occurrence requires find",
796                )?;
797                require(
798                    find.as_ref().is_none_or(|s| !s.is_empty()),
799                    "comment.find must be nonempty",
800                )?;
801                occurrence(*selected)?;
802                if let Some(target) = through {
803                    target.validate()?;
804                }
805            }
806            Self::ReplyComment { text, .. } | Self::EditComment { text, .. } => {
807                require(!text.is_empty(), "comment text must be nonempty")?;
808            }
809            Self::DeleteParagraph { .. }
810            | Self::ResolveComment { .. }
811            | Self::DeleteComment { .. }
812            | Self::Strike { .. }
813            | Self::Restore { .. } => {}
814        }
815        Ok(())
816    }
817}
818
819// Engine-independent whitespace class for the author field: the union of
820// Rust's `char::is_whitespace` (Unicode White_Space) and U+FEFF. Matches the
821// explicit character class the schema enforces on the same field.
822fn is_author_whitespace(c: char) -> bool {
823    c.is_whitespace() || c == '\u{feff}'
824}
825
826// Calendar/time/offset validation for the schema's uppercase RFC 3339 shape.
827// The legacy Word xsd:dateTime parser also accepts an absent zone and caps
828// offsets at 14:00, so using it here would disagree with this schema.
829// Year 0000 and second 60 are refused to match XSD 1.0 dateTime (which the
830// schema also rejects).
831fn timestamp(value: &str) -> bool {
832    let b = value.as_bytes();
833    if b.len() < 20
834        || b[4] != b'-'
835        || b[7] != b'-'
836        || b[10] != b'T'
837        || b[13] != b':'
838        || b[16] != b':'
839    {
840        return false;
841    }
842    let number = |start, end| {
843        value
844            .get(start..end)
845            .filter(|s| s.bytes().all(|c| c.is_ascii_digit()))
846            .and_then(|s| s.parse::<i32>().ok())
847    };
848    let (Some(year), Some(month), Some(day), Some(hour), Some(minute), Some(second)) = (
849        number(0, 4),
850        number(5, 7),
851        number(8, 10),
852        number(11, 13),
853        number(14, 16),
854        number(17, 19),
855    ) else {
856        return false;
857    };
858    let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
859    let days = match month {
860        2 if leap => 29,
861        2 => 28,
862        4 | 6 | 9 | 11 => 30,
863        1..=12 => 31,
864        _ => 0,
865    };
866    if year == 0 || !(1..=days).contains(&day) || hour > 23 || minute > 59 || second > 59 {
867        return false;
868    }
869    let mut zone = 19;
870    if b[zone] == b'.' {
871        zone += 1;
872        let start = zone;
873        while zone < b.len() && b[zone].is_ascii_digit() {
874            zone += 1;
875        }
876        if zone == start {
877            return false;
878        }
879    }
880    match &b[zone..] {
881        [b'Z'] => true,
882        [b'+' | b'-', a, c, b':', d, e] if [a, c, d, e].iter().all(|v| v.is_ascii_digit()) => {
883            let hours = (a - b'0') * 10 + (c - b'0');
884            let minutes = (d - b'0') * 10 + (e - b'0');
885            hours <= 23 && minutes <= 59
886        }
887        _ => false,
888    }
889}
890
891/// Exact logical text codec v1 for a supported `w:p` in an admitted DOM.
892///
893/// Reuses the engine's final paragraph projection: exact `w:t` characters,
894/// `w:tab` as U+0009 and untyped/`textWrapping` `w:br` as U+000A. The
895/// paragraph mark is outside the text. Double spaces, U+00A0 and Unicode
896/// normalization forms remain distinct. Plain hyperlinks and supported
897/// insertion/deletion wrappers retain the same final-text projection.
898///
899/// Refused opaque constructs (returned as `UNSUPPORTED_TEXT_CODEC` rather
900/// than silently mapped to placeholder characters): `w:cr`, `w:noBreakHyphen`
901/// and `w:softHyphen` (the projector maps them deterministically, but the
902/// codec refuses rather than silently substituting), plus page/column/unknown
903/// `w:br`, `w:sym`, `w:drawing`, `w:fldChar`, `w:instrText`,
904/// `w:footnoteReference`, `w:ptab` and any element outside the `w:` namespace
905/// or with an unsupported local name. The argument must be a `w:p`; any
906/// other element name is rejected.
907///
908/// This only proves text representation, not rewrite eligibility or range
909/// preservation.
910pub fn logical_text(dom: &Dom, paragraph: NodeId) -> Result<String, EditError> {
911    if dom.name(paragraph) != Some(W::p()) {
912        return Err(codec_error("expected a w:p element"));
913    }
914    check_text_content(dom, paragraph)?;
915    Ok(crate::inspect::project_paragraph(dom, paragraph).text)
916}
917
918/// Validate exact typed payloads without normalization. A file's leading BOM
919/// is an encoding mark; every other U+FEFF remains content.
920#[doc(hidden)]
921pub fn check_payload_text(text: &str, from_file: bool) -> Result<(), EditError> {
922    if from_file && text.starts_with('\u{feff}') {
923        return Err(super::err(
924            "INVALID_EDIT",
925            None,
926            "text file holds U+FEFF at character offset 0, an encoding mark; save exact UTF-8 without a BOM",
927        ));
928    }
929    if let Some(offset) = text.chars().position(|c| c == '\r') {
930        return Err(super::err(
931            "INVALID_EDIT",
932            None,
933            format!(
934                "text holds U+000D at character offset {offset}; use LF (U+000A) for line breaks"
935            ),
936        ));
937    }
938    Ok(())
939}
940
941/// Lowercase hexadecimal SHA-256 of the final logical projection of
942/// `paragraph` in `dom` (the same string [`logical_text`] returns for that
943/// pair). Hashes characters, not XML, JSON escapes, Markdown or normalized
944/// words. For the plan field `Rewrite.before_sha256`, the caller passes the
945/// effective working document (after selected accept/reject decisions),
946/// because selected decisions can change the projected text.
947pub fn before_sha256(dom: &Dom, paragraph: NodeId) -> Result<String, EditError> {
948    Ok(crate::inspect::source_sha256(
949        logical_text(dom, paragraph)?.as_bytes(),
950    ))
951}
952
953fn codec_error(message: impl Into<String>) -> EditError {
954    super::err("UNSUPPORTED_TEXT_CODEC", None, message)
955}
956fn check_text_content(dom: &Dom, container: NodeId) -> Result<(), EditError> {
957    let in_run = dom.name(container) == Some(W::r());
958    for child in dom.elements(container, None) {
959        let Some(name) = dom.name(child) else {
960            return Err(codec_error("unnamed text element"));
961        };
962        if name.namespace_name() != W::URI {
963            return Err(codec_error(format!("unsupported text element {name:?}")));
964        }
965        // Follow the same container/run distinction as project_paragraph.
966        // A run nested in a run, or bare w:t beneath w:p, is not projected.
967        match (in_run, name.local_name()) {
968            (
969                false,
970                "pPr" | "proofErr" | "bookmarkStart" | "bookmarkEnd" | "commentRangeStart"
971                | "commentRangeEnd" | "permStart" | "permEnd" | "moveFromRangeStart"
972                | "moveFromRangeEnd" | "moveToRangeStart" | "moveToRangeEnd" | "del" | "moveFrom",
973            ) => {}
974            (true, "rPr" | "commentReference" | "lastRenderedPageBreak") => {}
975            (false, "r" | "ins" | "moveTo" | "hyperlink") => check_text_content(dom, child)?,
976            (true, "t" | "tab") if !dom.has_elements(child) => {}
977            (true, "br")
978                if matches!(
979                    dom.attribute(child, &W::type_()),
980                    None | Some("textWrapping")
981                ) && !dom.has_elements(child) => {}
982            _ => return Err(codec_error(format!("unsupported text element {name:?}"))),
983        }
984    }
985    Ok(())
986}