Skip to main content

jubarte_edit/edit/
prepared.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! `PreparedEdit`: one preparation path for dry run and apply (V2-08).
6//!
7//! The plan resolves and applies in memory, the result serializes, and the
8//! *actual primary bytes* are chosen before final checks: the serialized
9//! candidate for a changed result, or the original source bytes verbatim
10//! for a truly unchanged one. Those chosen bytes are what findings, output
11//! references and digests describe — a reserialized package is never
12//! validated and then swapped for the source at commit. Dry run and apply
13//! share this whole path; they differ only at publication.
14
15use std::collections::{BTreeMap, HashMap, HashSet};
16
17use super::{
18    EditError, EditOutcome, EditPlan, EditResult, ExistingRevisions, OperationKind, Resolved,
19    StoryPart, Transaction, check_update_fields, comment_holds_kept_text, comment_text_of,
20    controls, enclose_deleted_paragraph_comment_references, lift_deletion_comments,
21    revision_counts, sections, tracked, whole,
22};
23use crate::comparer::WmlComparerSettings;
24use crate::inspect::{body_paragraph_nodes, project_paragraph, source_sha256};
25use crate::namespaces::W;
26use crate::result::{Effect, codes};
27use crate::validate::{self, Finding};
28
29/// A finding identity the publication policy compares on: rule set, code,
30/// part and the entity/range the finding points at. Findings are compared
31/// by identity, never by aggregate counts: a baseline warning healed beside
32/// a new same-code warning elsewhere still reports the new one.
33fn finding_key(f: &Finding) -> (String, String, String, String) {
34    (
35        f.set.clone(),
36        f.code.clone(),
37        f.part.clone(),
38        f.location.clone(),
39    )
40}
41
42/// The findings in `candidate` that `baseline` does not carry, first
43/// occurrence each, in `candidate` order.
44pub fn introduced_findings(baseline: &[Finding], candidate: &[Finding]) -> Vec<Finding> {
45    let held: HashSet<_> = baseline.iter().map(finding_key).collect();
46    let mut seen = HashSet::new();
47    candidate
48        .iter()
49        .filter(|f| !held.contains(&finding_key(f)))
50        .filter(|f| seen.insert(finding_key(f)))
51        .cloned()
52        .collect()
53}
54
55/// A non-`word_fatal` finding code that still blocks publication when the
56/// edit introduces it. `BOOKMARK_CROSSES_REVISION` is a protected-range
57/// regression the general validator reports as a warning; an introduced
58/// crossing is a failed invariant, never a disclosed lead.
59/// `CELL_FINAL_MARK_REVISION` opens in Word, but its Accept All or Reject
60/// All never returns (#1669).
61const BLOCKING_CODES: &[&str] = &["BOOKMARK_CROSSES_REVISION", "CELL_FINAL_MARK_REVISION"];
62
63/// Whether `f` blocks publication when it is newly introduced.
64fn blocking(f: &Finding) -> bool {
65    f.word_fatal || BLOCKING_CODES.contains(&f.code.as_str())
66}
67
68/// Which serialized bytes the prepared edit chose as its primary.
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub enum PrimaryBytes {
71    /// The original source, byte for byte: a truly unchanged primary is
72    /// never a reserialization.
73    Source,
74    /// The serialized candidate the engine produced.
75    Candidate,
76}
77
78/// The candidate's findings split by provenance.
79#[derive(Clone, Debug, Default, PartialEq, Eq)]
80pub struct CandidateChecks {
81    /// Findings the input already carried; disclosed, never blocking on
82    /// their own.
83    pub baseline: Vec<Finding>,
84    /// Findings the edit introduced. Only blocking ones fail preparation;
85    /// the rest are disclosed here.
86    pub introduced: Vec<Finding>,
87    /// Findings persisting in either validated representation, deduplicated by identity.
88    pub unresolved: Vec<Finding>,
89    /// Both serialized representations passed the required integrity gate.
90    pub integrity: bool,
91    /// DOM-realized and serialized-story postconditions completed successfully.
92    pub operation_postconditions: bool,
93}
94
95impl CandidateChecks {
96    /// Report only completed checks and their computed findings.
97    pub fn verification(&self) -> crate::result::Verification {
98        let outcome = |ran| if ran { "passed" } else { "skipped" }.to_string();
99        crate::result::Verification {
100            integrity: outcome(self.integrity),
101            operation_postconditions: outcome(self.operation_postconditions),
102            baseline_findings: Some(self.baseline.clone()),
103            introduced_findings: Some(self.introduced.clone()),
104            unresolved_findings: Some(self.unresolved.clone()),
105            ..Default::default()
106        }
107    }
108}
109
110/// Which serialized candidate is the prepared transaction's publication:
111/// the clean copy (changes accepted) or the redline (changes tracked).
112/// The role drives the bytes `prepare` chooses as `primary`, the digest
113/// it derives, and the serialized-story postcondition it runs: validation
114/// describes the chosen primary, not a reserialized package swapped in at
115/// commit. An unchanged transaction always returns the original source
116/// bytes, regardless of role.
117#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
118pub enum PrimaryRole {
119    /// Publish the clean (untracked) candidate. The default — preserves
120    /// the v1 helper callers, the Python and WASM bindings, and every
121    /// caller that has not chosen a publication track yet.
122    #[default]
123    Clean,
124    /// Publish the redline (tracked) candidate. The v1 typed CLI uses it;
125    /// `prepare_v2` likewise publishes redline, by construction.
126    Redline,
127}
128
129/// What to check beyond the shared candidate checks.
130#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub struct PrepareOptions {
132    /// Refuse `NO_CHANGES_REQUESTED` after the checks pass when the primary
133    /// has no document effect. Renders, reports and other derivatives are
134    /// not consulted: the condition judges the primary only.
135    pub require_change: bool,
136    /// Compare each `rewrite`'s requested text with the realized paragraph
137    /// exactly: a request the word-level rewrite algorithm normalizes away
138    /// is `POSTCONDITION_FAILED`, not an unchanged success. The v1 `rewrite`
139    /// contract documents that normalization, so it stays off there; the v2
140    /// exact-text codec sets it.
141    pub exact_text: bool,
142    /// Which serialized candidate `prepare` chooses as the publication.
143    /// `Clean` (the default) keeps the helper-callers' contract, where the
144    /// clean copy is the primary and the redline is a side artifact.
145    /// `Redline` makes the redline the primary: the chosen bytes the
146    /// serialized-story postcondition describes and the receipt digest
147    /// names, so a redline-only defect cannot slip through.
148    pub role: PrimaryRole,
149    /// The request syntax a refusal hint quotes: a flags-built plan names
150    /// flags, a JSON plan names JSON (#1108).
151    pub syntax: super::PlanSyntax,
152    /// `--skip-failed` (#1253): leave out every operation that fails, and
153    /// every operation of its `group`, instead of refusing the plan; the
154    /// rest is applied as a plan of its own. [`PreparedEdit::skipped`]
155    /// lists what was left out. A failure no operation is blamed for is
156    /// never skipped, and a plan whose every operation fails is refused.
157    pub skip_failed: bool,
158}
159
160impl Default for PrepareOptions {
161    fn default() -> Self {
162        Self {
163            require_change: false,
164            exact_text: false,
165            role: PrimaryRole::Clean,
166            syntax: super::PlanSyntax::V1,
167            skip_failed: false,
168        }
169    }
170}
171
172/// A plan applied and verified in memory, up to publication.
173#[derive(Clone, Debug)]
174pub struct PreparedEdit {
175    /// The v1 artifacts: clean copy, redline and per-operation report.
176    pub result: EditResult,
177    /// SHA-256 of the original source.
178    pub source_sha256: String,
179    /// SHA-256 of the normalized plan JSON the engine applied.
180    pub request_sha256: String,
181    /// The chosen primary bytes, the same bytes `checks` describe.
182    pub primary: Vec<u8>,
183    /// Which bytes `primary` holds.
184    pub primary_bytes: PrimaryBytes,
185    /// SHA-256 of `primary`: output digests come from the checked bytes.
186    pub primary_sha256: String,
187    /// The primary transaction's document effect (`changed`/`unchanged`
188    /// only; `not_applied` belongs to the dry-run envelope).
189    pub primary_effect: Effect,
190    /// Baseline and introduced findings on the primary's basis.
191    pub checks: CandidateChecks,
192    /// Source paragraph → chosen-primary correspondence for `--expect`
193    /// (V2-13). `None` on the v1 path, whose published primary is a
194    /// comparer redline with no tracked correspondence: a v1 plan plus
195    /// `--expect` refuses instead of guessing.
196    pub correspondence: Option<crate::expect::SourceToOutputCorrespondence>,
197    /// The operations [`PrepareOptions::skip_failed`] left out, in plan
198    /// order; empty otherwise.
199    pub skipped: Vec<super::SkippedOperation>,
200}
201
202/// Run the shared preparation: resolve, apply, choose the primary bytes,
203/// verify the serialized candidate, then apply `options` last. A dry run is
204/// this same result without publication.
205///
206/// # Errors
207///
208/// Every error [`crate::edit::apply_plan`] reports, plus
209/// `POSTCONDITION_FAILED` when a requested effect is not realized in the
210/// serialized candidate (or, with [`PrepareOptions::exact_text`], when the
211/// requested text differs from it), `CANDIDATE_INVALID` when the candidate
212/// introduces a blocking finding, and `NO_CHANGES_REQUESTED` under
213/// [`PrepareOptions::require_change`] when the primary is unchanged.
214pub fn prepare(
215    source: &[u8],
216    plan: &EditPlan,
217    options: &PrepareOptions,
218) -> Result<PreparedEdit, EditError> {
219    if options.skip_failed {
220        // Each attempt comes back here with `skip_failed` off: the whole
221        // plan, refused at its first failure.
222        return super::skip::prepare_skipping(source, plan, options);
223    }
224    let known = SourceChecks::default();
225    prepare_once(source, plan, options, &known).map_err(|failure| {
226        // A v1 plan's operations are independent (`check_conflicts`):
227        // any of them make a plan of their own.
228        let mut reruns = Reruns::new(|ops: &[usize]| {
229            let part = EditPlan {
230                operations: ops.iter().map(|&i| plan.operations[i].clone()).collect(),
231                ..plan.clone()
232            };
233            prepare_once(source, &part, options, &known)
234                .err()
235                .and_then(|f| f.refusal)
236                .map(|(refusals, _)| refusals)
237        })
238        .knowing(plan.operations.len(), &failure);
239        attributed(*failure, plan.operations.len(), true, &mut reruns)
240    })
241}
242
243/// `plan` prepared once for `--skip-failed`, which may leave out only its
244/// first `count` operations: the rest follow every rerun. A failure the
245/// candidate checks did not raise comes back [`Blame::Plain`]; a candidate
246/// refusal comes back with every defect attributed at once, the reruns
247/// shared, so a retry never bisects again what this one did.
248pub(super) fn prepare_blaming(
249    source: &[u8],
250    plan: &EditPlan,
251    count: usize,
252    options: &PrepareOptions,
253) -> Result<PreparedEdit, Box<Blame>> {
254    let known = SourceChecks::default();
255    let failure = match prepare_once(source, plan, options, &known) {
256        Ok(prepared) => return Ok(prepared),
257        Err(failure) => failure,
258    };
259    let Some((refusals, outcomes)) = failure.refusal.clone() else {
260        return Err(Box::new(Blame::Plain(failure.error)));
261    };
262    let mut reruns = Reruns::new(|ops: &[usize]| {
263        let part = EditPlan {
264            operations: ops
265                .iter()
266                .copied()
267                .chain(count..plan.operations.len())
268                .map(|i| plan.operations[i].clone())
269                .collect(),
270            ..plan.clone()
271        };
272        prepare_once(source, &part, options, &known)
273            .err()
274            .and_then(|f| f.refusal)
275            .map(|(refusals, _)| refusals)
276    })
277    .knowing(count, &failure);
278    let mut distinct: Vec<&Refusal> = Vec::new();
279    for refusal in &refusals {
280        if !distinct.iter().any(|d| d.same(refusal)) {
281            distinct.push(refusal);
282        }
283    }
284    // Each operation alone is one short preparation; a defect's bisection
285    // about log2(count) long ones. With about as many defects as
286    // operations over log2(count), the operations alone cost less: a
287    // defect an operation meets alone is blamed on that one alone.
288    let bits = (usize::BITS - count.leading_zeros()) as usize;
289    let alone = distinct.len() * bits >= count;
290    // Every defect, once: one the plan without operations meets too is
291    // the plan's own, and no operation left out clears it.
292    let mut blamed: Vec<(usize, EditError)> = Vec::new();
293    for refusal in distinct {
294        let single = alone
295            .then(|| (0..count).find(|&i| reruns.reproduces(&[i], refusal)))
296            .flatten()
297            .map(|i| vec![i]);
298        let Some(ops) =
299            single.or_else(|| culprits(count, true, |ops| reruns.reproduces(ops, refusal)))
300        else {
301            return Err(Box::new(Blame::Candidate(
302                attributed(*failure, count, true, &mut reruns),
303                Vec::new(),
304            )));
305        };
306        if !blamed.iter().any(|(i, _)| *i == ops[0]) {
307            let error = advised(
308                naming(refusal.error.clone(), &ops, &outcomes),
309                failure.advice,
310            );
311            blamed.push((ops[0], error));
312        }
313    }
314    // Each blamed operation carries its own error; the plan's is the
315    // refusal unattributed.
316    Err(Box::new(Blame::Candidate(failure.error, blamed)))
317}
318
319/// Why [`prepare_blaming`] refused a plan.
320pub(super) enum Blame {
321    /// A failure the candidate checks did not raise: its error, as
322    /// [`prepare`] reports it.
323    Plain(EditError),
324    /// A candidate refusal: the error [`prepare`] reports, and each
325    /// operation (plan index) a defect is blamed on, with the error that
326    /// names it for that defect, in the order the candidate checks met
327    /// them. Empty when a defect is the plan's own.
328    Candidate(EditError, Vec<(usize, EditError)>),
329}
330
331/// What the candidate checks read in the source, read once for a plan and
332/// every rerun of it.
333#[derive(Default)]
334struct SourceChecks {
335    /// `validate::validate(source)`, `None` when unreadable.
336    findings: std::cell::OnceCell<Option<Vec<Finding>>>,
337    /// `validate::revision_id_occurrences(source)`, `None` when unreadable.
338    revision_ids: std::cell::OnceCell<Option<HashMap<(String, String), usize>>>,
339}
340
341/// One defect a candidate gate refuses, as the attribution reruns compare
342/// it: the artifact refused, the finding's code (or the gate's own), its
343/// part, and its subject, which tells it from another defect of that code
344/// in that part and stays put when a rerun leaves operations out (a
345/// source's revision id, a bookmark's name; never an index or a minted
346/// id). `error` refuses the candidate for this defect.
347#[derive(Clone, Debug)]
348struct Refusal {
349    artifact: &'static str,
350    code: String,
351    part: String,
352    subject: String,
353    error: EditError,
354}
355
356impl Refusal {
357    /// The same defect: `error` aside, as reruns find it again.
358    fn same(&self, other: &Self) -> bool {
359        self.artifact == other.artifact
360            && self.code == other.code
361            && self.part == other.part
362            && self.subject == other.subject
363    }
364}
365
366/// A candidate gate's refusal: every defect it met, the one its error
367/// reports first. Never empty.
368type Refused = Vec<Refusal>;
369
370/// The refusal of one defect: `CANDIDATE_INVALID` with `message`.
371fn refused(
372    artifact: &'static str,
373    code: &str,
374    part: &str,
375    subject: String,
376    message: String,
377) -> Refusal {
378    Refusal {
379        artifact,
380        code: code.to_string(),
381        part: part.to_string(),
382        subject,
383        error: err("CANDIDATE_INVALID", None, message),
384    }
385}
386
387/// A failed preparation, and the candidate refusal behind it with every
388/// operation's outcome, when the candidate checks refused it. `advice`
389/// closes the message, after the operations [`attributed`] names.
390struct Failure {
391    error: EditError,
392    refusal: Option<(Refused, Vec<EditOutcome>)>,
393    advice: Option<&'static str>,
394}
395
396/// The candidate refusals reruns of some of a plan's operations meet, each
397/// set of operations prepared once.
398struct Reruns<F> {
399    rerun: F,
400    met: HashMap<Vec<usize>, Option<Refused>>,
401}
402
403impl<F: FnMut(&[usize]) -> Option<Refused>> Reruns<F> {
404    fn new(rerun: F) -> Self {
405        Self {
406            rerun,
407            met: HashMap::new(),
408        }
409    }
410
411    /// `failure`'s refusal as what the whole plan of `count` operations
412    /// meets: a rerun of them all is the preparation that failed.
413    fn knowing(mut self, count: usize, failure: &Failure) -> Self {
414        if let Some((refusals, _)) = &failure.refusal {
415            self.met
416                .insert((0..count).collect(), Some(refusals.clone()));
417        }
418        self
419    }
420
421    /// Whether the plan's operations `ops` alone meet `refusal`'s defect
422    /// again, among every defect they meet.
423    fn reproduces(&mut self, ops: &[usize], refusal: &Refusal) -> bool {
424        let rerun = &mut self.rerun;
425        self.met
426            .entry(ops.to_vec())
427            .or_insert_with(|| rerun(ops))
428            .as_ref()
429            .is_some_and(|met| met.iter().any(|r| r.same(refusal)))
430    }
431}
432
433/// `error` with `advice` closing its message.
434fn advised(mut error: EditError, advice: Option<&'static str>) -> EditError {
435    if let Some(advice) = advice {
436        error.message = format!("{}; {advice}", error.message);
437    }
438    error
439}
440
441impl From<EditError> for Box<Failure> {
442    fn from(error: EditError) -> Self {
443        Box::new(Failure {
444            error,
445            refusal: None,
446            advice: None,
447        })
448    }
449}
450
451/// `failure`'s error, naming the operations that cause the defect its
452/// candidate refusal reports first. `reruns` prepares only some of the
453/// plan's operations and tells whether they meet that defect again;
454/// [`culprits`] finds the operations from it, and [`naming`] names them. A
455/// failure the candidate checks did not raise, or one the plan without
456/// operations meets too, stays the plan's own (`operation` unset).
457fn attributed<F: FnMut(&[usize]) -> Option<Refused>>(
458    failure: Failure,
459    count: usize,
460    together: bool,
461    reruns: &mut Reruns<F>,
462) -> EditError {
463    let Failure {
464        error,
465        refusal,
466        advice,
467    } = failure;
468    let Some((refusals, outcomes)) = refusal else {
469        return advised(error, advice);
470    };
471    let Some(first) = refusals.first() else {
472        return advised(error, advice);
473    };
474    let Some(ops) = culprits(count, together, |ops| reruns.reproduces(ops, first)) else {
475        return advised(error, advice);
476    };
477    advised(naming(error, &ops, &outcomes), advice)
478}
479
480/// `error` naming the operations `ops` (plan indices, the one that brings
481/// the defect in first): the first becomes its `operation`, and the
482/// message names each by its id and target, from `outcomes`, or by its
483/// pointer (`/operations/N`) when `outcomes` has none.
484fn naming(mut error: EditError, ops: &[usize], outcomes: &[EditOutcome]) -> EditError {
485    let name = |i: usize| match outcomes.get(i) {
486        Some(EditOutcome {
487            id,
488            kind,
489            paragraph: Some(paragraph),
490            ..
491        }) => format!("{id} ({kind} on {paragraph})"),
492        Some(EditOutcome { id, kind, .. }) => format!("{id} ({kind})"),
493        None => format!("/operations/{i}"),
494    };
495    let Some(&cause) = ops.first() else {
496        return error;
497    };
498    error.operation = Some(match outcomes.get(cause) {
499        Some(outcome) => outcome.id.clone(),
500        None => format!("/operations/{cause}"),
501    });
502    error.message = format!("{}; {} introduces it", error.message, name(cause));
503    if let [_, others @ ..] = ops
504        && let Some((&last, rest)) = others.split_last()
505    {
506        let mut message = format!("{}, together with ", error.message);
507        for (n, &i) in rest.iter().enumerate() {
508            if n > 0 {
509                message.push_str(", ");
510            }
511            message.push_str(&name(i));
512        }
513        if !rest.is_empty() {
514            message.push_str(" and ");
515        }
516        message.push_str(&name(last));
517        error.message = message;
518    }
519    error
520}
521
522/// The operations (plan indices) that cause a refusal the whole plan of
523/// `count` operations meets: `reproduces(ops)` tells whether the plan's
524/// operations `ops` alone, in plan order, meet it again. The first is the
525/// operation that brings it in: the first prefix of the plan that
526/// reproduces it ends there, the prefix before it does not. Under
527/// `together` (operations independent of each other), the others are the
528/// earlier operations that one needs, when it does not reproduce the
529/// refusal alone, in plan order, each found the same way. `None` when the
530/// plan without operations reproduces it: no operation causes it.
531///
532/// Prefixes are bisected, so the reruns are logarithmic in `count`, once
533/// for the first operation and once for each other one.
534fn culprits(
535    count: usize,
536    together: bool,
537    mut reproduces: impl FnMut(&[usize]) -> bool,
538) -> Option<Vec<usize>> {
539    if count == 0 || reproduces(&[]) {
540        return None;
541    }
542    // Every prefix is a slice of this one list, built once.
543    let all: Vec<usize> = (0..count).collect();
544    // `lo` operations do not reproduce it; `hi` do: the whole plan does.
545    let (mut lo, mut hi) = (0, count);
546    while hi - lo > 1 {
547        let mid = lo + (hi - lo) / 2;
548        if reproduces(&all[..mid]) {
549            hi = mid;
550        } else {
551            lo = mid;
552        }
553    }
554    let first = hi - 1;
555    let mut needed = vec![first];
556    if !together {
557        return Some(needed);
558    }
559    let with = |pool: &[usize], needed: &[usize]| {
560        let mut ops: Vec<usize> = pool.iter().chain(needed).copied().collect();
561        ops.sort_unstable();
562        ops
563    };
564    // The candidates: the operations before the last one found. With all of
565    // them `needed` reproduces it (the whole prefix through `first` at the
566    // start, the prefix the last search ended on after it); with none,
567    // `needed` alone does not.
568    let mut pool = all[..first].to_vec();
569    while !reproduces(&with(&[], &needed)) {
570        let (mut lo, mut hi) = (0, pool.len());
571        while hi - lo > 1 {
572            let mid = lo + (hi - lo) / 2;
573            if reproduces(&with(&pool[..mid], &needed)) {
574                hi = mid;
575            } else {
576                lo = mid;
577            }
578        }
579        let Some(&next) = pool.get(hi.wrapping_sub(1)) else {
580            break;
581        };
582        needed.push(next);
583        pool.truncate(hi - 1);
584    }
585    needed[1..].sort_unstable();
586    Some(needed)
587}
588
589/// [`prepare`] without `skip_failed` and without attribution: the failure
590/// keeps the candidate refusal, if one was met, for [`attributed`].
591/// `known` holds what the candidate checks read in `source`.
592fn prepare_once(
593    source: &[u8],
594    plan: &EditPlan,
595    options: &PrepareOptions,
596    known: &SourceChecks,
597) -> Result<PreparedEdit, Box<Failure>> {
598    #[cfg(test)]
599    tests::PREPARATIONS.with(|count| count.set(count.get() + 1));
600    check_update_fields(plan)?;
601    let lowered = super::visible::lower(source, plan, options.syntax)?;
602    let plan = lowered.as_ref().unwrap_or(plan);
603    let mut tx = Transaction::start_quoting(source, plan, options.syntax)?;
604    tx.resolve()?;
605    tracked::check(&tx)?;
606    let emit = tx.emits_directly()?;
607    // `update_fields` compares an edit beside a range marker (#1156): a
608    // refused candidate then names the route that keeps the marker.
609    let compared_beside = !emit && plan.update_fields && tx.edits_beside_a_range_marker();
610    tx.apply()?;
611    check_dom_realized(&tx, options.exact_text)?;
612    let result = produce(&mut tx, emit, options.role)?;
613    let effect = primary_effect(&tx, &result)?;
614    let (primary, primary_bytes) = match effect {
615        Effect::Unchanged => (source.to_vec(), PrimaryBytes::Source),
616        _ => match options.role {
617            PrimaryRole::Clean => (result.clean.clone(), PrimaryBytes::Candidate),
618            PrimaryRole::Redline => (result.redline.clone(), PrimaryBytes::Candidate),
619        },
620    };
621    let mut checks = screen_candidates(source, &result, known)
622        .and_then(|checks| {
623            if compared_beside {
624                check_rejected_ranges(source, &result.redline)?;
625            }
626            Ok(checks)
627        })
628        .map_err(|refusals| {
629            Box::new(Failure {
630                error: refusals[0].error.clone(),
631                refusal: Some((refusals, tx.outcomes.clone())),
632                advice: compared_beside.then_some(
633                    "update_fields compares an edit beside a bookmark, comment or permission range, so drop update_fields and refresh the fields with `jubarte convert FILE --update-fields -o OUT.docx` afterwards",
634                ),
635            })
636        })?;
637    checks.operation_postconditions = true;
638    if options.require_change && effect == Effect::Unchanged {
639        return Err(err(
640            codes::NO_CHANGES_REQUESTED,
641            None,
642            "the primary transaction has no document effect; --require-change was given",
643        )
644        .into());
645    }
646    Ok(PreparedEdit {
647        result,
648        source_sha256: source_sha256(source),
649        request_sha256: source_sha256(plan.to_json().as_bytes()),
650        primary_sha256: source_sha256(&primary),
651        primary,
652        primary_bytes,
653        primary_effect: effect,
654        checks,
655        correspondence: None,
656        skipped: Vec::new(),
657    })
658}
659
660/// Whether the edit updated a field. Field updates need the renderer, so a
661/// build without it updates none.
662#[cfg(feature = "render")]
663fn fields_updated(report: &super::EditReport) -> bool {
664    !report.fields.is_empty()
665}
666
667#[cfg(not(feature = "render"))]
668fn fields_updated(_report: &super::EditReport) -> bool {
669    false
670}
671
672/// The primary transaction's document effect. Aggregated text equality
673/// alone never proves `unchanged`: revision resolution, comments, thread
674/// state, formatting, media, fields and structure are effects too.
675fn primary_effect(tx: &Transaction<'_>, result: &EditResult) -> Result<Effect, EditError> {
676    let report = &result.report;
677    if !report.resolved_revisions.is_empty()
678        || report.revisions.total > 0
679        || report.paragraphs.from != report.paragraphs.to
680        || fields_updated(report)
681        || report.comments_added > 0
682        || tx.watermark.is_some()
683        || tx.settings.is_some()
684        || tx.notes_story.is_some()
685    {
686        return Ok(Effect::Changed);
687    }
688    for (op, resolved) in &tx.resolved {
689        // Only plain text operations can be truly no-effect; a comment,
690        // thread, formatting, control, table or structural resolution is an
691        // effect even when the aggregated text is equal. A `redact`
692        // resolves as text but empties the base too, so the diff misses it.
693        if !matches!(resolved, Resolved::Text { .. })
694            || !matches!(
695                tx.plan.operations[*op].kind,
696                OperationKind::Replace { .. }
697                    | OperationKind::Insert { .. }
698                    | OperationKind::Delete { .. }
699                    | OperationKind::Rewrite { .. }
700            )
701        {
702            return Ok(Effect::Changed);
703        }
704    }
705    // A text edit that meant to change the text is an effect even when the
706    // engine wrote nothing for it.
707    if expected_texts(tx, false)?.into_iter().any(|(p, e)| {
708        matches!(e.scope, ExpectedScope::Paragraph) && e.text != tx.projections[p].text
709    }) {
710        return Ok(Effect::Changed);
711    }
712    Ok(Effect::Unchanged)
713}
714
715/// Reject All of `redline` gives the source back, so it keeps each of the
716/// source's bookmarks (by name; Word's own `_GoBack` aside), comment ranges
717/// and permission ranges. Compare places them by the words around them and
718/// can carry one into an insertion, which Reject All then removes: the
719/// TOC entry linking to a heading's `_Toc` bookmark reads "Error! Bookmark
720/// not defined." (#1156).
721fn check_rejected_ranges(source: &[u8], redline: &[u8]) -> Result<(), Refused> {
722    let rejected = crate::document_comparer::reject_revisions(redline).map_err(|e| {
723        vec![refused(
724            "redline",
725            "REJECT_FAILED",
726            "",
727            String::new(),
728            format!("the redline cannot be rejected: {e}"),
729        )]
730    })?;
731    let (before, after) = (range_markers(source), range_markers(&rejected));
732    let lost = before
733        .bookmarks
734        .difference(&after.bookmarks)
735        .map(|name| format!("bookmark {name}"))
736        .chain((after.comments < before.comments).then(|| "a comment's range".to_string()))
737        .chain((after.permissions < before.permissions).then(|| "a permission range".to_string()))
738        .collect::<Vec<_>>();
739    if lost.is_empty() {
740        return Ok(());
741    }
742    // The ranges lost, together, are the defect: a rerun that loses only
743    // some of them meets another.
744    let lost = lost.join(", ");
745    Err(vec![refused(
746        "redline",
747        "RANGE_LOST",
748        "",
749        lost.clone(),
750        format!("Reject All of the redline drops {lost} the source holds"),
751    )])
752}
753
754/// The range markers of a package's stories: bookmark names, and how many
755/// comment and permission ranges open.
756#[derive(Default)]
757struct RangeMarkers {
758    bookmarks: std::collections::BTreeSet<String>,
759    comments: usize,
760    permissions: usize,
761}
762
763fn range_markers(docx: &[u8]) -> RangeMarkers {
764    let mut markers = RangeMarkers::default();
765    let Ok(opened) = crate::inspect::Opened::open(docx) else {
766        return markers;
767    };
768    let mut parts = vec![opened.main.clone()];
769    parts.extend(opened.story_parts().into_iter().map(|(_, _, part)| part));
770    for part in parts {
771        let Ok((dom, _, root)) = crate::inspect::parse_part(&opened.pkg, &part) else {
772            continue;
773        };
774        for start in dom.descendants(root, Some(&W::bookmark_start())) {
775            if let Some(name) = dom.attribute(start, &W::name("name"))
776                && name != "_GoBack"
777            {
778                markers.bookmarks.insert(name.to_string());
779            }
780        }
781        markers.comments += dom.descendants(root, Some(&W::comment_range_start())).len();
782        markers.permissions += dom.descendants(root, Some(&W::perm_start())).len();
783    }
784    markers
785}
786
787/// Findings on the input and what each serialized artifact adds. The
788/// baseline discloses without blocking; an introduced blocking finding
789/// fails preparation.
790#[cfg(test)]
791fn check_candidates(source: &[u8], result: &EditResult) -> Result<CandidateChecks, EditError> {
792    screen_candidates(source, result, &SourceChecks::default())
793        .map_err(|refusals| refusals[0].error.clone())
794}
795
796/// The candidate gates, with every defect they meet (the test-only
797/// `check_candidates` keeps the first), in
798/// the order they meet them: the clean copy's, then the redline's; in each,
799/// the duplicate revision ids, then the introduced blocking findings. The
800/// first is the one the refusal reports, as when the gates stopped there;
801/// the others let a rerun tell whether it meets that defect again.
802/// `known` holds what the gates read in `source`.
803fn screen_candidates(
804    source: &[u8],
805    result: &EditResult,
806    known: &SourceChecks,
807) -> Result<CandidateChecks, Refused> {
808    // A source the validator cannot read gives no trustworthy baseline:
809    // an empty one would call every candidate finding introduced, so with
810    // no baseline nothing is claimed introduced (the candidate's own
811    // validation below still gates what the edit produced).
812    let baseline = known
813        .findings
814        .get_or_init(|| validate::validate(source).ok())
815        .as_ref();
816    let mut refusals = Vec::new();
817    let mut introduced = Vec::new();
818    let mut unresolved = Vec::new();
819    for (artifact, bytes) in [("clean copy", &result.clean), ("redline", &result.redline)] {
820        // An unreadable artifact ends the checks; the defects met before
821        // it still come first.
822        let findings = match validate::validate(bytes) {
823            Ok(findings) => findings,
824            Err(e) => {
825                refusals.push(refused(
826                    artifact,
827                    "UNREADABLE",
828                    "",
829                    String::new(),
830                    format!("the serialized candidate cannot be validated: {e}"),
831                ));
832                return Err(refusals);
833            }
834        };
835        // Counted only when a candidate repeats an id at all: its own
836        // `DUPLICATE_REVISION_ID` reads the same parts, records and keys.
837        if findings.iter().any(|f| f.code == "DUPLICATE_REVISION_ID")
838            && let Some(source_ids) = known
839                .revision_ids
840                .get_or_init(|| validate::revision_id_occurrences(source).ok())
841        {
842            match check_revision_ids(source_ids, artifact, bytes) {
843                Ok(duplicates) => refusals.extend(duplicates),
844                Err(unreadable) => {
845                    refusals.extend(unreadable);
846                    return Err(refusals);
847                }
848            }
849        }
850        for finding in &findings {
851            if !unresolved
852                .iter()
853                .any(|f| finding_key(f) == finding_key(finding))
854            {
855                unresolved.push(finding.clone());
856            }
857        }
858        let Some(baseline) = baseline else {
859            continue;
860        };
861        // A block placed before a finding shifts its sibling indices. The
862        // finding is still the one the source had when a stable anchor
863        // (paragraph id, revision id, or that element's own text) finds it.
864        // Only findings of a code the candidate seems to introduce are
865        // relocated, so an edit that introduces nothing reads no XML here
866        // (#2127 review).
867        let suspects: HashSet<String> = introduced_findings(baseline, &findings)
868            .into_iter()
869            .map(|finding| finding.code)
870            .collect();
871        let baseline = if suspects.is_empty() {
872            baseline.to_vec()
873        } else {
874            relocate_findings(source, bytes, baseline, &suspects)
875        };
876        for finding in introduced_findings(&baseline, &findings) {
877            if blocking(&finding) {
878                refusals.push(refused(
879                    artifact,
880                    &finding.code,
881                    &finding.part,
882                    finding.unnumbered(),
883                    format!(
884                        "the edit introduces {} in {}#{}: {}",
885                        finding.code, finding.part, finding.location, finding.message
886                    ),
887                ));
888                continue;
889            }
890            if !introduced
891                .iter()
892                .any(|f| finding_key(f) == finding_key(&finding))
893            {
894                introduced.push(finding);
895            }
896        }
897    }
898    if !refusals.is_empty() {
899        return Err(refusals);
900    }
901    Ok(CandidateChecks {
902        baseline: baseline.cloned().unwrap_or_default(),
903        introduced,
904        unresolved,
905        integrity: true,
906        operation_postconditions: false,
907    })
908}
909
910struct ParsedPart {
911    dom: crate::xmllinq::Dom,
912    root: crate::xmllinq::NodeId,
913    /// Same-name children per parent, with each child's text and revision
914    /// marks, built once per part: every finding's walk reads them, and a
915    /// part with many findings would otherwise rescan its siblings for
916    /// each (#2127 review).
917    siblings: HashMap<(crate::xmllinq::NodeId, String, String), std::rc::Rc<Siblings>>,
918}
919
920struct Siblings {
921    nodes: Vec<crate::xmllinq::NodeId>,
922    texts: Vec<String>,
923    marks: Vec<Vec<(String, String)>>,
924    /// How many siblings carry each text.
925    text_counts: HashMap<String, usize>,
926}
927
928impl ParsedPart {
929    fn siblings(
930        &mut self,
931        parent: crate::xmllinq::NodeId,
932        namespace: &str,
933        local: &str,
934    ) -> std::rc::Rc<Siblings> {
935        let key = (parent, namespace.to_string(), local.to_string());
936        if let Some(found) = self.siblings.get(&key) {
937            return std::rc::Rc::clone(found);
938        }
939        let nodes = named_children(&self.dom, parent, namespace, local);
940        let texts: Vec<String> = nodes.iter().map(|&node| self.dom.value(node)).collect();
941        let marks = nodes
942            .iter()
943            .map(|&node| revision_marks(&self.dom, node))
944            .collect();
945        let mut text_counts = HashMap::new();
946        for text in &texts {
947            *text_counts.entry(text.clone()).or_insert(0) += 1;
948        }
949        let built = std::rc::Rc::new(Siblings {
950            nodes,
951            texts,
952            marks,
953            text_counts,
954        });
955        self.siblings.insert(key, std::rc::Rc::clone(&built));
956        built
957    }
958}
959
960/// Baseline findings of a `suspects` code with locations rewritten to where
961/// the same element sits in `candidate`. An element the candidate no longer
962/// has, or that cannot be told from a sibling, keeps the location the
963/// source reported. Both packages are read as Transitional, as validation
964/// reads a Strict one, so the locations name the same elements (#2127
965/// review).
966fn relocate_findings(
967    source: &[u8],
968    candidate: &[u8],
969    baseline: &[Finding],
970    suspects: &HashSet<String>,
971) -> Vec<Finding> {
972    let (Ok(source), Ok(candidate)) = (
973        crate::strict_translation::strict_to_transitional_docx(source),
974        crate::strict_translation::strict_to_transitional_docx(candidate),
975    ) else {
976        return baseline.to_vec();
977    };
978    let Ok(source_pkg) = crate::opc::PartFs::open(&source) else {
979        return baseline.to_vec();
980    };
981    let Ok(candidate_pkg) = crate::opc::PartFs::open(&candidate) else {
982        return baseline.to_vec();
983    };
984    let mut source_parts = HashMap::new();
985    let mut candidate_parts = HashMap::new();
986    baseline
987        .iter()
988        .map(|finding| {
989            let mut finding = finding.clone();
990            if !suspects.contains(&finding.code) {
991                return finding;
992            }
993            if let Some(location) = moved_location(
994                &source_pkg,
995                &candidate_pkg,
996                &mut source_parts,
997                &mut candidate_parts,
998                &finding.part,
999                &finding.location,
1000            ) {
1001                finding.r#ref.clone_from(&location);
1002                finding.location = location;
1003            }
1004            finding
1005        })
1006        .collect()
1007}
1008
1009fn ensure_part(
1010    pkg: &crate::opc::PartFs,
1011    cache: &mut HashMap<String, ParsedPart>,
1012    part: &str,
1013) -> Option<()> {
1014    if cache.contains_key(part) {
1015        return Some(());
1016    }
1017    let (dom, _, root) = crate::inspect::parse_part(pkg, part).ok()?;
1018    cache.insert(
1019        part.to_string(),
1020        ParsedPart {
1021            dom,
1022            root,
1023            siblings: HashMap::new(),
1024        },
1025    );
1026    Some(())
1027}
1028
1029fn moved_location(
1030    source_pkg: &crate::opc::PartFs,
1031    candidate_pkg: &crate::opc::PartFs,
1032    source_parts: &mut HashMap<String, ParsedPart>,
1033    candidate_parts: &mut HashMap<String, ParsedPart>,
1034    part: &str,
1035    location: &str,
1036) -> Option<String> {
1037    if !location.contains('[') {
1038        return None;
1039    }
1040    ensure_part(source_pkg, source_parts, part)?;
1041    ensure_part(candidate_pkg, candidate_parts, part)?;
1042    let source = source_parts.get_mut(part)?;
1043    let candidate = candidate_parts.get_mut(part)?;
1044    let mut source_node = source.root;
1045    let mut candidate_node = candidate.root;
1046    let mut steps = Vec::new();
1047    for step in location.split('/') {
1048        let (namespace, local, index) = parse_step(step)?;
1049        let source_siblings = source.siblings(source_node, &namespace, &local);
1050        let candidate_siblings = candidate.siblings(candidate_node, &namespace, &local);
1051        let source_child = *source_siblings.nodes.get(index)?;
1052        let new_index = match_child(
1053            &source.dom,
1054            index,
1055            &source_siblings,
1056            &candidate.dom,
1057            &candidate_siblings,
1058        )?;
1059        let candidate_child = candidate_siblings.nodes[new_index];
1060        let name = step.split_once('[').map_or(step, |(name, _)| name);
1061        steps.push(format!("{name}[{new_index}]"));
1062        source_node = source_child;
1063        candidate_node = candidate_child;
1064    }
1065    let relocated = steps.join("/");
1066    (relocated != location).then_some(relocated)
1067}
1068
1069fn parse_step(step: &str) -> Option<(String, String, usize)> {
1070    let (name, rest) = step.strip_suffix(']')?.split_once('[')?;
1071    let index = rest.parse().ok()?;
1072    let (namespace, local) = match name.split_once(':') {
1073        Some((prefix, local)) => (
1074            crate::xmllinq::serialize::well_known_namespace(prefix)?.to_string(),
1075            local.to_string(),
1076        ),
1077        None => (String::new(), name.to_string()),
1078    };
1079    Some((namespace, local, index))
1080}
1081
1082fn named_children(
1083    dom: &crate::xmllinq::Dom,
1084    parent: crate::xmllinq::NodeId,
1085    namespace: &str,
1086    local: &str,
1087) -> Vec<crate::xmllinq::NodeId> {
1088    dom.elements(parent, None)
1089        .into_iter()
1090        .filter(|&element| {
1091            dom.name(element).is_some_and(|name| {
1092                name.local_name() == local && name.namespace_name() == namespace
1093            })
1094        })
1095        .collect()
1096}
1097
1098/// The index among `candidate` of the sibling that is `source.nodes[index]`,
1099/// told apart by paragraph id, its own revision, its revision marks, or its
1100/// text (an empty text too, #2127 review), each only when that anchor is
1101/// unique on both sides; else by position when no sibling came or went.
1102fn match_child(
1103    source_dom: &crate::xmllinq::Dom,
1104    index: usize,
1105    source: &Siblings,
1106    candidate_dom: &crate::xmllinq::Dom,
1107    candidate: &Siblings,
1108) -> Option<usize> {
1109    let node = source.nodes[index];
1110    let para_id = crate::namespaces::W14::para_id();
1111    if let Some(id) = source_dom.attribute(node, &para_id)
1112        && let Some(found) = sole_index(&candidate.nodes, |sibling| {
1113            candidate_dom.attribute(sibling, &para_id) == Some(id)
1114        })
1115        && sole_index(&source.nodes, |sibling| {
1116            source_dom.attribute(sibling, &para_id) == Some(id)
1117        })
1118        .is_some()
1119    {
1120        return Some(found);
1121    }
1122    if let Some(revision) = own_revision(source_dom, node)
1123        && let Some(found) = sole_index(&candidate.nodes, |sibling| {
1124            own_revision(candidate_dom, sibling).as_ref() == Some(&revision)
1125        })
1126    {
1127        return Some(found);
1128    }
1129    let marks = &source.marks[index];
1130    if !marks.is_empty()
1131        && source.marks.iter().filter(|other| *other == marks).count() == 1
1132        && let Some(found) = unique_position(&candidate.marks, marks)
1133    {
1134        return Some(found);
1135    }
1136    let text = &source.texts[index];
1137    if source.text_counts.get(text) == Some(&1) && candidate.text_counts.get(text) == Some(&1) {
1138        return candidate.texts.iter().position(|other| other == text);
1139    }
1140    (source.nodes.len() == candidate.nodes.len()).then_some(index)
1141}
1142
1143fn unique_position<T: PartialEq>(items: &[T], wanted: &T) -> Option<usize> {
1144    let mut found = None;
1145    for (at, item) in items.iter().enumerate() {
1146        if item != wanted {
1147            continue;
1148        }
1149        if found.is_some() {
1150            return None;
1151        }
1152        found = Some(at);
1153    }
1154    found
1155}
1156
1157fn sole_index(
1158    nodes: &[crate::xmllinq::NodeId],
1159    mut pred: impl FnMut(crate::xmllinq::NodeId) -> bool,
1160) -> Option<usize> {
1161    let mut found = None;
1162    for (at, &node) in nodes.iter().enumerate() {
1163        if !pred(node) {
1164            continue;
1165        }
1166        if found.is_some() {
1167            return None;
1168        }
1169        found = Some(at);
1170    }
1171    found
1172}
1173
1174fn own_revision(
1175    dom: &crate::xmllinq::Dom,
1176    node: crate::xmllinq::NodeId,
1177) -> Option<(String, String)> {
1178    let id = dom.attribute(node, &W::id())?;
1179    dom.attribute(node, &W::author())?;
1180    Some((dom.name(node)?.local_name().to_string(), id.to_string()))
1181}
1182
1183fn revision_marks(
1184    dom: &crate::xmllinq::Dom,
1185    node: crate::xmllinq::NodeId,
1186) -> Vec<(String, String)> {
1187    let mut marks: Vec<(String, String)> = std::iter::once(node)
1188        .chain(dom.descendants(node, None))
1189        .filter_map(|element| own_revision(dom, element))
1190        .collect();
1191    marks.sort();
1192    marks.dedup();
1193    marks
1194}
1195
1196/// A candidate may not give a revision id a same-kind duplicate the source
1197/// did not have: per part, record type and id, an id that occurs more than
1198/// once may occur no more often than in the source. Inherited duplicates
1199/// pass, healing one hides no collision under another, and kinds may share
1200/// an id. `jubarte validate` still calls the duplicate non-fatal: Word
1201/// opens it; publication refuses it. `artifact` names the candidate; every
1202/// duplicate it introduces is one defect, in key order. An id the source
1203/// holds is the defect's subject; one the edit minted is not, since a rerun
1204/// of fewer operations mints others.
1205fn check_revision_ids(
1206    source: &HashMap<(String, String), usize>,
1207    artifact: &'static str,
1208    candidate: &[u8],
1209) -> Result<Vec<Refusal>, Refused> {
1210    let occurrences = validate::revision_id_occurrences(candidate).map_err(|e| {
1211        vec![refused(
1212            artifact,
1213            "UNREADABLE",
1214            "",
1215            String::new(),
1216            format!("the serialized candidate cannot be read: {e}"),
1217        )]
1218    })?;
1219    let mut introduced: Vec<_> = occurrences
1220        .iter()
1221        .filter(|&(key, &count)| count > 1 && count > source.get(key).copied().unwrap_or(0))
1222        .collect();
1223    introduced.sort();
1224    Ok(introduced
1225        .into_iter()
1226        .map(|(entry, &count)| {
1227            let (part, key) = entry;
1228            let mut fields = key.splitn(3, ':');
1229            let (kind, mark, id) = (
1230                fields.next().unwrap_or_default(),
1231                fields.next() == Some("true"),
1232                fields.next().unwrap_or_default(),
1233            );
1234            let mark = if mark { " on a mark" } else { "" };
1235            let had = source.get(entry).copied().unwrap_or(0);
1236            let subject = if had > 0 {
1237                format!("w:{kind}{mark} w:id {id}")
1238            } else {
1239                format!("w:{kind}{mark}")
1240            };
1241            refused(
1242                artifact,
1243                "DUPLICATE_REVISION_ID",
1244                part,
1245                subject,
1246                format!(
1247                    "the edit introduces a duplicate revision id in the {artifact}: w:{kind}{mark} w:id {id} occurs {count} times in {part} (the source has {had})"
1248                ),
1249            )
1250        })
1251        .collect())
1252}
1253
1254/// What one paragraph reads as once the plan applies, and whether symbol
1255/// placeholders are out of the comparison.
1256struct ExpectedText {
1257    /// The operation that defined it (`op-N`), for error reports.
1258    op: String,
1259    /// The expected exact logical text.
1260    text: String,
1261    /// Compare without U+FFFC placeholders: a `rewrite` keeps the
1262    /// paragraph's symbols wherever they sit.
1263    ignore_symbols: bool,
1264    /// What `text` covers.
1265    scope: ExpectedScope,
1266}
1267
1268/// The part of a paragraph an [`ExpectedText`] covers.
1269#[derive(Clone, Copy)]
1270enum ExpectedScope {
1271    /// The paragraph's projected text.
1272    Paragraph,
1273    /// The content of a content control: the value indexes
1274    /// `Transaction::controls`. A `fill_control` replaces its control's
1275    /// projected text, which the span composition cannot predict, so the
1276    /// fill's own requested value is the postcondition instead.
1277    Control(usize),
1278}
1279
1280/// The exact text each paragraph must read as in the candidate: resolution
1281/// composed over the base projection, or, under `exact`, the `rewrite`'s
1282/// requested text itself — so a requested change the algorithm normalizes
1283/// away is detected instead of passing as a no-op.
1284fn expected_texts(
1285    tx: &Transaction<'_>,
1286    exact: bool,
1287) -> Result<Vec<(usize, ExpectedText)>, EditError> {
1288    /// `para` → (first op id, `(start, end, replacement, op, restore,
1289    /// attach_before)` spans).
1290    type Spans = (String, Vec<(usize, usize, String, usize, bool, bool)>);
1291    let mut edits: BTreeMap<usize, Spans> = BTreeMap::new();
1292    let mut merges = Vec::new();
1293    let mut filled: HashSet<usize> = HashSet::new();
1294    // `(para, control, requested text, op id)` — a fill's own postcondition.
1295    let mut fills = Vec::new();
1296    for (op, resolved) in &tx.resolved {
1297        match resolved {
1298            Resolved::Text {
1299                para,
1300                start,
1301                end,
1302                replacement,
1303                attach_before,
1304                ..
1305            } => {
1306                let entry = edits
1307                    .entry(*para)
1308                    .or_insert_with(|| (tx.outcomes[*op].id.clone(), Vec::new()));
1309                entry.1.push((
1310                    *start,
1311                    *end,
1312                    replacement.clone(),
1313                    *op,
1314                    false,
1315                    *attach_before,
1316                ));
1317            }
1318            // A restore's copy is text inserted where the deletion is.
1319            Resolved::Restore { para, at, text, .. } => {
1320                let entry = edits
1321                    .entry(*para)
1322                    .or_insert_with(|| (tx.outcomes[*op].id.clone(), Vec::new()));
1323                entry.1.push((*at, *at, text.clone(), *op, true, false));
1324            }
1325            Resolved::MergeParagraphs {
1326                para,
1327                next,
1328                separator,
1329                ..
1330            } => {
1331                merges.push((*para, *next, separator.clone(), tx.outcomes[*op].id.clone()));
1332            }
1333            Resolved::FillControl {
1334                control,
1335                paragraphs,
1336                value,
1337                ..
1338            } => {
1339                let text = match value {
1340                    controls::FillValue::Text(text) | controls::FillValue::Date { text, .. } => {
1341                        text.clone()
1342                    }
1343                    controls::FillValue::Checked { glyph, .. } => glyph.to_string(),
1344                };
1345                for para in paragraphs {
1346                    fills.push((*para, *control, text.clone(), tx.outcomes[*op].id.clone()));
1347                }
1348                filled.extend(paragraphs.iter().copied());
1349            }
1350            _ => {}
1351        }
1352    }
1353    let mut expected = BTreeMap::new();
1354    for (para, (op, mut spans)) in edits {
1355        let rewrite = if exact { rewrite_text(tx, para) } else { None };
1356        let rewrite_op = rewrite.as_ref().map(|&(op, _)| op);
1357        let base = &tx.projections[para].text;
1358        // A restore's copy follows its deletion, ahead of the visible text
1359        // that starts where the deletion is; other spans keep their order,
1360        // but in an empty paragraph the start edge's text comes first, as
1361        // `sort_edits` applies it (#1303).
1362        let empty = base.is_empty();
1363        // Match the writers' source-range order: an insertion at a removal's
1364        // start precedes that removal, independent of plan order (#1922).
1365        spans.sort_by_key(|&(start, end, _, op, restore, after)| {
1366            (start, !restore, end, empty && after, op)
1367        });
1368        let mut text = String::with_capacity(base.len());
1369        // The rewrite's own spans alone, composed on the base: a rewrite
1370        // beside co-resident edits must still realize its request, or the
1371        // failure is the rewrite's, not the composed text's.
1372        let mut own = String::with_capacity(base.len());
1373        let mut at = 0;
1374        let mut own_at = 0;
1375        let mut previous_op = None;
1376        for (start, end, replacement, span_op, ..) in spans {
1377            let conflict = || {
1378                let previous = previous_op.unwrap_or(span_op);
1379                tx.conflict(
1380                    span_op,
1381                    &format!(
1382                        "{} and {} have text ranges that cannot be composed in p{para}",
1383                        tx.outcomes[previous].id, tx.outcomes[span_op].id
1384                    ),
1385                )
1386            };
1387            // Check every bound, including UTF-8 boundaries. Even an invalid
1388            // resolved span must refuse rather than reach slice_error_fail.
1389            let gap = base.get(at..start).ok_or_else(conflict)?;
1390            base.get(start..end).ok_or_else(conflict)?;
1391            text.push_str(gap);
1392            text.push_str(&replacement);
1393            at = end;
1394            if Some(span_op) == rewrite_op {
1395                own.push_str(base.get(own_at..start).ok_or_else(conflict)?);
1396                own.push_str(&replacement);
1397                own_at = end;
1398            }
1399            previous_op = Some(span_op);
1400        }
1401        // Both cursors came from a checked span (or remain at zero).
1402        text.push_str(base.get(at..).ok_or_else(|| {
1403            tx.conflict(
1404                previous_op.unwrap_or(0),
1405                "text range ends outside the paragraph",
1406            )
1407        })?);
1408        own.push_str(base.get(own_at..).ok_or_else(|| {
1409            tx.conflict(
1410                rewrite_op.unwrap_or(0),
1411                "rewrite range ends outside the paragraph",
1412            )
1413        })?);
1414        if let Some((rewrite_op, requested)) = rewrite {
1415            let entry = if own == requested {
1416                // The rewrite's own edits realize its request: the
1417                // postcondition is the full composition — the request with
1418                // every co-resident edit applied — never the bare request
1419                // discarding a neighbour's effect.
1420                ExpectedText {
1421                    op,
1422                    text,
1423                    ignore_symbols: true,
1424                    scope: ExpectedScope::Paragraph,
1425                }
1426            } else {
1427                ExpectedText {
1428                    op: tx.outcomes[rewrite_op].id.clone(),
1429                    text: requested,
1430                    ignore_symbols: true,
1431                    scope: ExpectedScope::Paragraph,
1432                }
1433            };
1434            expected.insert(para, entry);
1435            continue;
1436        }
1437        expected.insert(
1438            para,
1439            ExpectedText {
1440                op,
1441                text,
1442                ignore_symbols: false,
1443                scope: ExpectedScope::Paragraph,
1444            },
1445        );
1446    }
1447    // A rewrite that resolved to no edits still has a postcondition.
1448    if exact {
1449        for (i, op) in tx.plan.operations.iter().enumerate() {
1450            let OperationKind::Rewrite {
1451                paragraph, text, ..
1452            } = &op.kind
1453            else {
1454                continue;
1455            };
1456            if comment_text_of(paragraph).is_some() {
1457                continue;
1458            }
1459            let Some(para) = outcome_paragraph(tx, i) else {
1460                continue;
1461            };
1462            expected.entry(para).or_insert_with(|| ExpectedText {
1463                op: tx.outcomes[i].id.clone(),
1464                text: text.clone(),
1465                ignore_symbols: true,
1466                scope: ExpectedScope::Paragraph,
1467            });
1468        }
1469    }
1470    for (para, next, separator, op) in merges {
1471        let survivor = expected
1472            .get(&next)
1473            .map(|e| e.text.clone())
1474            .unwrap_or_else(|| tx.projections[next].text.clone());
1475        let first = expected
1476            .get(&para)
1477            .map(|e| e.text.clone())
1478            .unwrap_or_else(|| tx.projections[para].text.clone());
1479        expected.insert(
1480            next,
1481            ExpectedText {
1482                op,
1483                text: format!("{first}{separator}{survivor}"),
1484                ignore_symbols: false,
1485                scope: ExpectedScope::Paragraph,
1486            },
1487        );
1488        expected.remove(&para);
1489    }
1490    for para in filled {
1491        expected.remove(&para);
1492    }
1493    let mut out: Vec<(usize, ExpectedText)> = expected.into_iter().collect();
1494    for (para, control, text, op) in fills {
1495        out.push((
1496            para,
1497            ExpectedText {
1498                op,
1499                text,
1500                ignore_symbols: false,
1501                scope: ExpectedScope::Control(control),
1502            },
1503        ));
1504    }
1505    out.sort_by_key(|(para, _)| *para);
1506    Ok(out)
1507}
1508
1509/// The first `rewrite` op on `para` and the text it asks for, or `None`
1510/// when no rewrite op resolved onto it (`cN.text` rewrites excluded: their
1511/// target is the covered span, not the paragraph).
1512fn rewrite_text(tx: &Transaction<'_>, para: usize) -> Option<(usize, String)> {
1513    tx.plan.operations.iter().enumerate().find_map(|(i, op)| {
1514        let OperationKind::Rewrite {
1515            paragraph, text, ..
1516        } = &op.kind
1517        else {
1518            return None;
1519        };
1520        if comment_text_of(paragraph).is_some() {
1521            return None;
1522        }
1523        (outcome_paragraph(tx, i) == Some(para)).then(|| (i, text.clone()))
1524    })
1525}
1526
1527/// The paragraph index an outcome names (`p3`, `header1.p1`, …) inside the
1528/// transaction's story list.
1529fn outcome_paragraph(tx: &Transaction<'_>, op: usize) -> Option<usize> {
1530    let id = tx.outcomes[op].paragraph.as_deref()?;
1531    let (story, index) = crate::ids::paragraph_place(id)?;
1532    let story = tx.stories.iter().position(|s| s.id == story)?;
1533    tx.paragraph_story
1534        .iter()
1535        .position(|&(s, i)| s == story && i == index)
1536}
1537
1538/// `para`'s node still belongs to its story in the mutated DOM.
1539fn attached(tx: &Transaction<'_>, para: usize) -> bool {
1540    let node = tx.paragraph_nodes[para];
1541    let (story, _) = tx.paragraph_story[para];
1542    let root = tx.stories[story].root;
1543    node == root || tx.opened.dom.ancestors(node, None).contains(&root)
1544}
1545
1546/// Each expected paragraph reads exactly so after apply, in the DOM the
1547/// candidate is serialized from. A realized difference is
1548/// `POSTCONDITION_FAILED` with the plan's outcomes, never a silent miss.
1549pub(super) fn check_dom_realized(tx: &Transaction<'_>, exact: bool) -> Result<(), EditError> {
1550    for (para, expected) in expected_texts(tx, exact)? {
1551        if !attached(tx, para) {
1552            // Merged-away or deleted paragraphs carry no text postcondition;
1553            // merge survivors are checked on their own entry.
1554            continue;
1555        }
1556        let realized = match expected.scope {
1557            ExpectedScope::Paragraph => {
1558                project_paragraph(&tx.opened.dom, tx.paragraph_nodes[para]).text
1559            }
1560            ExpectedScope::Control(control) => control_text(&tx.opened.dom, tx.controls[control]),
1561        };
1562        let (want, got) = if expected.ignore_symbols {
1563            (
1564                expected.text.replace('\u{FFFC}', ""),
1565                realized.replace('\u{FFFC}', ""),
1566            )
1567        } else {
1568            (expected.text.clone(), realized)
1569        };
1570        if want != got {
1571            let mut e = err(
1572                codes::POSTCONDITION_FAILED,
1573                Some(&expected.op),
1574                format!(
1575                    "the requested text was not realized in paragraph {}",
1576                    crate::ids::paragraph_id(
1577                        &tx.stories[tx.paragraph_story[para].0].id,
1578                        tx.paragraph_story[para].1,
1579                    ),
1580                ),
1581            );
1582            e.outcomes = tx.outcomes.clone();
1583            return Err(e);
1584        }
1585    }
1586    Ok(())
1587}
1588
1589/// The projected text of a content control (`w:sdtContent` content).
1590fn control_text(dom: &crate::xmllinq::Dom, sdt: crate::xmllinq::NodeId) -> String {
1591    dom.element(sdt, &crate::namespaces::W::sdt_content())
1592        .map(|content| project_paragraph(dom, content).text)
1593        .unwrap_or_default()
1594}
1595
1596/// The serialized paragraphs of every story the plan wrote read exactly
1597/// as the DOM they were written from — the body always, plus each header,
1598/// footer and notes story an operation touched: a character the writer
1599/// dropped or restated is `POSTCONDITION_FAILED`.
1600pub(super) fn check_serialized_stories(
1601    tx: &Transaction<'_>,
1602    clean: &[u8],
1603) -> Result<(), EditError> {
1604    let post = body_paragraph_nodes(&tx.opened.dom, tx.opened.body);
1605    let reopened = crate::inspect::paragraphs(clean)
1606        .map_err(|e| err("POSTCONDITION_FAILED", None, e.to_string()))?;
1607    if reopened.len() != post.len() {
1608        return Err(err(
1609            codes::POSTCONDITION_FAILED,
1610            None,
1611            format!(
1612                "the serialized candidate holds {} body paragraphs, the prepared document {}",
1613                reopened.len(),
1614                post.len(),
1615            ),
1616        ));
1617    }
1618    for (node, paragraph) in post.iter().zip(&reopened) {
1619        let expected = project_paragraph(&tx.opened.dom, *node).text;
1620        if expected != paragraph.text {
1621            return Err(err(
1622                codes::POSTCONDITION_FAILED,
1623                None,
1624                format!(
1625                    "the serialized candidate's paragraph {} reads differently than prepared",
1626                    paragraph.id,
1627                ),
1628            ));
1629        }
1630    }
1631    let written: Vec<usize> = tx
1632        .written_stories
1633        .iter()
1634        .copied()
1635        .filter(|&story| story != 0)
1636        .collect();
1637    if written.is_empty() {
1638        return Ok(());
1639    }
1640    let reopened = crate::inspect::stories(clean)
1641        .map_err(|e| err("POSTCONDITION_FAILED", None, e.to_string()))?;
1642    for story in written {
1643        let StoryPart { part, root, .. } = &tx.stories[story];
1644        let post = crate::inspect::story_paragraph_nodes(&tx.opened.dom, *root);
1645        let Some(reopened) = reopened.iter().find(|s| &s.part == part) else {
1646            return Err(err(
1647                codes::POSTCONDITION_FAILED,
1648                None,
1649                format!("the serialized candidate lost the {part} story"),
1650            ));
1651        };
1652        if reopened.paragraphs.len() != post.len() {
1653            return Err(err(
1654                codes::POSTCONDITION_FAILED,
1655                None,
1656                format!(
1657                    "the serialized candidate holds {} {part} paragraphs, the prepared document {}",
1658                    reopened.paragraphs.len(),
1659                    post.len(),
1660                ),
1661            ));
1662        }
1663        for (node, paragraph) in post.iter().zip(&reopened.paragraphs) {
1664            let expected = project_paragraph(&tx.opened.dom, *node).text;
1665            if expected != paragraph.text {
1666                return Err(err(
1667                    codes::POSTCONDITION_FAILED,
1668                    None,
1669                    format!(
1670                        "the serialized candidate's paragraph {} reads differently than prepared",
1671                        paragraph.id,
1672                    ),
1673                ));
1674            }
1675        }
1676    }
1677    Ok(())
1678}
1679
1680/// Compare the published redline's accepted text with the final clean copy.
1681fn check_redline_stories(
1682    tx: &Transaction<'_>,
1683    clean: &[u8],
1684    redline: &[u8],
1685) -> Result<(), EditError> {
1686    fn compare(
1687        part: &str,
1688        clean: &[crate::inspect::Paragraph],
1689        redline: &[crate::inspect::Paragraph],
1690    ) -> Result<(), EditError> {
1691        if clean.len() != redline.len() {
1692            return Err(err(
1693                codes::POSTCONDITION_FAILED,
1694                None,
1695                format!(
1696                    "the accepted redline's {part} paragraph {} differs: {} paragraphs, the clean candidate {}",
1697                    clean.len().min(redline.len()),
1698                    redline.len(),
1699                    clean.len(),
1700                ),
1701            ));
1702        }
1703        for (expected, actual) in clean.iter().zip(redline) {
1704            if expected.text != actual.text {
1705                return Err(err(
1706                    codes::POSTCONDITION_FAILED,
1707                    None,
1708                    format!(
1709                        "the accepted redline's {part} paragraph {} reads differently than the clean candidate",
1710                        expected.id,
1711                    ),
1712                ));
1713            }
1714        }
1715        Ok(())
1716    }
1717
1718    // Under keep, even the clean copy retains the source's revisions.
1719    // Settle both copies for comparison without changing the published bytes.
1720    let accept = |bytes: &[u8]| {
1721        crate::document_comparer::accept_revisions(bytes)
1722            .map_err(|e| err(codes::POSTCONDITION_FAILED, None, e.to_string()))
1723    };
1724    let clean = accept(clean)?;
1725    let redline = accept(redline)?;
1726    let paragraphs = |bytes: &[u8]| {
1727        crate::inspect::paragraphs(bytes)
1728            .map_err(|e| err(codes::POSTCONDITION_FAILED, None, e.to_string()))
1729    };
1730    compare(
1731        &tx.opened.main,
1732        &paragraphs(&clean)?,
1733        &paragraphs(&redline)?,
1734    )?;
1735    if tx.written_stories.iter().all(|&story| story == 0) {
1736        return Ok(());
1737    }
1738    let stories = |bytes: &[u8]| {
1739        crate::inspect::stories(bytes)
1740            .map_err(|e| err(codes::POSTCONDITION_FAILED, None, e.to_string()))
1741    };
1742    let clean = stories(&clean)?;
1743    let redline = stories(&redline)?;
1744    for &story in &tx.written_stories {
1745        if story == 0 {
1746            continue;
1747        }
1748        let part = &tx.stories[story].part;
1749        let expected = clean.iter().find(|s| &s.part == part);
1750        let actual = redline.iter().find(|s| &s.part == part);
1751        let (Some(expected), Some(actual)) = (expected, actual) else {
1752            return Err(err(
1753                codes::POSTCONDITION_FAILED,
1754                None,
1755                format!("the accepted candidates lost the {part} story at paragraph 0"),
1756            ));
1757        };
1758        compare(part, &expected.paragraphs, &actual.paragraphs)?;
1759    }
1760    Ok(())
1761}
1762
1763/// Serialize and check the prepared DOM before field updates, then check
1764/// the published redline against the final clean candidate.
1765fn produce(
1766    tx: &mut Transaction<'_>,
1767    emit: bool,
1768    role: PrimaryRole,
1769) -> Result<EditResult, EditError> {
1770    let plan = tx.plan;
1771    let (clean, marked) = tx.finish()?;
1772    check_serialized_stories(tx, &clean)?;
1773    // A reworded or deleted comment makes the comparer's base a copy; the
1774    // emitter writes those threads itself, as under keep.
1775    if plan.existing_revisions == ExistingRevisions::Keep
1776        || (emit
1777            && (tx.edits_only_comments()
1778                || matches!(tx.commented_base()?, std::borrow::Cow::Borrowed(_))))
1779    {
1780        let result = tracked::result(tx, clean)?;
1781        tx.check_redactions(&[&result.clean, &result.redline])?;
1782        if role == PrimaryRole::Redline {
1783            check_redline_stories(tx, &result.clean, &result.redline)?;
1784        }
1785        return Ok(result);
1786    }
1787    // Only the field refresh below rewrites the candidates.
1788    #[cfg(feature = "render")]
1789    let (mut clean, mut marked) = (clean, marked);
1790    #[cfg(feature = "render")]
1791    let mut fields = Vec::new();
1792    #[cfg(feature = "render")]
1793    if plan.update_fields {
1794        let refresh = |bytes: &[u8]| {
1795            crate::fields::update_fields(bytes)
1796                .map_err(|e| err("FIELDS_FAILED", None, e.to_string()))
1797        };
1798        let updated = refresh(&clean)?;
1799        clean = updated.docx;
1800        fields = updated.fields;
1801        if let Some(bytes) = &marked {
1802            marked = Some(refresh(bytes)?.docx);
1803        }
1804    }
1805    // Accept All gives back `clean`: the comparer leaves what the plan did
1806    // not touch as the source has it (#1868).
1807    let settings = WmlComparerSettings {
1808        author_for_revisions: plan.author.clone(),
1809        date_time_for_revisions: tx.date.clone(),
1810        preserve_untouched: true,
1811        ..WmlComparerSettings::default()
1812    };
1813    let revised = marked.as_deref().unwrap_or(&clean);
1814    let base = tx.commented_base()?;
1815    let mut redline =
1816        crate::document_comparer::compare_documents_for_edit(&base, revised, &settings)
1817            .map_err(|e| err("COMPARE_FAILED", None, e.to_string()))?;
1818    if tx
1819        .resolved
1820        .iter()
1821        .any(|(_, r)| matches!(r, Resolved::PageSetup { .. }))
1822    {
1823        redline = sections::record_mid_changes(&redline, &base, &plan.author, &tx.date)?;
1824    }
1825    redline = super::ranges::restore(&redline, &base, revised, &plan.author)?;
1826    if marked.is_some() {
1827        let (rewritten, fallbacks) = whole::rewrite(
1828            &redline,
1829            (&base, revised),
1830            &tx.whole_marks,
1831            &plan.author,
1832            &tx.date,
1833        )?;
1834        redline = rewritten;
1835        for (op, reason) in fallbacks {
1836            tx.outcomes[op].message = Some(format!("shown as a word-level diff: {reason}"));
1837        }
1838    }
1839    if let Some(&(_, op)) = tx
1840        .deletion_comments
1841        .iter()
1842        .find(|&&(id, _)| comment_holds_kept_text(&redline, id))
1843    {
1844        // Under keep the deletion is written as given, and its comment
1845        // wraps the words named, its reply the struck paragraph.
1846        let keep = match tx.syntax {
1847            super::PlanSyntax::Flags | super::PlanSyntax::Typed => "--existing-revisions keep",
1848            super::PlanSyntax::V1 | super::PlanSyntax::V2 => r#""existing_revisions": "keep""#,
1849        };
1850        let message = match plan.operations[op].kind {
1851            OperationKind::Delete { .. } => format!(
1852                "the comparer deleted the same words elsewhere instead, so the comment would sit on text that stays; pass {keep} to write the deletion as given, or delete without a comment"
1853            ),
1854            OperationKind::ReplyComment { .. } => format!(
1855                "the comparer deleted an identical paragraph instead, so the reply would sit on text that stays; pass {keep} to write the deletion as given"
1856            ),
1857            _ => "the comparer deleted an identical paragraph instead, so the comment would sit on text that stays; delete without a comment, or comment on a neighbouring paragraph".to_string(),
1858        };
1859        let mut error = tx.conflict(op, &message);
1860        error.code = "UNSUPPORTED_STRUCTURE".into();
1861        error.outcomes[op].code = Some(error.code.clone());
1862        return Err(error);
1863    }
1864    // After the reply check: a deletion with no new comment can still land
1865    // on a later copy of the same paragraph. Refuse that before publishing.
1866    if let Some((op, message)) = identical_paragraph_kept(tx, &redline)? {
1867        let mut error = tx.conflict(op, &message);
1868        error.code = "UNSUPPORTED_STRUCTURE".into();
1869        error.outcomes[op].code = Some(error.code.clone());
1870        return Err(error);
1871    }
1872    // A deleted text's comment wraps its deletion, as a strike's does.
1873    let lifted: Vec<u32> = tx
1874        .deletion_comments
1875        .iter()
1876        .filter(|&&(_, op)| matches!(plan.operations[op].kind, OperationKind::Delete { .. }))
1877        .map(|&(id, _)| id)
1878        .collect();
1879    redline = lift_deletion_comments(&redline, &lifted)?;
1880    redline = enclose_deleted_paragraph_comment_references(&redline, &plan.author)?;
1881    // Settings are not revisions: the redline takes them as they are.
1882    if let Some(request) = &tx.settings {
1883        redline = crate::settings::apply_settings_to_docx(&redline, request)
1884            .map_err(|m| err("PACKAGE_WRITE", None, m))?;
1885    }
1886    redline = super::replacement_order::typing_order(&redline)?;
1887    tx.check_redactions(&[&clean, &redline])?;
1888    let mut report = tx.report(true);
1889    report.paragraphs.to = crate::inspect::paragraphs(&clean)
1890        .map(|p| p.len())
1891        .unwrap_or(report.paragraphs.from);
1892    report.revisions = revision_counts(&redline);
1893    #[cfg(feature = "render")]
1894    {
1895        report.fields = fields;
1896    }
1897    report.clean_removed_comments = crate::comment_settlement::threads_the_clean_copy_drops(
1898        &clean,
1899        &redline,
1900        &report.removed_comments,
1901        &tx.deleted_paragraph_ids(),
1902    )?;
1903    if role == PrimaryRole::Redline {
1904        check_redline_stories(tx, &clean, &redline)?;
1905    }
1906    Ok(EditResult {
1907        clean,
1908        redline,
1909        report,
1910    })
1911}
1912
1913/// A whole-paragraph deletion whose named paragraph still shows the same
1914/// non-empty text. The comparer struck another copy. An empty paragraph
1915/// is skipped: nothing distinguishes it from its twin.
1916fn identical_paragraph_kept(
1917    tx: &Transaction<'_>,
1918    redline: &[u8],
1919) -> Result<Option<(usize, String)>, EditError> {
1920    let deletions: Vec<(usize, usize)> = tx
1921        .resolved
1922        .iter()
1923        .filter_map(|(op, resolved)| match resolved {
1924            Resolved::DeleteParagraph { para } => Some((*op, *para)),
1925            _ => None,
1926        })
1927        .collect();
1928    if deletions.is_empty() {
1929        return Ok(None);
1930    }
1931    let opened = crate::inspect::Opened::open(redline)
1932        .map_err(|error| err("PACKAGE_WRITE", None, error.to_string()))?;
1933    let mut texts: HashMap<usize, Vec<String>> = HashMap::new();
1934    for (op, para) in deletions {
1935        let source = match tx.projections.get(para) {
1936            Some(projection) if !projection.text.is_empty() => projection.text.as_str(),
1937            _ => continue,
1938        };
1939        let Some(&(story, local)) = tx.paragraph_story.get(para) else {
1940            continue;
1941        };
1942        if let std::collections::hash_map::Entry::Vacant(slot) = texts.entry(story) {
1943            slot.insert(visible_paragraphs(&opened, tx, story)?);
1944        }
1945        let still_there = texts
1946            .get(&story)
1947            .and_then(|paragraphs| paragraphs.get(local))
1948            .is_some_and(|text| text == source);
1949        if !still_there {
1950            continue;
1951        }
1952        let keep = match tx.syntax {
1953            super::PlanSyntax::Flags | super::PlanSyntax::Typed => "--existing-revisions keep",
1954            super::PlanSyntax::V1 | super::PlanSyntax::V2 => r#""existing_revisions": "keep""#,
1955        };
1956        return Ok(Some((
1957            op,
1958            format!(
1959                "the comparer deleted an identical paragraph instead of the one named; pass {keep} to write the deletion as given"
1960            ),
1961        )));
1962    }
1963    Ok(None)
1964}
1965
1966/// Visible text of each paragraph in `story`, in the order a plan addresses.
1967fn visible_paragraphs(
1968    opened: &crate::inspect::Opened,
1969    tx: &Transaction<'_>,
1970    story: usize,
1971) -> Result<Vec<String>, EditError> {
1972    if story == 0 {
1973        return Ok(body_paragraph_nodes(&opened.dom, opened.body)
1974            .into_iter()
1975            .map(|paragraph| project_paragraph(&opened.dom, paragraph).text)
1976            .collect());
1977    }
1978    let Some(part) = tx.stories.get(story).map(|story| story.part.clone()) else {
1979        return Ok(Vec::new());
1980    };
1981    if opened.pkg.part_bytes(&part).is_none() {
1982        return Ok(Vec::new());
1983    }
1984    let (dom, _, root) = crate::inspect::parse_part(&opened.pkg, &part)
1985        .map_err(|error| err("PACKAGE_WRITE", None, error.to_string()))?;
1986    Ok(crate::inspect::story_paragraph_nodes(&dom, root)
1987        .into_iter()
1988        .map(|paragraph| project_paragraph(&dom, paragraph).text)
1989        .collect())
1990}
1991
1992/// An [`EditError`] as `super::err` builds it.
1993fn err(code: &str, operation: Option<&str>, message: impl Into<String>) -> EditError {
1994    super::err(code, operation, message)
1995}
1996
1997/// Prepare a PlanV2 through the existing source/working-baseline adapter and
1998/// the same serialized candidate checks as v1. Both inline and saved v2
1999/// requests use this entry point; tracking never selects a different primary.
2000///
2001/// # Errors
2002/// Returns the adapter's source, scope, baseline and effect errors, candidate
2003/// validation failures, or `NO_CHANGES_REQUESTED` when required.
2004pub fn prepare_v2(
2005    source: &[u8],
2006    plan: &super::v2::PlanV2,
2007    options: &PrepareOptions,
2008) -> Result<PreparedEdit, EditError> {
2009    let known = SourceChecks::default();
2010    prepare_v2_once(source, plan, options, &known).map_err(|failure| {
2011        // A v2 plan's operations apply in order, each on what the ones
2012        // before it left: only prefixes are plans of their own, so only
2013        // the operation that brings the refusal in is named.
2014        let mut reruns = Reruns::new(|ops: &[usize]| {
2015            let part = super::v2::PlanV2 {
2016                operations: ops.iter().map(|&i| plan.operations[i].clone()).collect(),
2017                ..plan.clone()
2018            };
2019            prepare_v2_once(source, &part, options, &known)
2020                .err()
2021                .and_then(|f| f.refusal)
2022                .map(|(refusals, _)| refusals)
2023        })
2024        .knowing(plan.operations.len(), &failure);
2025        attributed(*failure, plan.operations.len(), false, &mut reruns)
2026    })
2027}
2028
2029/// [`prepare_v2`] without attribution, as [`prepare_once`] is to
2030/// [`prepare`].
2031fn prepare_v2_once(
2032    source: &[u8],
2033    plan: &super::v2::PlanV2,
2034    options: &PrepareOptions,
2035    known: &SourceChecks,
2036) -> Result<PreparedEdit, Box<Failure>> {
2037    // A v2 plan's refusals quote its JSON, unless a typed command built it.
2038    let syntax = if options.syntax == super::PlanSyntax::Typed {
2039        super::PlanSyntax::Typed
2040    } else {
2041        super::PlanSyntax::V2
2042    };
2043    let applied = super::v2_apply::apply_quoting(source, plan, syntax)?;
2044    let result = EditResult {
2045        clean: applied.clean,
2046        redline: applied.redline,
2047        report: applied.report,
2048    };
2049    let primary = result.redline.clone();
2050    let unchanged = primary == source;
2051    let effect = if unchanged {
2052        Effect::Unchanged
2053    } else {
2054        Effect::Changed
2055    };
2056    let mut checks = screen_candidates(source, &result, known).map_err(|refusals| {
2057        Box::new(Failure {
2058            error: refusals[0].error.clone(),
2059            // A v2 operation is named by its pointer, `/operations/N`.
2060            refusal: Some((refusals, Vec::new())),
2061            advice: None,
2062        })
2063    })?;
2064    checks.operation_postconditions = true;
2065    if options.require_change && unchanged {
2066        return Err(err(
2067            codes::NO_CHANGES_REQUESTED,
2068            None,
2069            "the primary transaction has no document effect; --require-change was given",
2070        )
2071        .into());
2072    }
2073    Ok(PreparedEdit {
2074        source_sha256: source_sha256(source),
2075        request_sha256: source_sha256(
2076            serde_json::to_string(plan)
2077                .expect("plan serializes")
2078                .as_bytes(),
2079        ),
2080        primary_sha256: source_sha256(&primary),
2081        primary,
2082        primary_bytes: if unchanged {
2083            PrimaryBytes::Source
2084        } else {
2085            PrimaryBytes::Candidate
2086        },
2087        primary_effect: effect,
2088        result,
2089        checks,
2090        correspondence: Some(applied.correspondence),
2091        skipped: Vec::new(),
2092    })
2093}
2094
2095#[cfg(test)]
2096#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2097pub(crate) mod tests {
2098    use super::super::{
2099        EditReport, EditResult, ExistingRevisions, ParagraphDelta, deeper_boundary_fixture,
2100    };
2101    use super::*;
2102
2103    fn result_of(clean: Vec<u8>) -> EditResult {
2104        EditResult {
2105            clean: clean.clone(),
2106            redline: clean,
2107            report: EditReport {
2108                schema_version: 1,
2109                ok: true,
2110                source_sha256: String::new(),
2111                base_sha256: String::new(),
2112                guarded: false,
2113                author: "T".into(),
2114                date: "2026-10-17T12:00:00Z".into(),
2115                existing_revisions: ExistingRevisions::Refuse,
2116                resolved_revisions: Default::default(),
2117                removed_comments: Vec::new(),
2118                clean_removed_comments: Vec::new(),
2119                kept_comments: Vec::new(),
2120                paragraph_ids: Vec::new(),
2121                split_revisions: Vec::new(),
2122                paragraphs: ParagraphDelta::default(),
2123                operations: Vec::new(),
2124                comments_added: 0,
2125                revisions: Default::default(),
2126                #[cfg(feature = "render")]
2127                fields: Vec::new(),
2128                skipped: 0,
2129                notes: Vec::new(),
2130                output_sha256: None,
2131            },
2132        }
2133    }
2134
2135    /// A source the full validator cannot read must not become an empty
2136    /// baseline that calls every candidate finding introduced: with no
2137    /// trustworthy baseline nothing is claimed introduced, while the
2138    /// candidate's own validation still runs (fail-safe disclosure, not
2139    /// a fabricated verdict).
2140    #[test]
2141    fn unvalidatable_source_never_claims_findings_introduced() {
2142        let orphan = deeper_boundary_fixture::docx(
2143            r#"<w:p><w:r><w:t>x</w:t></w:r><w:r><w:commentReference w:id="0"/></w:r></w:p>"#,
2144        );
2145        let findings = crate::validate::validate(&orphan).unwrap();
2146        assert!(
2147            findings.iter().any(|f| f.code == "COMMENT_ANCHOR_ORPHAN"),
2148            "{findings:?}"
2149        );
2150        let checks = check_candidates(b"not a zip at all", &result_of(orphan)).unwrap();
2151        assert!(checks.introduced.is_empty(), "{:?}", checks.introduced);
2152        assert!(checks.baseline.is_empty());
2153    }
2154
2155    /// A paragraph of revisions: each `(kind, id)` around one word.
2156    fn revisions(records: &[(&str, u32)]) -> Vec<u8> {
2157        let body: String = records
2158            .iter()
2159            .map(|&(kind, id)| match kind {
2160                "customXmlInsRangeStart" => format!(
2161                    r#"<w:customXmlInsRangeStart w:id="{id}" w:author="A" w:date="2026-10-17T09:00:00Z"/><w:r><w:t>w</w:t></w:r><w:customXmlInsRangeEnd w:id="{id}"/>"#
2162                ),
2163                "rPrChange" => format!(
2164                    r#"<w:r><w:rPr><w:b/><w:rPrChange w:id="{id}" w:author="A" w:date="2026-10-17T09:00:00Z"><w:rPr/></w:rPrChange></w:rPr><w:t>w</w:t></w:r>"#
2165                ),
2166                _ => format!(
2167                    r#"<w:{kind} w:id="{id}" w:author="A" w:date="2026-10-17T09:00:00Z"><w:r><w:{t}>w</w:{t}></w:r></w:{kind}>"#,
2168                    t = if kind == "del" { "delText" } else { "t" }
2169                ),
2170            })
2171            .collect();
2172        deeper_boundary_fixture::docx(&format!("<w:p>{body}</w:p>"))
2173    }
2174
2175    fn gate(
2176        source: &[(&str, u32)],
2177        candidate: &[(&str, u32)],
2178    ) -> Result<CandidateChecks, EditError> {
2179        check_candidates(&revisions(source), &result_of(revisions(candidate)))
2180    }
2181
2182    /// `result` refuses `record` (`w:ins w:id 5`), repeated in `part` of
2183    /// the clean copy.
2184    fn refused_as_duplicate(result: Result<CandidateChecks, EditError>, record: &str, part: &str) {
2185        let error = result.unwrap_err();
2186        assert_eq!(error.code, "CANDIDATE_INVALID", "{error:?}");
2187        assert!(
2188            error
2189                .message
2190                .contains("introduces a duplicate revision id in the clean copy: ")
2191                && error.message.contains(&format!(": {record} occurs "))
2192                && error.message.contains(&format!(" times in {part} (")),
2193            "{error:?}"
2194        );
2195    }
2196
2197    #[test]
2198    fn a_candidate_may_not_introduce_a_duplicate_revision_id() {
2199        refused_as_duplicate(
2200            gate(&[("ins", 5), ("ins", 6)], &[("ins", 5), ("ins", 5)]),
2201            "w:ins w:id 5",
2202            "word/document.xml",
2203        );
2204        refused_as_duplicate(
2205            gate(&[("rPrChange", 5)], &[("rPrChange", 5), ("rPrChange", 5)]),
2206            "w:rPrChange w:id 5",
2207            "word/document.xml",
2208        );
2209    }
2210
2211    #[test]
2212    fn a_candidate_may_not_add_an_occurrence_to_an_inherited_duplicate() {
2213        refused_as_duplicate(
2214            gate(
2215                &[("ins", 5), ("ins", 5)],
2216                &[("ins", 5), ("ins", 5), ("ins", 5)],
2217            ),
2218            "w:ins w:id 5",
2219            "word/document.xml",
2220        );
2221    }
2222
2223    #[test]
2224    fn healing_one_duplicate_revision_id_hides_no_new_one() {
2225        refused_as_duplicate(
2226            gate(
2227                &[("ins", 5), ("ins", 5)],
2228                &[("ins", 5), ("ins", 7), ("ins", 7)],
2229            ),
2230            "w:ins w:id 7",
2231            "word/document.xml",
2232        );
2233    }
2234
2235    #[test]
2236    fn a_custom_xml_range_start_may_not_take_a_duplicate_id() {
2237        // A range start and its end share an id; two starts may not.
2238        assert!(
2239            gate(
2240                &[("customXmlInsRangeStart", 5)],
2241                &[("customXmlInsRangeStart", 5)]
2242            )
2243            .is_ok()
2244        );
2245        // Their ends repeat too, and come first by name (#1666).
2246        refused_as_duplicate(
2247            gate(
2248                &[("customXmlInsRangeStart", 5), ("customXmlInsRangeStart", 6)],
2249                &[("customXmlInsRangeStart", 5), ("customXmlInsRangeStart", 5)],
2250            ),
2251            "w:customXmlInsRangeEnd w:id 5",
2252            "word/document.xml",
2253        );
2254    }
2255
2256    /// `bytes` with its main part's WordprocessingML namespace made Strict's.
2257    fn strict(bytes: &[u8]) -> Vec<u8> {
2258        let mut pkg = crate::opc::PartFs::open(bytes).unwrap();
2259        let xml = pkg.part_string("word/document.xml").unwrap().replace(
2260            "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
2261            "http://purl.oclc.org/ooxml/wordprocessingml/main",
2262        );
2263        pkg.set_part("word/document.xml", xml.into_bytes());
2264        pkg.to_zip().unwrap()
2265    }
2266
2267    #[test]
2268    fn a_strict_sources_duplicates_are_inherited() {
2269        // The edit writes a Strict source's revisions in Transitional.
2270        let source = strict(&revisions(&[("ins", 5), ("ins", 5)]));
2271        let candidate = revisions(&[("ins", 5), ("ins", 5)]);
2272        let result = check_candidates(&source, &result_of(candidate));
2273        assert!(result.is_ok(), "{result:?}");
2274    }
2275
2276    /// `bytes` with its main part at `name`, wherever its relationship
2277    /// and content type point.
2278    fn main_named(bytes: &[u8], name: &str) -> Vec<u8> {
2279        const OFFICE_DOCUMENT: &str =
2280            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
2281        let mut pkg = crate::opc::PartFs::open(bytes).unwrap();
2282        let xml = pkg.part_bytes("word/document.xml").unwrap().to_vec();
2283        pkg.remove_part("word/document.xml");
2284        pkg.set_part(name, xml);
2285        pkg.add_content_type_override(
2286            &format!("/{name}"),
2287            "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
2288        );
2289        pkg.remove_package_relationships_by_type(OFFICE_DOCUMENT);
2290        pkg.add_package_relationship(OFFICE_DOCUMENT, name);
2291        pkg.to_zip().unwrap()
2292    }
2293
2294    #[test]
2295    fn a_main_part_without_an_xml_extension_is_gated_too() {
2296        let source = main_named(&revisions(&[("ins", 5), ("ins", 6)]), "word/main.dat");
2297        let candidate = main_named(&revisions(&[("ins", 5), ("ins", 5)]), "word/main.dat");
2298        refused_as_duplicate(
2299            check_candidates(&source, &result_of(candidate)),
2300            "w:ins w:id 5",
2301            "word/main.dat",
2302        );
2303    }
2304
2305    #[test]
2306    fn a_strict_main_part_without_an_xml_extension_is_read_as_transitional() {
2307        // #1666: its inherited duplicates stay inherited.
2308        let source = main_named(
2309            &strict(&revisions(&[("ins", 5), ("ins", 5)])),
2310            "word/main.dat",
2311        );
2312        let candidate = main_named(&revisions(&[("ins", 5), ("ins", 5)]), "word/main.dat");
2313        let result = check_candidates(&source, &result_of(candidate));
2314        assert!(result.is_ok(), "{result:?}");
2315    }
2316
2317    fn prepared(source: &[u8], operation: &str) -> Result<PreparedEdit, EditError> {
2318        let json = format!(
2319            r#"{{"schema_version":1,"author":"Bob","date":"2026-10-17T12:00:00Z","existing_revisions":"keep","operations":[{operation}]}}"#
2320        );
2321        let plan = EditPlan::from_json(&json).unwrap();
2322        prepare(source, &plan, &PrepareOptions::default())
2323    }
2324
2325    #[test]
2326    fn a_paragraph_marks_revision_id_survives_paragraph_edits() {
2327        // `w:pPr/w:rPr/w:ins`: a new paragraph made like it, one split off
2328        // it, and a replacement inside it publish.
2329        let source = deeper_boundary_fixture::docx(
2330            r#"<w:p><w:pPr><w:rPr><w:ins w:id="7" w:author="Ann" w:date="2026-09-01T00:00:00Z"/></w:rPr></w:pPr><w:r><w:t xml:space="preserve">abcd efgh</w:t></w:r></w:p><w:p><w:r><w:t>next</w:t></w:r></w:p>"#,
2331        );
2332        for operation in [
2333            r#"{"kind":"insert_paragraph","paragraph":{"index":1},"runs":[{"text":"b"}],"like":{"index":0}}"#,
2334            r#"{"kind":"insert","paragraph":"p0","after":"abcd","text":"\nnew para"}"#,
2335            r#"{"kind":"replace","paragraph":"p0","find":"cd","replacement":"X"}"#,
2336        ] {
2337            let result = prepared(&source, operation);
2338            assert!(result.is_ok(), "{operation}: {:?}", result.err());
2339        }
2340    }
2341
2342    /// `culprits` against a refusal that comes back whenever the
2343    /// operations it is given include every set of one of `causes`,
2344    /// counting the reruns.
2345    fn culprits_of(
2346        count: usize,
2347        together: bool,
2348        causes: &[&[usize]],
2349    ) -> (Option<Vec<usize>>, usize) {
2350        let mut reruns = 0;
2351        let found = culprits(count, together, |ops| {
2352            reruns += 1;
2353            causes
2354                .iter()
2355                .any(|cause| cause.iter().all(|i| ops.contains(i)))
2356        });
2357        (found, reruns)
2358    }
2359
2360    #[test]
2361    fn culprits_finds_one_operation_in_logarithmic_reruns() {
2362        for at in 0..64 {
2363            let (found, reruns) = culprits_of(64, true, &[&[at]]);
2364            assert_eq!(found, Some(vec![at]));
2365            // The empty plan, six halvings, and the operation alone.
2366            assert!(reruns <= 8, "{at}: {reruns}");
2367        }
2368        assert_eq!(culprits_of(1, true, &[&[0]]).0, Some(vec![0]));
2369    }
2370
2371    #[test]
2372    fn culprits_names_the_operations_a_refusal_needs() {
2373        // The later one brings it in; the earlier ones it needs follow in
2374        // plan order.
2375        assert_eq!(culprits_of(10, true, &[&[2, 7]]).0, Some(vec![7, 2]));
2376        assert_eq!(culprits_of(10, true, &[&[5, 1, 8]]).0, Some(vec![8, 1, 5]));
2377        assert_eq!(culprits_of(2, true, &[&[0, 1]]).0, Some(vec![1, 0]));
2378        // Independent causes: the first one complete in plan order is
2379        // named, alone.
2380        assert_eq!(culprits_of(10, true, &[&[6], &[3]]).0, Some(vec![3]));
2381        // Without `together` (v2), only the operation that brings it in.
2382        assert_eq!(culprits_of(10, false, &[&[2, 7]]).0, Some(vec![7]));
2383    }
2384
2385    #[test]
2386    fn culprits_seeks_each_further_operation_before_the_last_found() {
2387        // The operations before the last one found, with those found,
2388        // reproduce the refusal: the next search covers only them.
2389        let (found, reruns) = culprits_of(64, true, &[&[0, 1, 2, 3, 63]]);
2390        assert_eq!(found, Some(vec![63, 0, 1, 2, 3]));
2391        assert!(reruns <= 21, "{reruns}");
2392        let (found, reruns) = culprits_of(64, true, &[&[1, 3, 63]]);
2393        assert_eq!(found, Some(vec![63, 1, 3]));
2394        assert!(reruns <= 18, "{reruns}");
2395    }
2396
2397    #[test]
2398    fn a_refusal_without_operations_names_none() {
2399        // The plan without operations meets it: settling, not an
2400        // operation, causes it.
2401        assert_eq!(culprits_of(5, true, &[&[]]).0, None);
2402        assert_eq!(culprits_of(0, true, &[]).0, None);
2403    }
2404
2405    /// A failure the candidate checks did not raise keeps its error as it
2406    /// is, without a rerun; a refusal no operation causes stays the plan's.
2407    #[test]
2408    fn attribution_leaves_other_failures_alone() {
2409        let error = err("OVERLAPPING_EDITS", Some("op-2"), "two edits");
2410        let mut never = Reruns::new(|_: &[usize]| -> Option<Refused> {
2411            panic!("no rerun for a failure the candidate checks did not raise")
2412        });
2413        let kept = attributed(*Box::<Failure>::from(error.clone()), 3, true, &mut never);
2414        assert_eq!(kept, error);
2415        let refusal = refused(
2416            "redline",
2417            "BOOKMARK_CROSSES_REVISION",
2418            "word/document.xml",
2419            "Clause".into(),
2420            "the edit introduces it".into(),
2421        );
2422        let failure = Box::new(Failure {
2423            error: refusal.error.clone(),
2424            refusal: Some((vec![refusal.clone()], Vec::new())),
2425            advice: Some("drop update_fields"),
2426        });
2427        let mut always = Reruns::new(|_: &[usize]| Some(vec![refusal.clone()]));
2428        let kept = attributed(*failure, 3, true, &mut always);
2429        assert_eq!(kept.operation, None);
2430        assert_eq!(kept.message, "the edit introduces it; drop update_fields");
2431    }
2432
2433    /// The operations are named before the advice that closes the message.
2434    #[test]
2435    fn named_operations_come_before_the_advice() {
2436        let refusal = refused(
2437            "redline",
2438            "RANGE_LOST",
2439            "",
2440            "bookmark B".into(),
2441            "Reject All drops bookmark B".into(),
2442        );
2443        let outcome = |id: &str, kind: &str, paragraph: Option<&str>| EditOutcome {
2444            id: id.into(),
2445            kind: kind.into(),
2446            status: String::new(),
2447            paragraph: paragraph.map(str::to_string),
2448            matches: 0,
2449            context: None,
2450            comment_id: None,
2451            anchor_given: None,
2452            anchor_read_as: None,
2453            near: None,
2454            candidates: Vec::new(),
2455            code: None,
2456            message: None,
2457        };
2458        let failure = Box::new(Failure {
2459            error: refusal.error.clone(),
2460            refusal: Some((
2461                vec![refusal.clone()],
2462                vec![
2463                    outcome("op-1", "replace", Some("p0")),
2464                    outcome("op-2", "insert", Some("p4")),
2465                    outcome("op-3", "page_setup", None),
2466                ],
2467            )),
2468            advice: Some("drop update_fields"),
2469        });
2470        let mut reruns = Reruns::new(|ops: &[usize]| {
2471            (ops.contains(&0) && ops.contains(&2)).then(|| vec![refusal.clone()])
2472        });
2473        let named = attributed(*failure, 3, true, &mut reruns);
2474        assert_eq!(named.operation.as_deref(), Some("op-3"));
2475        assert_eq!(
2476            named.message,
2477            "Reject All drops bookmark B; op-3 (page_setup) introduces it, together with op-1 (replace on p0); drop update_fields"
2478        );
2479    }
2480
2481    /// A rerun reproduces a defect when it meets that one among others,
2482    /// never another defect of its code and part; each set of operations
2483    /// is prepared once.
2484    #[test]
2485    fn a_rerun_reproduces_the_defect_not_its_code() {
2486        let defect = |subject: &str| {
2487            refused(
2488                "redline",
2489                "DUPLICATE_REVISION_ID",
2490                "word/document.xml",
2491                subject.into(),
2492                format!("{subject} repeats"),
2493            )
2494        };
2495        let mut runs = 0;
2496        let mut reruns = Reruns::new(|ops: &[usize]| {
2497            runs += 1;
2498            let mut met = Vec::new();
2499            if ops.contains(&0) {
2500                met.push(defect("w:ins w:id 9"));
2501            }
2502            if ops.contains(&1) {
2503                met.push(defect("w:ins w:id 7"));
2504            }
2505            (!met.is_empty()).then_some(met)
2506        });
2507        let seven = defect("w:ins w:id 7");
2508        assert!(!reruns.reproduces(&[0], &seven));
2509        assert!(reruns.reproduces(&[1], &seven));
2510        assert!(reruns.reproduces(&[0, 1], &seven));
2511        assert!(!reruns.reproduces(&[0], &seven));
2512        drop(reruns);
2513        assert_eq!(runs, 3);
2514    }
2515
2516    #[test]
2517    fn a_run_marks_revision_id_split_in_two_is_refused() {
2518        // A run's `w:rPr` holds no `w:ins` (OpenXmlValidator:
2519        // `Sch_InvalidElementContentExpectingComplex`). Splitting such a run
2520        // copies the mark's id: the candidate is refused, not published.
2521        let source = deeper_boundary_fixture::docx(
2522            r#"<w:p><w:r><w:rPr><w:ins w:id="7" w:author="Ann" w:date="2026-09-01T00:00:00Z"/></w:rPr><w:t>abcd</w:t></w:r></w:p>"#,
2523        );
2524        let error = prepared(
2525            &source,
2526            r#"{"kind":"replace","paragraph":"p0","find":"bc","replacement":"X"}"#,
2527        )
2528        .err()
2529        .unwrap();
2530        assert_eq!(error.code, "CANDIDATE_INVALID", "{error:?}");
2531        assert!(
2532            error.message.contains("w:ins on a mark w:id 7"),
2533            "{error:?}"
2534        );
2535    }
2536
2537    /// The KI-8 shape: the clean copy resolves the edit's insertion away
2538    /// and only the redline repeats an id. The refusal names the redline.
2539    #[test]
2540    fn a_duplicate_only_the_redline_carries_is_refused_by_its_artifact() {
2541        let source = revisions(&[("ins", 5), ("ins", 6)]);
2542        let mut result = result_of(revisions(&[("ins", 5), ("ins", 6)]));
2543        result.redline = revisions(&[("ins", 5), ("ins", 5)]);
2544        let error = check_candidates(&source, &result).unwrap_err();
2545        assert_eq!(error.code, "CANDIDATE_INVALID", "{error:?}");
2546        assert_eq!(
2547            error.message,
2548            "the edit introduces a duplicate revision id in the redline: w:ins w:id 5 occurs 2 times in word/document.xml (the source has 1)"
2549        );
2550    }
2551
2552    #[test]
2553    fn an_unreadable_source_skips_the_duplicate_gate() {
2554        let candidate = revisions(&[("ins", 5), ("ins", 5)]);
2555        let result = check_candidates(b"not a zip at all", &result_of(candidate));
2556        assert!(result.is_ok(), "{result:?}");
2557    }
2558
2559    #[test]
2560    fn inherited_duplicates_and_ids_shared_across_kinds_publish() {
2561        let inherited = [("ins", 5), ("ins", 5)];
2562        assert!(gate(&inherited, &inherited).is_ok());
2563        assert!(gate(&inherited, &[("ins", 5)]).is_ok());
2564        let shared = [("ins", 5), ("del", 5), ("rPrChange", 5)];
2565        assert!(gate(&[("ins", 5)], &shared).is_ok());
2566    }
2567
2568    #[test]
2569    fn verification_reports_only_completed_candidate_checks() {
2570        let skipped = CandidateChecks::default().verification();
2571        assert_eq!(skipped.integrity, "skipped");
2572        assert_eq!(skipped.operation_postconditions, "skipped");
2573        let source = deeper_boundary_fixture::docx("<w:p><w:r><w:t>old</w:t></w:r></w:p>");
2574        let plan = EditPlan::from_json(
2575            r#"{"schema_version":1,"author":"T","date":"2026-10-17T12:00:00Z","operations":[]}"#,
2576        )
2577        .unwrap();
2578        let checked = prepare(&source, &plan, &PrepareOptions::default())
2579            .unwrap()
2580            .checks
2581            .verification();
2582        assert_eq!(checked.integrity, "passed");
2583        assert_eq!(checked.operation_postconditions, "passed");
2584    }
2585
2586    #[test]
2587    fn redline_only_defects_name_the_story_and_paragraph() {
2588        use deeper_boundary_fixture::{Part, R_NS, W_NS, docx_with_sect, para};
2589
2590        let kinds = ["header", "footer", "footnotes", "endnotes"];
2591        let names = [
2592            "word/header1.xml",
2593            "word/footer1.xml",
2594            "word/footnotes.xml",
2595            "word/endnotes.xml",
2596        ];
2597        let roots = ["hdr", "ftr", "footnotes", "endnotes"];
2598        let xmls: Vec<_> = roots
2599            .iter()
2600            .map(|root| {
2601                let text = para("old");
2602                let content = match *root {
2603                    "footnotes" => format!(r#"<w:footnote w:id="1">{text}</w:footnote>"#),
2604                    "endnotes" => format!(r#"<w:endnote w:id="1">{text}</w:endnote>"#),
2605                    _ => text,
2606                };
2607                format!(r#"<w:{root} xmlns:w="{W_NS}">{content}</w:{root}>"#)
2608            })
2609            .collect();
2610        let rels: Vec<_> = kinds.iter().map(|k| format!("{R_NS}/{k}")).collect();
2611        let types: Vec<_> = kinds
2612            .iter()
2613            .map(|k| {
2614                format!("application/vnd.openxmlformats-officedocument.wordprocessingml.{k}+xml")
2615            })
2616            .collect();
2617        let parts: Vec<_> = (0..kinds.len())
2618            .map(|i| Part {
2619                name: names[i],
2620                content_type: &types[i],
2621                rel_type: &rels[i],
2622                xml: &xmls[i],
2623            })
2624            .collect();
2625        let source = docx_with_sect(
2626            &(para("old")
2627                + r#"<w:p><w:r><w:footnoteReference w:id="1"/><w:endnoteReference w:id="1"/></w:r></w:p>"#),
2628            &parts,
2629            r#"<w:headerReference w:type="default" r:id="rIdX0"/><w:footerReference w:type="default" r:id="rIdX1"/>"#,
2630        );
2631        let mut operations = vec![
2632            serde_json::json!({"kind":"replace", "paragraph":"p0", "find":"old", "replacement":"new"}),
2633        ];
2634        for story in crate::inspect::stories(&source).unwrap() {
2635            operations.push(serde_json::json!({"kind":"replace", "paragraph":story.paragraphs[0].id, "find":"old", "replacement":"new"}));
2636        }
2637        let plan = EditPlan::from_json(&serde_json::json!({
2638            "schema_version":1, "author":"T", "date":"2026-10-17T12:00:00Z", "operations":operations,
2639        }).to_string()).unwrap();
2640        let mut tx = Transaction::start(&source, &plan).unwrap();
2641        tx.resolve().unwrap();
2642        tx.apply().unwrap();
2643        let (clean, _) = tx.finish().unwrap();
2644        assert!(check_redline_stories(&tx, &clean, &clean).is_ok());
2645        let mut failures = Vec::new();
2646        for part in std::iter::once("word/document.xml").chain(names) {
2647            for defect in ["text", "count", "missing"] {
2648                if part == "word/document.xml" && defect == "missing" {
2649                    continue;
2650                }
2651                let mut pkg = crate::opc::PartFs::open(&clean).unwrap();
2652                let xml = pkg.part_string(part).unwrap();
2653                if defect == "missing" {
2654                    pkg.remove_related_part(
2655                        "word/document.xml",
2656                        &format!("rIdX{}", names.iter().position(|p| *p == part).unwrap()),
2657                    );
2658                } else {
2659                    let broken = if defect == "text" {
2660                        xml.replace("new", "WRONG")
2661                    } else {
2662                        xml.replace("</w:p>", "</w:p><w:p/>")
2663                    };
2664                    pkg.set_part(part, broken.into_bytes());
2665                }
2666                let redline = pkg.to_zip().unwrap();
2667                match check_redline_stories(&tx, &clean, &redline) {
2668                    Err(e)
2669                        if e.code == codes::POSTCONDITION_FAILED
2670                            && e.message.contains(part)
2671                            && e.message.contains("paragraph") => {}
2672                    outcome => failures.push(format!("{part} {defect}: {outcome:?}")),
2673                }
2674            }
2675        }
2676        assert!(failures.is_empty(), "{}", failures.join("\n"));
2677    }
2678
2679    thread_local! {
2680        /// How many times [`prepare_once`] ran on this test thread.
2681        pub(crate) static PREPARATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2682    }
2683
2684    /// `--skip-failed` attributes every defect of a refusal in one pass,
2685    /// each rerun once: a plan whose operations are each refused alone
2686    /// takes at most `2n + 1` preparations (the plan, its prefixes, each
2687    /// operation alone), not a bisection per retry (#1689 review).
2688    #[test]
2689    fn skip_failed_attributes_every_defect_of_a_refusal_at_once() {
2690        let n = 16;
2691        let body: String = (0..n)
2692            .map(|i| {
2693                format!(
2694                    r#"<w:p><w:r><w:rPr><w:ins w:id="{}" w:author="Ann" w:date="2026-09-01T00:00:00Z"/></w:rPr><w:t>abcd</w:t></w:r></w:p>"#,
2695                    100 + i
2696                )
2697            })
2698            .collect();
2699        let source = deeper_boundary_fixture::docx(&body);
2700        let operations: Vec<String> = (0..n)
2701            .map(|i| {
2702                format!(r#"{{"kind":"replace","paragraph":"p{i}","find":"bc","replacement":"X"}}"#)
2703            })
2704            .collect();
2705        let plan = EditPlan::from_json(&format!(
2706            r#"{{"schema_version":1,"author":"Bob","date":"2026-10-17T12:00:00Z","existing_revisions":"keep","operations":[{}]}}"#,
2707            operations.join(",")
2708        ))
2709        .unwrap();
2710        PREPARATIONS.with(|count| count.set(0));
2711        let options = PrepareOptions {
2712            skip_failed: true,
2713            ..PrepareOptions::default()
2714        };
2715        let error = prepare(&source, &plan, &options).unwrap_err();
2716        assert_eq!(error.code, "CANDIDATE_INVALID", "{error:?}");
2717        let failed = error
2718            .outcomes
2719            .iter()
2720            .filter(|o| o.status == "failed")
2721            .count();
2722        assert_eq!(failed, n, "{error:?}");
2723        // The plan, then each operation alone.
2724        let preparations = PREPARATIONS.with(std::cell::Cell::get);
2725        assert!(
2726            preparations <= n + 1,
2727            "{preparations} preparations for {n} operations"
2728        );
2729    }
2730
2731    /// One refused operation among many is still found by bisection, in
2732    /// logarithmic reruns, and `--skip-failed` publishes the others.
2733    #[test]
2734    fn skip_failed_bisects_a_lone_defect() {
2735        let n = 16;
2736        let culprit = 11;
2737        let body: String = (0..n)
2738            .map(|i| {
2739                let mark = if i == culprit {
2740                    r#"<w:rPr><w:ins w:id="100" w:author="Ann" w:date="2026-09-01T00:00:00Z"/></w:rPr>"#
2741                } else {
2742                    ""
2743                };
2744                format!(r#"<w:p><w:r>{mark}<w:t>abcd</w:t></w:r></w:p>"#)
2745            })
2746            .collect();
2747        let source = deeper_boundary_fixture::docx(&body);
2748        let operations: Vec<String> = (0..n)
2749            .map(|i| {
2750                format!(r#"{{"kind":"replace","paragraph":"p{i}","find":"bc","replacement":"X"}}"#)
2751            })
2752            .collect();
2753        let plan = EditPlan::from_json(&format!(
2754            r#"{{"schema_version":1,"author":"Bob","date":"2026-10-17T12:00:00Z","existing_revisions":"keep","operations":[{}]}}"#,
2755            operations.join(",")
2756        ))
2757        .unwrap();
2758        PREPARATIONS.with(|count| count.set(0));
2759        let options = PrepareOptions {
2760            skip_failed: true,
2761            ..PrepareOptions::default()
2762        };
2763        let prepared = prepare(&source, &plan, &options).unwrap();
2764        let skipped: Vec<usize> = prepared.skipped.iter().map(|s| s.index).collect();
2765        assert_eq!(skipped, [culprit]);
2766        assert!(
2767            prepared.skipped[0]
2768                .message
2769                .contains("op-12 (replace on p11) introduces it"),
2770            "{:?}",
2771            prepared.skipped
2772        );
2773        // The plan, the plan without operations, four prefixes, the
2774        // culprit alone and the survivors.
2775        let preparations = PREPARATIONS.with(std::cell::Cell::get);
2776        assert!(preparations <= 8, "{preparations} preparations");
2777    }
2778
2779    thread_local! {
2780        static SERIALIZED_CANDIDATE: std::cell::RefCell<Option<Vec<u8>>> = const { std::cell::RefCell::new(None) };
2781    }
2782
2783    // A deterministic serializer fake: only the current test thread sees it.
2784    pub(crate) fn serialized_candidate(bytes: Vec<u8>) -> Vec<u8> {
2785        SERIALIZED_CANDIDATE.with(|candidate| candidate.borrow().clone().unwrap_or(bytes))
2786    }
2787
2788    #[test]
2789    fn review_11_prepare_v2_checks_serialized_text_like_v1() {
2790        struct Reset;
2791        impl Drop for Reset {
2792            fn drop(&mut self) {
2793                SERIALIZED_CANDIDATE.with(|c| *c.borrow_mut() = None);
2794            }
2795        }
2796        let source = deeper_boundary_fixture::docx("<w:p><w:r><w:t>old</w:t></w:r></w:p>");
2797        let legacy = EditPlan::from_json(r#"{"schema_version":1,"author":"T","date":"2026-10-17T12:00:00Z","existing_revisions":"keep","operations":[{"kind":"replace","paragraph":"p0","find":"old","replacement":"new"}]}"#).unwrap();
2798        let view = super::super::for_edit::for_edit(
2799            &source,
2800            &super::super::for_edit::ForEditRequest {
2801                all: true,
2802                ..Default::default()
2803            },
2804        )
2805        .unwrap();
2806        let target = &view.paragraphs[0].target;
2807        let value = serde_json::json!({
2808            "schema_version": 2, "source": {"sha256": source_sha256(&source)},
2809            "author": "T", "date": "2026-10-17T12:00:00Z",
2810            "policy": {"track": "off", "existing_revisions": "keep", "text_view":"final"},
2811            "resolve_revisions":{"accept":[],"reject":[]}, "scope": {"kind":"all"},
2812            "operations": [{"kind":"replace", "target": {"short_id":target.short_id,"long_id":target.long_id}, "find":"old", "text":"new"}]
2813        });
2814        let plan = super::super::v2::PlanV2::from_json(&value.to_string()).unwrap();
2815        // The requested DOM reads "new", while the fake serializer emits "wrong".
2816        SERIALIZED_CANDIDATE.with(|c| {
2817            *c.borrow_mut() = Some(deeper_boundary_fixture::docx(
2818                "<w:p><w:r><w:t>wrong</w:t></w:r></w:p>",
2819            ));
2820        });
2821        let _reset = Reset;
2822        let v1 = prepare(&source, &legacy, &PrepareOptions::default());
2823        assert!(v1.is_err(), "v1 must detect the serializer disagreement");
2824        let expected = v1.unwrap_err();
2825        assert_eq!(expected.code, "POSTCONDITION_FAILED");
2826        for track in [super::super::v2::Track::Off, super::super::v2::Track::On] {
2827            let mut plan = plan.clone();
2828            plan.policy.track = track;
2829            let actual = prepare_v2(&source, &plan, &PrepareOptions::default());
2830            assert!(
2831                actual.is_err(),
2832                "prepare_v2 must refuse the same serialized-text disagreement as prepare"
2833            );
2834            assert_eq!(actual.unwrap_err().code, expected.code);
2835        }
2836    }
2837}
2838
2839#[cfg(test)]
2840#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2841mod blame_branch_tests {
2842    use super::*;
2843
2844    fn refusal(artifact: &'static str, code: &str, part: &str, subject: &str) -> Refusal {
2845        Refusal {
2846            artifact,
2847            code: code.into(),
2848            part: part.into(),
2849            subject: subject.into(),
2850            error: err("CANDIDATE_INVALID", None, "bad"),
2851        }
2852    }
2853
2854    #[test]
2855    fn the_same_defect_matches_on_every_field_but_the_error() {
2856        let base = refusal("redline", "X", "word/document.xml", "r1");
2857        assert!(base.same(&refusal("redline", "X", "word/document.xml", "r1")));
2858        for other in [
2859            refusal("clean", "X", "word/document.xml", "r1"),
2860            refusal("redline", "Y", "word/document.xml", "r1"),
2861            refusal("redline", "X", "word/header1.xml", "r1"),
2862            refusal("redline", "X", "word/document.xml", "r2"),
2863        ] {
2864            assert!(!base.same(&other), "{other:?}");
2865        }
2866    }
2867
2868    fn outcome(id: &str, paragraph: Option<&str>) -> EditOutcome {
2869        EditOutcome {
2870            id: id.into(),
2871            kind: "replace".into(),
2872            status: "ok".into(),
2873            paragraph: paragraph.map(Into::into),
2874            matches: 1,
2875            context: None,
2876            comment_id: None,
2877            anchor_given: None,
2878            anchor_read_as: None,
2879            near: None,
2880            candidates: Vec::new(),
2881            code: None,
2882            message: None,
2883        }
2884    }
2885
2886    #[test]
2887    fn naming_lists_every_operation_that_brings_the_defect() {
2888        let outcomes = [
2889            outcome("e1", Some("p0")),
2890            outcome("e2", None),
2891            outcome("e3", None),
2892        ];
2893        let error = || err("CANDIDATE_INVALID", None, "broken");
2894        assert_eq!(naming(error(), &[], &outcomes).message, "broken");
2895        let one = naming(error(), &[0], &outcomes);
2896        assert_eq!(one.operation.as_deref(), Some("e1"));
2897        assert_eq!(one.message, "broken; e1 (replace on p0) introduces it");
2898        let two = naming(error(), &[1, 0], &outcomes);
2899        assert_eq!(
2900            two.message,
2901            "broken; e2 (replace) introduces it, together with e1 (replace on p0)"
2902        );
2903        let many = naming(error(), &[0, 1, 2, 7], &outcomes);
2904        assert_eq!(
2905            many.message,
2906            "broken; e1 (replace on p0) introduces it, together with e2 (replace), e3 (replace) and /operations/7"
2907        );
2908        let unknown = naming(error(), &[9], &outcomes);
2909        assert_eq!(unknown.operation.as_deref(), Some("/operations/9"));
2910    }
2911}
2912
2913#[cfg(test)]
2914#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2915mod marker_branch_tests {
2916    use super::super::deeper_boundary_fixture::docx;
2917    use super::*;
2918
2919    #[test]
2920    fn range_markers_skip_go_back_and_nameless_bookmarks() {
2921        let source = docx(
2922            r#"<w:p><w:bookmarkStart w:id="0" w:name="_GoBack"/><w:bookmarkEnd w:id="0"/><w:bookmarkStart w:id="1"/><w:bookmarkEnd w:id="1"/><w:bookmarkStart w:id="2" w:name="Kept"/><w:bookmarkEnd w:id="2"/><w:permStart w:id="3" w:edGrp="everyone"/><w:r><w:t>Text</w:t></w:r><w:permEnd w:id="3"/></w:p>"#,
2923        );
2924        let markers = range_markers(&source);
2925        assert_eq!(
2926            markers.bookmarks.into_iter().collect::<Vec<_>>(),
2927            vec!["Kept"]
2928        );
2929        assert_eq!(markers.permissions, 1);
2930        assert_eq!(markers.comments, 0);
2931        let none = range_markers(b"not a package");
2932        assert!(none.bookmarks.is_empty() && none.permissions == 0);
2933    }
2934
2935    #[test]
2936    fn a_location_without_a_step_moves_nowhere() {
2937        let source = docx("<w:p><w:r><w:t>Text</w:t></w:r></w:p>");
2938        let pkg = crate::opc::PartFs::open(&source).unwrap();
2939        let (mut a, mut b) = (HashMap::new(), HashMap::new());
2940        assert_eq!(
2941            moved_location(
2942                &pkg,
2943                &pkg,
2944                &mut a,
2945                &mut b,
2946                "word/document.xml",
2947                "/w:document"
2948            ),
2949            None
2950        );
2951        assert!(a.is_empty() && b.is_empty());
2952    }
2953}