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