1use 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
29fn 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
42pub 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
55const BLOCKING_CODES: &[&str] = &["BOOKMARK_CROSSES_REVISION", "CELL_FINAL_MARK_REVISION"];
62
63fn blocking(f: &Finding) -> bool {
65 f.word_fatal || BLOCKING_CODES.contains(&f.code.as_str())
66}
67
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub enum PrimaryBytes {
71 Source,
74 Candidate,
76}
77
78#[derive(Clone, Debug, Default, PartialEq, Eq)]
80pub struct CandidateChecks {
81 pub baseline: Vec<Finding>,
84 pub introduced: Vec<Finding>,
87 pub unresolved: Vec<Finding>,
89 pub integrity: bool,
91 pub operation_postconditions: bool,
93}
94
95impl CandidateChecks {
96 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
118pub enum PrimaryRole {
119 #[default]
123 Clean,
124 Redline,
127}
128
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub struct PrepareOptions {
132 pub require_change: bool,
136 pub exact_text: bool,
142 pub role: PrimaryRole,
149 pub syntax: super::PlanSyntax,
152 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#[derive(Clone, Debug)]
174pub struct PreparedEdit {
175 pub result: EditResult,
177 pub source_sha256: String,
179 pub request_sha256: String,
181 pub primary: Vec<u8>,
183 pub primary_bytes: PrimaryBytes,
185 pub primary_sha256: String,
187 pub primary_effect: Effect,
190 pub checks: CandidateChecks,
192 pub correspondence: Option<crate::expect::SourceToOutputCorrespondence>,
197 pub skipped: Vec<super::SkippedOperation>,
200}
201
202pub fn prepare(
215 source: &[u8],
216 plan: &EditPlan,
217 options: &PrepareOptions,
218) -> Result<PreparedEdit, EditError> {
219 if options.skip_failed {
220 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 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
243pub(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 let bits = (usize::BITS - count.leading_zeros()) as usize;
289 let alone = distinct.len() * bits >= count;
290 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 Err(Box::new(Blame::Candidate(failure.error, blamed)))
317}
318
319pub(super) enum Blame {
321 Plain(EditError),
324 Candidate(EditError, Vec<(usize, EditError)>),
329}
330
331#[derive(Default)]
334struct SourceChecks {
335 findings: std::cell::OnceCell<Option<Vec<Finding>>>,
337 revision_ids: std::cell::OnceCell<Option<HashMap<(String, String), usize>>>,
339}
340
341#[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 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
366type Refused = Vec<Refusal>;
369
370fn 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
387struct Failure {
391 error: EditError,
392 refusal: Option<(Refused, Vec<EditOutcome>)>,
393 advice: Option<&'static str>,
394}
395
396struct 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 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 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
433fn 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
451fn 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
480fn 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
522fn 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 let all: Vec<usize> = (0..count).collect();
544 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 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
589fn 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 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#[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
673fn 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 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 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
716fn 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 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#[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#[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
797fn screen_candidates(
805 source: &[u8],
806 result: &EditResult,
807 known: &SourceChecks,
808) -> Result<CandidateChecks, Refused> {
809 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 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 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 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 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 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
961fn 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
1099fn 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, ¶_id)
1113 && let Some(found) = sole_index(&candidate.nodes, |sibling| {
1114 candidate_dom.attribute(sibling, ¶_id) == Some(id)
1115 })
1116 && sole_index(&source.nodes, |sibling| {
1117 source_dom.attribute(sibling, ¶_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
1197fn 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
1255struct ExpectedText {
1258 op: String,
1260 text: String,
1262 ignore_symbols: bool,
1265 scope: ExpectedScope,
1267}
1268
1269#[derive(Clone, Copy)]
1271enum ExpectedScope {
1272 Paragraph,
1274 Control(usize),
1279}
1280
1281fn expected_texts(
1286 tx: &Transaction<'_>,
1287 exact: bool,
1288) -> Result<Vec<(usize, ExpectedText)>, EditError> {
1289 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 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 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 let empty = base.is_empty();
1364 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 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 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 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 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 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(¶)
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(¶);
1490 }
1491 for para in filled {
1492 expected.remove(¶);
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
1510fn 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
1528fn 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
1539fn 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
1547pub(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 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
1590fn 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
1597pub(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
1681fn 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 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 ¶graphs(&clean)?,
1734 ¶graphs(&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
1764fn 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 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 #[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 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 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 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 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 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
1914fn 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
1967fn 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
1993fn err(code: &str, operation: Option<&str>, message: impl Into<String>) -> EditError {
1995 super::err(code, operation, message)
1996}
1997
1998pub 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 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
2030fn prepare_v2_once(
2033 source: &[u8],
2034 plan: &super::v2::PlanV2,
2035 options: &PrepareOptions,
2036 known: &SourceChecks,
2037) -> Result<PreparedEdit, Box<Failure>> {
2038 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 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 #[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 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 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 assert!(
2240 gate(
2241 &[("customXmlInsRangeStart", 5)],
2242 &[("customXmlInsRangeStart", 5)]
2243 )
2244 .is_ok()
2245 );
2246 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 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 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 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 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 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 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 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 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 assert_eq!(culprits_of(10, true, &[&[6], &[3]]).0, Some(vec![3]));
2382 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 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 assert_eq!(culprits_of(5, true, &[&[]]).0, None);
2403 assert_eq!(culprits_of(0, true, &[]).0, None);
2404 }
2405
2406 #[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 #[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 #[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 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 #[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 pub(crate) static PREPARATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2683 }
2684
2685 #[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 let preparations = PREPARATIONS.with(std::cell::Cell::get);
2726 assert!(
2727 preparations <= n + 1,
2728 "{preparations} preparations for {n} operations"
2729 );
2730 }
2731
2732 #[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 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 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 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}