Skip to main content

jubarte_doc/
validate.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Word-validity findings beyond the schema: what makes Word refuse or
6//! repair a package, as data.
7//!
8//! [`validate`] runs the Ring-1 invariants (the checks the test suite has
9//! gated every produced package on) and the five `jubarte debug` triage
10//! checks, and returns one [`Finding`](crate::validate::Finding) per problem with a stable `code`.
11//! [`repair`](crate::validate::repair) fixes the findings that have a deterministic fix and reports
12//! what it could not fix. [`audit_tracked`](crate::validate::audit_tracked) is `validate.py --original
13//! --author` without an XSD: every visible-text difference between an
14//! original and an edited document must sit in a revision by one author.
15//!
16//! XSD validation stays with `tools/validate-docx` (OpenXmlValidator); the
17//! question answered here is "will Word open it", which a schema does not
18//! answer.
19//!
20//! Codes, with whether Word refuses or repairs the file for them
21//! (`word_fatal`) and whether [`repair`](crate::validate::repair) fixes them (`repairable`):
22//!
23//! | Code | `word_fatal` | `repairable` |
24//! |---|---|---|
25//! | `MC_UNBOUND_PREFIX` | yes | when the prefix is a conventional one |
26//! | `MISSING_CONTENT_TYPE`, `OVERRIDE_WITHOUT_PART`, `MALFORMED_XML` | yes | no |
27//! | `DANGLING_RELATIONSHIP` | yes for `r:id`, `r:embed`, `r:link`; other names (`r:dm`, `r:pict`, ...) are unverified leads (#1937) | yes: the attribute is dropped |
28//! | `DUPLICATE_RID` | yes | an identical repeat is kept once on open; two relationships under one Id are refused |
29//! | `MISSING_REL_TARGET` | yes when used by markup; unused relationships are unverified warning leads (#1938) | no |
30//! | `PICTURE_BULLET_UNDEFINED` | yes | no |
31//! | `DUPLICATE_REVISION_ID` | no: Word opens same-kind duplicates (102 probes, 2026-10-18, #1137); the OOXML validator refuses them (`Sem_UniqueAttributeValue`); error diagnostic | yes: renumbered |
32//! | `DUPLICATE_DOCPR_ID` | no (lead): also across story parts and for a header or footer with drawings that two sections share; Windows Word 2024 refused 16 such redlines and opened 24 (2026-11-23) | yes: renumbered across parts; a shared part with drawings is copied per section |
33//! | `VML_SHAPE_TYPE_INVALID` | no: self-referential or missing VML type; warning (#1800) | no |
34//! | `PARA_ID_OUT_OF_RANGE` | no: Word opens it; the schema forbids it | yes: renumbered |
35//! | `TEXT_INSIDE_DELETION`, `DELTEXT_OUTSIDE_DELETION`, `MOVEFROM_WITH_DELTEXT` | yes | yes: `w:t` and `w:delText` swapped |
36//! | `INSTR_TEXT_INSIDE_DELETION` | no (not probed in Word) | yes |
37//! | `BOOKMARK_IN_SINGLE_VALUE_CONTROL` | yes | yes: the bookmark is dropped |
38//! | `COMMENT_ANCHOR_ORPHAN` | yes | yes: the anchor is dropped |
39//! | `COMMENT_RANGE_ORPHAN` | no: Word opens it | yes: the marker is dropped |
40//! | `COMMENT_PARTS_INCONSISTENT` | yes | no |
41//! | `COMMENT_UNANCHORED`, `COMMENT_ID_REPEATED`, `COMMENT_METADATA_MISMATCH`, `COMMENT_PARENT_CYCLE` | no: Word opens it | no |
42//! | `RUN_OUTSIDE_PARAGRAPH` | yes | no |
43//! | `RUBY_OUTSIDE_RUN` | no: direct paragraph child rejected by OpenXmlValidator; Word unverified (#1711) | no |
44//! | `FIELD_UNBALANCED`, `FIELD_SPLIT_DELETION` | yes | no |
45//! | `FIELD_CODE_STATE` | no | no |
46//! | `EMPTY_FIELD_CODE`, `ROW_WITHOUT_CELL`, `SECTPR_NOT_LAST` | yes | no |
47//! | `NESTED_SAME_REVISION` | no: Word opens direct same-kind nests faithfully (info); alternating nests misread reject-all (warning); probe 2026-10-17, #1134 | no |
48//! | `CELL_WITHOUT_PARAGRAPH` | yes | yes: an empty paragraph is appended |
49//! | `NOTE_REFERENCE_DANGLING` | yes | no |
50//! | `DUPLICATE_EXPANDED_ATTRIBUTE` | yes: aliased duplicate refused by Word (#650) | no |
51//! | `NESTED_TEXT_BOX` | yes: A/C/E crash; F/H refuse to load; B/D/G open (Word probes 2026-10-18, #1132) | no |
52//! | `COMMENT_RANGE_UNPAIRED`, `BARE_RUN_IN_DELETED_TEXTBOX`, `BOOKMARK_*` | no | no |
53//! | `MOVE_RANGE_COUNT_MISMATCH` | no: Word opens it but Reject All can duplicate moved text (#1214); warning | no |
54//! | `MOVE_RANGE_NAME_MISSING` | no: `w:name` is schema-required; Word's reaction to a nameless range is unverified (#1939); warning | no |
55//! | `DATA_BINDING_WITHOUT_STORE` | no: Word opens it and shows the bound control empty (#1427); warning | no |
56//! | `CELL_FINAL_MARK_REVISION` | no: Word opens it, but Accept All or Reject All never returns (#1669, Word 16, 2026-10-23); error diagnostic | no |
57//! | `DELETED_SECTION_PAGE_FIELD` | no: Word 16.115 crashed opening 9 of 11 such redlines (#1833, 2026-10-25); warning | no |
58//! | `INSERTED_TEXT_BEFORE_DELETED_TABLE` | no: Word 16.115 crashed opening 6 of the 16 release-sample redlines with the paragraph right before the table (#1851, 2026-10-25); warning | no |
59//! | `NON_FINITE_MEASURE` | yes for `gridCol` (Word 16.115, 2026-10-31: `gridcol-NaN`, `gridcol-inf`, `gridcol-1e40` unreadable); `tcW` and `tblW` open (`tcw-*`, `tblw-*`, `valid-control` clean, #1737) | no |
60//! | `UNTRACKED_EDIT`, `FOREIGN_AUTHOR`, `FOREIGN_COMMENT` | n/a | no |
61//!
62//! Revision ids are unique per OOXML record type within a part, as
63//! OpenXmlValidator checks them (`Sem_UniqueAttributeValue`): two `w:ins`
64//! runs sharing an id are a finding, a `w:ins` and a `w:del` sharing one are
65//! not, and neither is the `pPrChange`/`rPrChange` pair Word writes in style
66//! histories. Word opens every duplicate-id probe (102 files, 2026-10-18,
67//! #1137), so this is an error diagnostic, not Word-fatal.
68//!
69//! The comment codes follow a 98-file Word probe (2026-10-10). Word opens
70//! a comment whatever its range markers: missing, reversed, repeated, at
71//! block level, across paragraphs or cells. It shows the comment only from
72//! a `w:commentReference` in a paragraph of the main story. It refuses a
73//! reference whose id has no definition, two references for one id, any
74//! anchor when there is no comments part, and a run outside a paragraph.
75//! Of the parts beside `word/comments.xml` it refuses an id that is not
76//! hexadecimal, an entry without its paraId, and a part not related exactly
77//! once, to itself, with its content type; any other disagreement between
78//! them (missing, extra or repeated entries, out-of-range ids, dangling or
79//! cyclic parents) opens and shows the comment.
80
81use std::collections::{HashMap, HashSet};
82use std::fmt;
83
84use quick_xml::events::Event;
85use serde::{Deserialize, Serialize};
86
87use crate::admission::{AdmissionError, InputLimits};
88use crate::changes::{Change, ChangeError, ChangeFilter, list_changes, reject_changes};
89use crate::inspect::InspectError;
90use crate::namespaces::{MC, R, VML, W, W14, WP};
91use crate::opc::PartFs;
92use crate::xmllinq::serialize::{well_known_namespace, well_known_prefix};
93use crate::xmllinq::{Dom, NodeId, XName};
94
95/// One thing wrong with a package, from any rule set: Word validity
96/// (`word`), tracked-edit discipline (`edits`), or the [`crate::audit`] sets
97/// (`a11y`, `style`, `structure`). For `word` and `edits`, `location` is the
98/// element chain inside `part` (`w:body[0]/w:p[3]/w:r[2]`, each name indexed
99/// among its same-named siblings, root excluded), stable across runs, or a
100/// paragraph id (`p3`); empty for a package-level finding. For the audit
101/// sets it is the paragraph id (`p5`, `header1`, `header1.p1`:
102/// [`crate::ids::paragraph_id`]) or, when no paragraph applies, the part
103/// name. `ref` is the same text as `location`. Messages name paragraphs by
104/// the same ids.
105#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
106pub struct Finding {
107    /// Stable code (`TEXT_INSIDE_DELETION`, `MC_UNBOUND_PREFIX`, ...).
108    pub code: String,
109    /// The rule set it belongs to: one of `RULE_SETS`.
110    pub set: String,
111    /// `error`, `warning` or `info`. A `word` finding is an `error` when
112    /// Word-fatal, OOXML-invalid (`DUPLICATE_REVISION_ID`), or a revision
113    /// Word cannot resolve (`CELL_FINAL_MARK_REVISION`); otherwise a
114    /// `warning` (a lead), or `info` for direct
115    /// same-kind revision nesting that Word reads faithfully.
116    pub severity: String,
117    /// Package part the finding sits in.
118    pub part: String,
119    /// Where in the part (see the type's doc), or empty.
120    pub location: String,
121    /// The short id the text listing prints for [`Finding::location`].
122    #[serde(default, rename = "ref")]
123    pub r#ref: String,
124    /// Human-readable detail.
125    pub message: String,
126    /// True when Word refuses or repairs the file for this (Ring-1 and
127    /// Ring-3 evidence); false for leads (`DUPLICATE_DOCPR_ID`) and for
128    /// every finding outside the `word` set.
129    pub word_fatal: bool,
130    /// True when [`repair`] fixes it deterministically.
131    pub repairable: bool,
132}
133
134/// Every rule set `validate` runs, `word` (the default) first.
135#[doc(hidden)]
136pub const RULE_SETS: &[&str] = &["word", "edits", "a11y", "style", "structure"];
137
138impl Finding {
139    /// A `word` finding with `word_fatal` and `repairable` taken from the
140    /// code's table ([`traits`]). OOXML-invalid duplicate revision ids and
141    /// a cell's final mark revision are errors, though Word opens them.
142    pub fn new(
143        code: &str,
144        part: &str,
145        location: impl Into<String>,
146        message: impl Into<String>,
147    ) -> Self {
148        let (word_fatal, repairable) = traits(code);
149        let location = location.into();
150        let r#ref = location.clone();
151        Finding {
152            code: code.to_string(),
153            set: "word".to_string(),
154            severity: if word_fatal || ERROR_LEADS.contains(&code) {
155                "error"
156            } else {
157                "warning"
158            }
159            .to_string(),
160            part: part.to_string(),
161            location,
162            r#ref,
163            message: message.into(),
164            word_fatal,
165            repairable,
166        }
167    }
168}
169
170/// Errors without a Word-fatal claim: schema-invalid revision ids or ruby,
171/// and a cell's final mark revision Word's Accept All or Reject All never
172/// returns from (#1669). Word's response to paragraph-level ruby is unverified.
173const ERROR_LEADS: [&str; 3] = [
174    "DUPLICATE_REVISION_ID",
175    "CELL_FINAL_MARK_REVISION",
176    "RUBY_OUTSIDE_RUN",
177];
178
179/// `(word_fatal, repairable)` for a code; an unknown code is a lead with
180/// no repair.
181pub fn traits(code: &str) -> (bool, bool) {
182    match code {
183        "MC_UNBOUND_PREFIX"
184        | "DANGLING_RELATIONSHIP"
185        | "TEXT_INSIDE_DELETION"
186        | "DELTEXT_OUTSIDE_DELETION"
187        | "MOVEFROM_WITH_DELTEXT"
188        | "BOOKMARK_IN_SINGLE_VALUE_CONTROL"
189        | "COMMENT_ANCHOR_ORPHAN"
190        | "CELL_WITHOUT_PARAGRAPH"
191        // Only an identical repeat is reported (two relationships under one
192        // Id are refused on open), and opening already keeps it once.
193        | "DUPLICATE_RID" => (true, true),
194        "MISSING_CONTENT_TYPE"
195        | "OVERRIDE_WITHOUT_PART"
196        | "MALFORMED_XML"
197        | "DUPLICATE_EXPANDED_ATTRIBUTE"
198        | "MISSING_REL_TARGET"
199        | "PICTURE_BULLET_UNDEFINED"
200        | "COMMENT_PARTS_INCONSISTENT"
201        | "FIELD_UNBALANCED"
202        | "RUN_OUTSIDE_PARAGRAPH"
203        | "FIELD_SPLIT_DELETION"
204        | "EMPTY_FIELD_CODE"
205        | "ROW_WITHOUT_CELL"
206        | "SECTPR_NOT_LAST"
207        | "NESTED_TEXT_BOX"
208        | "NOTE_REFERENCE_DANGLING"
209        // `gridCol` only. `tcW` and `tblW` clear `word_fatal` on the finding.
210        | "NON_FINITE_MEASURE" => (true, false),
211        "DUPLICATE_REVISION_ID"
212        | "DUPLICATE_DOCPR_ID"
213        | "INSTR_TEXT_INSIDE_DELETION"
214        | "PARA_ID_OUT_OF_RANGE"
215        | "COMMENT_RANGE_ORPHAN" => (false, true),
216        _ => (false, false),
217    }
218}
219
220/// Codes the Ring-1 checks own; the triage checks' findings under these
221/// codes are the same problems seen twice and are left out of [`validate`].
222const RING1_CODES: [&str; 39] = [
223    "DATA_BINDING_WITHOUT_STORE",
224    "MOVE_RANGE_COUNT_MISMATCH",
225    "MOVE_RANGE_NAME_MISSING",
226    "NESTED_TEXT_BOX",
227    "NESTED_PPR",
228    "MC_UNBOUND_PREFIX",
229    "MISSING_CONTENT_TYPE",
230    "MALFORMED_XML",
231    "DUPLICATE_EXPANDED_ATTRIBUTE",
232    "DANGLING_RELATIONSHIP",
233    "DUPLICATE_RID",
234    "MISSING_REL_TARGET",
235    "PICTURE_BULLET_UNDEFINED",
236    "DUPLICATE_REVISION_ID",
237    "DUPLICATE_DOCPR_ID",
238    "VML_SHAPE_TYPE_INVALID",
239    "PARA_ID_OUT_OF_RANGE",
240    "TEXT_INSIDE_DELETION",
241    "INSTR_TEXT_INSIDE_DELETION",
242    "DELTEXT_OUTSIDE_DELETION",
243    "MOVEFROM_WITH_DELTEXT",
244    "BOOKMARK_IN_SINGLE_VALUE_CONTROL",
245    "COMMENT_ANCHOR_ORPHAN",
246    "COMMENT_RANGE_ORPHAN",
247    "COMMENT_PARTS_INCONSISTENT",
248    "COMMENT_PARENT_CYCLE",
249    "RUN_OUTSIDE_PARAGRAPH",
250    "RUBY_OUTSIDE_RUN",
251    "COMMENT_UNANCHORED",
252    "COMMENT_ID_REPEATED",
253    "COMMENT_METADATA_MISMATCH",
254    "STYLE_NAME_COMMA",
255    "CELL_FINAL_MARK_REVISION",
256    "DELETED_SECTION_PAGE_FIELD",
257    "INSERTED_TEXT_BEFORE_DELETED_TABLE",
258    "NON_FINITE_MEASURE",
259    "DUPLICATE_DURABLE_ID",
260    "STYLE_CHANGE_SIBLINGS",
261    "DOC_DEFAULTS_CHANGE",
262];
263
264/// Why a package could not be validated at all (a finding is never an
265/// error).
266#[derive(Clone, Debug, PartialEq, Eq)]
267pub enum ValidateError {
268    /// Refused before parsing by [`crate::admission`].
269    Refused(AdmissionError),
270    /// The package could not be read or written.
271    Package(String),
272    /// The tracked changes could not be listed or rejected.
273    Changes(ChangeError),
274    /// The paragraphs could not be read.
275    Inspect(InspectError),
276    /// The rules asked for cannot run: an unknown rule, or `edits` without
277    /// the original document and author.
278    Usage(String),
279    /// The layout pass an audit rule reads failed.
280    Layout(String),
281}
282
283impl fmt::Display for ValidateError {
284    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285        match self {
286            Self::Refused(e) => write!(f, "DOCX refused: {e}"),
287            Self::Package(m) => write!(f, "invalid package: {m}"),
288            Self::Changes(e) => write!(f, "{e}"),
289            Self::Inspect(e) => write!(f, "{e}"),
290            Self::Usage(m) => write!(f, "{m}"),
291            Self::Layout(m) => write!(f, "layout pass failed: {m}"),
292        }
293    }
294}
295
296impl std::error::Error for ValidateError {}
297
298impl From<AdmissionError> for ValidateError {
299    fn from(e: AdmissionError) -> Self {
300        Self::Refused(e)
301    }
302}
303
304impl From<ChangeError> for ValidateError {
305    fn from(e: ChangeError) -> Self {
306        Self::Changes(e)
307    }
308}
309
310impl From<InspectError> for ValidateError {
311    fn from(e: InspectError) -> Self {
312        Self::Inspect(e)
313    }
314}
315
316impl From<crate::opc::OpcError> for ValidateError {
317    fn from(e: crate::opc::OpcError) -> Self {
318        Self::Package(e.to_string())
319    }
320}
321
322/// The package with every repairable finding fixed, the findings it fixed
323/// and the ones it could not. Untouched parts keep their bytes.
324#[derive(Clone, Debug, PartialEq, Eq)]
325pub struct Repaired {
326    /// The repaired package.
327    pub docx: Vec<u8>,
328    /// Findings of the input that the output no longer has.
329    pub repaired: Vec<Finding>,
330    /// Findings the output still has.
331    pub remaining: Vec<Finding>,
332}
333
334/// [`validate`] with rule sets: `word` (the default), `edits`, and the
335/// [`crate::audit`] sets or codes (`a11y`, `style`, `structure`,
336/// `LITERAL_BULLET`, ...). `original` (the document before the edits and the
337/// author every change must carry) adds `edits`. `layout` is the pass the
338/// audit's `FONT_SUBSTITUTED` and `STALE_FIELD_CACHE` read
339/// (`crate::audit::word_layout` with the `render` feature; `None` in a build without the
340/// renderer). Findings come word first (by part, location, code and
341/// message), then edits, then the audit's in its rule order.
342///
343/// # Errors
344///
345/// [`ValidateError::Usage`] for an unknown rule, or `edits` without
346/// `original`; otherwise as [`validate`] and [`audit_tracked`].
347pub fn validate_with(
348    docx: &[u8],
349    rules: &[&str],
350    original: Option<(&[u8], &str)>,
351    layout: Option<crate::audit::LayoutPass<'_>>,
352) -> Result<Vec<Finding>, ValidateError> {
353    let mut word = rules.is_empty();
354    let mut edits = original.is_some();
355    let mut audit = Vec::new();
356    for &rule in rules {
357        match rule {
358            "word" => word = true,
359            "edits" => edits = true,
360            _ if crate::audit::is_rule(rule) => audit.push(rule),
361            _ => return Err(ValidateError::Usage(unknown_rule(rule))),
362        }
363    }
364    let mut out = Vec::new();
365    if word {
366        out.extend(validate(docx)?);
367    }
368    if edits {
369        let Some((before, author)) = original else {
370            return Err(ValidateError::Usage(
371                "rules edits needs --author, and --original or --baseline".to_string(),
372            ));
373        };
374        out.extend(audit_tracked(before, docx, author)?);
375    }
376    if !audit.is_empty() {
377        let report =
378            crate::audit::audit_report_with(docx, &audit, layout).map_err(|e| match e {
379                crate::audit::AuditError::Inspect(e) => ValidateError::Inspect(e),
380                crate::audit::AuditError::Layout(m) => ValidateError::Layout(m),
381                crate::audit::AuditError::UnknownRule(rule) => {
382                    ValidateError::Usage(unknown_rule(&rule))
383                }
384            })?;
385        out.extend(report.findings.into_iter().map(Finding::from));
386    }
387    Ok(out)
388}
389
390/// [`validate_with`] on `docx`, split by the findings of `base`, the
391/// document the edits started from, under the same rules and against the
392/// same original ([`baseline_keyed`], each side's keys read in its own
393/// document by [`identities`]). That original is `base` unless `original`
394/// names another; `author` turns the `edits` rule on as `validate_with`'s
395/// `original` does, so the other party's changes `base` already had are
396/// the input's, not the edit's. `Baselined::authors` names who signed the
397/// markup `docx` gained over the baseline, whoever that is (#1893): the
398/// summary needs no expected author, only `none of it is signed` does.
399///
400/// # Errors
401///
402/// As [`validate_with`], for either document.
403pub fn validate_baselined(
404    docx: &[u8],
405    base: &[u8],
406    rules: &[&str],
407    original: Option<&[u8]>,
408    author: Option<&str>,
409    layout: Option<crate::audit::LayoutPass<'_>>,
410) -> Result<Baselined, ValidateError> {
411    let against = original.or(Some(base)).zip(author);
412    // The pass runs once per document: lend it to the first call and keep
413    // it for the second. Without the renderer the only value is `None`.
414    #[cfg(feature = "render")]
415    let mut layout = layout;
416    #[cfg(feature = "render")]
417    let first = layout
418        .as_mut()
419        .map(|pass| &mut **pass as crate::audit::LayoutPass<'_>);
420    #[cfg(not(feature = "render"))]
421    let first = layout;
422    let findings = validate_with(docx, rules, against, first)?;
423    let inherited = validate_with(base, rules, against, layout)?;
424    let keys = identities(docx, &findings);
425    let inherited_keys = identities(base, &inherited);
426    let mut split = baseline_keyed(findings, &keys, inherited, &inherited_keys);
427    // The new markup is what the edit gained over the baseline, whoever
428    // signed it: the summary names them even without an author to check
429    // them against (#1893).
430    split.authors = new_markup(base, docx)?;
431    if let Some(author) = author {
432        split.author = Some(author.to_string());
433    }
434    Ok(split)
435}
436
437/// Who signed the markup `edited` gained over `original` (#1893): the
438/// [`check_foreign_revisions`] comparison with nobody skipped — an author
439/// the run was given is the only one skipped, so a revision that names
440/// none counts as `<no author>` — read from its `is new` findings, plus
441/// `edited`'s comments no comment of `original` pairs with. One row per
442/// name, in first-appearance order: changes in document order, then
443/// comments. A change counts once, as `changes` lists it.
444fn new_markup(original: &[u8], edited: &[u8]) -> Result<Vec<AuthorMark>, ValidateError> {
445    /// One more change or comment signed by `name`.
446    fn add(marks: &mut Vec<AuthorMark>, name: &str, comment: bool) {
447        let mark = match marks.iter_mut().find(|m| m.name == name) {
448            Some(mark) => mark,
449            None => {
450                marks.push(AuthorMark {
451                    name: name.to_string(),
452                    ..AuthorMark::default()
453                });
454                marks.last_mut().expect("just pushed")
455            }
456        };
457        if comment {
458            mark.comments += 1;
459        } else {
460            mark.changes += 1;
461        }
462    }
463    let wholes = foreign_wholes(original, edited);
464    let mut revisions = Vec::new();
465    check_foreign_revisions(original, edited, None, &wholes, &mut revisions)?;
466    let mut out = Vec::new();
467    let mut counted: HashSet<(&str, &str)> = HashSet::new();
468    for finding in &revisions {
469        if let Some((id, author)) = new_foreign(finding) {
470            // The finding names the change as `changes` lists it, or one
471            // mark of it; the map names the change either way.
472            let change = wholes.whole(false, id);
473            if counted.insert((change, author)) {
474                add(&mut out, author, false);
475            }
476        }
477    }
478    let after = comments_of(edited)?;
479    let (_, _, paired) = comment_pairs(&comments_of(original)?, &after);
480    for (comment, &paired) in after.iter().zip(&paired) {
481        if !paired {
482            add(
483                &mut out,
484                if comment.author.is_empty() {
485                    "<no author>"
486                } else {
487                    &comment.author
488                },
489                true,
490            );
491        }
492    }
493    Ok(out)
494}
495
496/// The usage message for a rule that is neither a set nor an audit code.
497fn unknown_rule(rule: &str) -> String {
498    let codes: Vec<&str> = crate::audit::RULES.iter().map(|rule| rule.0).collect();
499    format!(
500        "unknown rule {rule}; expected one of {} or {}",
501        RULE_SETS.join(", "),
502        codes.join(", ")
503    )
504}
505
506/// True when `findings` fail a run: any `word` or `edits` finding, any
507/// `error`, or (`strict`) any `warning`.
508pub fn fails(findings: &[Finding], strict: bool) -> bool {
509    findings.iter().any(|f| {
510        matches!(f.set.as_str(), "word" | "edits")
511            || f.severity == "error"
512            || (strict && f.severity == "warning")
513    })
514}
515
516/// One line per finding, then a summary. A line is `* CODE\tSEVERITY\t
517/// PART#REF\tMESSAGE` for `word` and `edits` (`*` marks Word-fatal, a
518/// space otherwise) and `  CODE\tSEVERITY\tREF\tMESSAGE` for the audit
519/// sets, where `REF` is [`Finding::location`] (a paragraph id such as
520/// `p5`, an element chain or a part name). The summary is `no findings` or
521/// `N finding(s): E error, W warning, I info`.
522pub fn findings_text(findings: &[Finding]) -> String {
523    let mut out = String::new();
524    for f in findings {
525        out.push_str(&finding_line(f));
526    }
527    if findings.is_empty() {
528        out.push_str("no findings\n");
529    } else {
530        let count = |severity: &str| findings.iter().filter(|f| f.severity == severity).count();
531        out.push_str(&format!(
532            "{} finding(s): {} error, {} warning, {} info\n",
533            findings.len(),
534            count("error"),
535            count("warning"),
536            count("info")
537        ));
538    }
539    out
540}
541
542/// One [`findings_text`] line, newline included.
543fn finding_line(f: &Finding) -> String {
544    let star = if f.word_fatal { '*' } else { ' ' };
545    let place = if matches!(f.set.as_str(), "word" | "edits") {
546        format!("{}#{}", f.part, f.location)
547    } else {
548        f.location.clone()
549    };
550    format!(
551        "{star} {}\t{}\t{place}\t{}\n",
552        f.code, f.severity, f.message
553    )
554}
555
556/// What makes a finding in one version of a document the same finding in
557/// another ([`Finding::identity`]): its code, set and part, where it sits
558/// (its paragraph id or element chain, empty for a part-level finding), its
559/// message with element indices dropped (`w:p[3]` reads `w:p`) and
560/// paragraph ids spelled `p#`, and what surrounds it there ([`Place`]). A
561/// finding named by an entity, a durableId or a bookmark, keeps that
562/// entity in its message.
563#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
564pub struct FindingKey {
565    /// [`Finding::code`].
566    pub code: String,
567    /// [`Finding::set`].
568    pub set: String,
569    /// [`Finding::part`].
570    pub part: String,
571    /// [`Finding::location`]; from [`identities`], an element chain with
572    /// its indices dropped, or `p#` for a paragraph id.
573    pub location: String,
574    /// [`Finding::message`], normalised.
575    pub message: String,
576    /// What surrounds the finding in its document, read by [`identities`];
577    /// empty from [`Finding::identity`].
578    pub place: Place,
579}
580
581/// What surrounds a finding in its document ([`identities`]), each part
582/// `None` where there is none: what [`baseline_keyed`] tells two findings
583/// of one kind apart by.
584#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
585pub struct Place {
586    /// The text of the paragraph the finding sits in; outside one, of its
587    /// table, or else of its element with the attributes of that element
588    /// and of everything holding it (a style's `w:styleId`), leaving out
589    /// the ones an edit renumbers.
590    pub text: Option<String>,
591    /// That paragraph's `w14:paraId`.
592    pub paragraph_id: Option<String>,
593    /// The tracked change, or comment, the finding sits in: its element
594    /// and `w:id` (`del 3`); for `FOREIGN_AUTHOR`, the change's id (`r3`).
595    /// `jubarte edit` keeps the input's `w:id` values.
596    pub revision: Option<String>,
597    /// The text of the element before the one [`Self::text`] reads, of its
598    /// name and in the same parent.
599    pub previous: Option<String>,
600    /// The text of the element after it, of its name and in the same
601    /// parent.
602    pub next: Option<String>,
603}
604
605impl Finding {
606    /// This finding's [`FindingKey`]: [`baseline`] matches findings by it.
607    pub fn identity(&self) -> FindingKey {
608        FindingKey {
609            code: self.code.clone(),
610            set: self.set.clone(),
611            part: self.part.clone(),
612            location: self.location.clone(),
613            message: normalised(&self.message),
614            place: Place::default(),
615        }
616    }
617
618    /// What tells this finding from another of its code in its part when
619    /// other edits renumber the document around it: its location's element
620    /// chain without the indices (`p#` for a paragraph id), and its message
621    /// [`normalised`] and without the numbers that stand alone. Names stay
622    /// (a bookmark's `Clause1`, a style's); revision ids, counts and
623    /// indices, which a rerun of fewer operations shifts, do not.
624    #[doc(hidden)]
625    pub fn unnumbered(&self) -> String {
626        let location = if self.location.contains('[') {
627            let mut out = String::with_capacity(self.location.len());
628            for (i, step) in self.location.split('/').enumerate() {
629                if i > 0 {
630                    out.push('/');
631                }
632                out.push_str(step.split_once('[').map_or(step, |(name, _)| name));
633            }
634            out
635        } else if is_paragraph_id(&self.location) {
636            "p#".to_string()
637        } else {
638            self.location.clone()
639        };
640        format!(
641            "{location}\u{1f}{}",
642            without_numbers(&normalised(&self.message))
643        )
644    }
645}
646
647/// `text` with every number that stands alone, not glued to a letter or a
648/// digit-led name, spelled `#`.
649fn without_numbers(text: &str) -> String {
650    let bytes = text.as_bytes();
651    let mut out = String::with_capacity(text.len());
652    let mut i = 0;
653    while i < bytes.len() {
654        let digits = bytes[i..].iter().take_while(|b| b.is_ascii_digit()).count();
655        if digits > 0 {
656            let glued = |at: Option<&u8>| at.is_some_and(u8::is_ascii_alphanumeric);
657            let before = i.checked_sub(1).and_then(|at| bytes.get(at));
658            if glued(before) || glued(bytes.get(i + digits)) {
659                out.push_str(&text[i..i + digits]);
660            } else {
661                out.push('#');
662            }
663            i += digits;
664            continue;
665        }
666        let ch = text[i..].chars().next().expect("a char boundary");
667        out.push(ch);
668        i += ch.len_utf8();
669    }
670    out
671}
672
673/// Each of `findings`' [`FindingKey`], read in `docx`, the document they
674/// were found in. A finding at an element chain or a paragraph id, in any
675/// story, keys by the chain with its indices dropped (`p#` for the id) and
676/// by its [`Place`], so it keeps its identity when an edit moves or
677/// renumbers it. A `FOREIGN_AUTHOR` change keys by its kind, author and
678/// text, and by its id. Anything else keys as [`Finding::identity`] does.
679#[must_use]
680pub fn identities(docx: &[u8], findings: &[Finding]) -> Vec<FindingKey> {
681    let mut anchors = Anchors::new(docx);
682    findings
683        .iter()
684        .map(|f| {
685            let mut key = f.identity();
686            if f.code == "FOREIGN_AUTHOR" {
687                if let Some((id, rest)) = f.message.split_once(' ')
688                    && let Some(change) = anchors.change(id)
689                {
690                    key.message = normalised(rest);
691                    key.place = Place {
692                        text: Some(change),
693                        revision: Some(id.to_string()),
694                        ..Place::default()
695                    };
696                }
697            } else if let Some((location, place)) = anchors.place(&f.part, &f.location) {
698                key.location = location;
699                key.place = place;
700            }
701            key
702        })
703        .collect()
704}
705
706/// What [`identities`] reads a document's places by, each part parsed once.
707struct Anchors<'a> {
708    docx: &'a [u8],
709    pkg: Option<PartFs>,
710    parts: HashMap<String, Option<Part>>,
711    changes: Option<HashMap<String, String>>,
712}
713
714impl<'a> Anchors<'a> {
715    fn new(docx: &'a [u8]) -> Self {
716        Anchors {
717            docx,
718            pkg: PartFs::open(docx).ok(),
719            parts: HashMap::new(),
720            changes: None,
721        }
722    }
723
724    /// `kind, author, text` of change `id` (`r3`), or of the marks a
725    /// composite id names together (`r3+4`, as `changes` lists them).
726    fn change(&mut self, id: &str) -> Option<String> {
727        let docx = self.docx;
728        let listed = self.changes.get_or_insert_with(|| {
729            list_changes(docx)
730                .unwrap_or_default()
731                .into_iter()
732                .map(|c| {
733                    let anchor = format!(
734                        "{:?}\u{1f}{}\u{1f}{}",
735                        c.kind,
736                        c.author.unwrap_or_default(),
737                        c.text
738                    );
739                    (c.id, anchor)
740                })
741                .collect()
742        });
743        let one = |id: &str| listed.get(id).cloned();
744        match crate::ids::parse_change_ids(id) {
745            Ok(marks) if marks.len() > 1 => marks
746                .iter()
747                .map(|mark| one(&mark.short()))
748                .collect::<Option<Vec<_>>>()
749                .map(|anchors| anchors.join("\u{1f}")),
750            _ => one(id),
751        }
752    }
753
754    /// The location `location` in `part` keys by, and its [`Place`];
755    /// `None` when it is neither an element chain of the part nor one of
756    /// the part's paragraph ids.
757    fn place(&mut self, part: &str, location: &str) -> Option<(String, Place)> {
758        if location.is_empty() {
759            return None;
760        }
761        let pkg = self.pkg.as_ref()?;
762        let part = self
763            .parts
764            .entry(part.to_string())
765            .or_insert_with(|| parse_part(pkg, part).map(|(dom, root)| Part::new(dom, root)))
766            .as_mut()?;
767        if location.contains('[') {
768            let node = part.resolve(location)?;
769            let chain: Vec<&str> = location
770                .split('/')
771                .map(|step| step.split_once('[').map_or(step, |(name, _)| name))
772                .collect();
773            Some((chain.join("/"), part.around(node)))
774        } else {
775            let (story, index) = crate::ids::paragraph_place(location)?;
776            let node = *part.paragraphs(&story).get(index)?;
777            Some(("p#".to_string(), part.around(node)))
778        }
779    }
780}
781
782/// A parsed part and the lookups [`Anchors`] made in it, so reading every
783/// finding's place costs one walk of the part.
784struct Part {
785    dom: Dom,
786    root: NodeId,
787    /// Each parent's child elements of one name, keyed by the parent, the
788    /// namespace and the local name.
789    children: HashMap<(NodeId, String, String), Vec<NodeId>>,
790    /// Where each element listed in `children` stands in its list.
791    rank: HashMap<NodeId, usize>,
792    /// The part's paragraphs in the order its paragraph ids count them.
793    paragraphs: Option<Vec<NodeId>>,
794}
795
796impl Part {
797    fn new(dom: Dom, root: NodeId) -> Self {
798        Part {
799            dom,
800            root,
801            children: HashMap::new(),
802            rank: HashMap::new(),
803            paragraphs: None,
804        }
805    }
806
807    /// The element `chain` ([`element_path`]) names under the root.
808    fn resolve(&mut self, chain: &str) -> Option<NodeId> {
809        let Part {
810            dom,
811            root,
812            children,
813            rank,
814            ..
815        } = self;
816        let mut node = *root;
817        for step in chain.split('/') {
818            let (name, index) = step.strip_suffix(']')?.split_once('[')?;
819            let index: usize = index.parse().ok()?;
820            let (namespace, local) = match name.split_once(':') {
821                Some((prefix, local)) => (well_known_namespace(prefix)?, local),
822                None => ("", name),
823            };
824            node = *named(dom, children, rank, node, namespace, local).get(index)?;
825        }
826        Some(node)
827    }
828
829    /// The paragraphs of `story`, this part's, in the order its paragraph
830    /// ids (`p3`, `header1.p2`) count them: the order `inspect` and the
831    /// audit number them in.
832    fn paragraphs(&mut self, story: &str) -> &[NodeId] {
833        let Part {
834            dom,
835            root,
836            paragraphs,
837            ..
838        } = self;
839        paragraphs.get_or_insert_with(|| {
840            if story == "body" {
841                dom.element(*root, &W::body())
842                    .map(|body| crate::inspect::body_paragraph_nodes(dom, body))
843                    .unwrap_or_default()
844            } else {
845                crate::inspect::story_paragraph_nodes(dom, *root)
846            }
847        })
848    }
849
850    /// The [`Place`] of `node`: what it sits in, read from its paragraph
851    /// (else its table, else itself), and the change around it.
852    fn around(&mut self, node: NodeId) -> Place {
853        let Part {
854            dom,
855            children,
856            rank,
857            ..
858        } = self;
859        let held: Vec<NodeId> = std::iter::once(node)
860            .chain(dom.ancestors(node, None))
861            .collect();
862        let anchor = [W::p(), W::tbl()]
863            .iter()
864            .find_map(|name| held.iter().copied().find(|&n| dom.name_is(n, name)));
865        let revision = held.iter().find_map(|&n| {
866            let id = dom.attribute(n, &W::id())?;
867            dom.attribute(n, &W::author())?;
868            Some(format!("{} {id}", dom.name(n)?.local_name()))
869        });
870        let (anchor, text) = match anchor {
871            Some(anchor) => (anchor, dom.value(anchor)),
872            None => (node, signature(dom, &held)),
873        };
874        let paragraph_id = if dom.name_is(anchor, &W::p()) {
875            dom.attribute(anchor, &W14::name("paraId"))
876                .map(str::to_string)
877        } else {
878            None
879        };
880        let (previous, next) = match (dom.parent(anchor), dom.name(anchor)) {
881            (Some(parent), Some(name)) => {
882                let siblings = named(
883                    dom,
884                    children,
885                    rank,
886                    parent,
887                    name.namespace_name(),
888                    name.local_name(),
889                );
890                let at = rank.get(&anchor).copied();
891                let text =
892                    |i: Option<usize>| i.and_then(|i| siblings.get(i)).map(|&n| dom.value(n));
893                (
894                    text(at.and_then(|at| at.checked_sub(1))),
895                    text(at.map(|at| at + 1)),
896                )
897            }
898            _ => (None, None),
899        };
900        Place {
901            text: Some(text),
902            paragraph_id,
903            revision,
904            previous,
905            next,
906        }
907    }
908}
909
910/// `parent`'s child elements named `local` in `namespace`, listed once
911/// into `children`, each one's place in the list into `rank`.
912fn named<'c>(
913    dom: &Dom,
914    children: &'c mut HashMap<(NodeId, String, String), Vec<NodeId>>,
915    rank: &mut HashMap<NodeId, usize>,
916    parent: NodeId,
917    namespace: &str,
918    local: &str,
919) -> &'c [NodeId] {
920    children
921        .entry((parent, namespace.to_string(), local.to_string()))
922        .or_insert_with(|| {
923            let list: Vec<NodeId> = dom
924                .elements(parent, None)
925                .into_iter()
926                .filter(|&e| {
927                    dom.name(e)
928                        .is_some_and(|n| n.local_name() == local && n.namespace_name() == namespace)
929                })
930                .collect();
931            for (i, &e) in list.iter().enumerate() {
932                rank.insert(e, i);
933            }
934            list
935        })
936}
937
938/// The text of `held[0]`, then the attributes of it and of each element
939/// holding it (`held[1..]`), but namespace declarations and the ones an
940/// edit renumbers (`rsid…`, `paraId`, `textId`, `id`).
941fn signature(dom: &Dom, held: &[NodeId]) -> String {
942    let mut out = held.first().map(|&n| dom.value(n)).unwrap_or_default();
943    for &n in held {
944        for (name, value) in dom.attributes(n) {
945            let local = name.local_name();
946            if dom.is_namespace_declaration(&name)
947                || local.starts_with("rsid")
948                || matches!(local, "paraId" | "textId" | "id")
949            {
950                continue;
951            }
952            out.push_str(&format!("\u{1f}{local}={value}"));
953        }
954    }
955    out
956}
957
958/// `message` with each `[N]` element index dropped and each paragraph or
959/// cell id ([`is_paragraph_id`]) spelled `p#`, so an inherited finding keeps
960/// its identity when an edit renumbers what it names in passing.
961fn normalised(message: &str) -> String {
962    let mut out = String::with_capacity(message.len());
963    let mut rest = message;
964    while let Some(start) = rest.find(|c: char| c.is_ascii_alphanumeric() || c == '[') {
965        out.push_str(&rest[..start]);
966        rest = &rest[start..];
967        if let Some(tail) = rest.strip_prefix('[') {
968            let digits = tail.bytes().take_while(u8::is_ascii_digit).count();
969            if digits > 0 && tail[digits..].starts_with(']') {
970                rest = &tail[digits + 1..];
971            } else {
972                out.push('[');
973                rest = tail;
974            }
975            continue;
976        }
977        let end = rest
978            .find(|c: char| !(c.is_ascii_alphanumeric() || c == '.'))
979            .unwrap_or(rest.len());
980        // A sentence's full stop is not part of the id before it.
981        let token = rest[..end].trim_end_matches('.');
982        if is_paragraph_id(token) {
983            out.push_str("p#");
984        } else {
985            out.push_str(token);
986        }
987        rest = &rest[token.len()..];
988    }
989    out.push_str(rest);
990    out
991}
992
993/// True for a paragraph or cell id `-p` takes (`p12`, `header1.p2`,
994/// `t0.row1.cell2`, `t0.row1.cell2.p1`): a position, which an edit
995/// renumbers. A story's bare name (`header1`) is no position, and a word
996/// that parses as one is not taken for an id.
997fn is_paragraph_id(token: &str) -> bool {
998    let last = token.rsplit('.').next().unwrap_or(token);
999    let numbered = |prefix: &str| {
1000        last.strip_prefix(prefix)
1001            .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
1002    };
1003    (numbered("p") || numbered("cell"))
1004        && matches!(
1005            crate::ids::parse_location(token),
1006            Ok(crate::ids::Location::Paragraph(_))
1007        )
1008}
1009
1010/// One name on the new markup (#1893): how many logical changes, and how
1011/// many comments, it signed.
1012#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1013pub struct AuthorMark {
1014    /// The signing name, as the document spells it (`<no author>` for
1015    /// markup that names none).
1016    pub name: String,
1017    /// Logical changes it signed, counted as `changes` lists them.
1018    pub changes: usize,
1019    /// Comments it signed.
1020    pub comments: usize,
1021}
1022
1023/// A baseline run's verdict (#1893): the last line of the report, `pass`
1024/// being what [`fails`] says of the new findings — the 0 against 2 exit.
1025#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1026pub struct Verdict {
1027    /// True when the new findings do not fail the run.
1028    pub pass: bool,
1029    /// The new findings.
1030    pub findings: usize,
1031    /// The distinct logical changes the findings name.
1032    pub changes: usize,
1033    /// The distinct comments the findings name.
1034    pub comments: usize,
1035    /// True when the authorship of the new markup was checked: the run
1036    /// had an author to check it against (#1893).
1037    pub authored: bool,
1038}
1039
1040/// A document's findings against those of the document it was made from
1041/// ([`baseline`]).
1042#[derive(Clone, Debug, Default, PartialEq, Eq)]
1043pub struct Baselined {
1044    /// The document's findings the baseline does not have: the edit's.
1045    pub new: Vec<Finding>,
1046    /// The document's findings the baseline already had.
1047    pub baseline: Vec<Finding>,
1048    /// The baseline's findings the document no longer has.
1049    pub resolved: Vec<Finding>,
1050    /// Who signed the markup the edit added over the baseline, counted per
1051    /// logical change as `changes` lists it and per comment, in
1052    /// first-appearance order (#1893): [`validate_baselined`] fills it
1053    /// with the markup `docx` gained over the baseline.
1054    pub authors: Vec<AuthorMark>,
1055    /// The `--author` the markup was checked against, when there is one;
1056    /// the text report's `none of it is signed` line reads it.
1057    pub author: Option<String>,
1058}
1059
1060impl Baselined {
1061    /// The run's verdict under `strict` (as [`fails`] reads the new
1062    /// findings): `pass` is the 0 exit. The counts are objects, not
1063    /// findings: the distinct logical changes and the distinct comments
1064    /// the findings name; a finding about neither counts as a finding
1065    /// only (#1893).
1066    #[must_use]
1067    pub fn verdict(&self, strict: bool) -> Verdict {
1068        let mut changes: HashSet<String> = HashSet::new();
1069        let mut comments: HashSet<String> = HashSet::new();
1070        for f in &self.new {
1071            match f.code.as_str() {
1072                "FOREIGN_AUTHOR" => changes.extend(change_of(&f.message)),
1073                "FOREIGN_COMMENT" => comments.extend(comment_of(&f.message)),
1074                _ => {}
1075            }
1076        }
1077        Verdict {
1078            pass: !fails(&self.new, strict),
1079            findings: self.new.len(),
1080            changes: changes.len(),
1081            comments: comments.len(),
1082            authored: self.author.is_some(),
1083        }
1084    }
1085}
1086
1087/// The logical change a `FOREIGN_AUTHOR` finding names, by its first
1088/// mark: `r10+11` and `r10` are one change (#1893).
1089fn change_of(message: &str) -> Option<String> {
1090    let id = if let Some(rest) = message
1091        .strip_suffix(FOREIGN_NEW)
1092        .or_else(|| message.strip_suffix(FOREIGN_ALTERED))
1093    {
1094        rest.trim_end().rsplit_once(" by ")?.0
1095    } else {
1096        let rest = message.strip_suffix(" in the original is gone")?;
1097        rest.rsplit_once("'s ")?.1
1098    };
1099    Some(
1100        crate::ids::parse_change_ids(id)
1101            .ok()
1102            .and_then(|ids| ids.first().map(crate::ids::ChangeId::short))
1103            .unwrap_or_else(|| id.to_string()),
1104    )
1105}
1106
1107/// The comment a `FOREIGN_COMMENT` finding names: `c3`, whatever else the
1108/// message says of it (#1893).
1109fn comment_of(message: &str) -> Option<String> {
1110    let rest = message.strip_prefix('c')?;
1111    let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
1112    (!digits.is_empty()).then(|| format!("c{digits}"))
1113}
1114
1115/// Splits `new` (the findings of an edited document) by those of `base`
1116/// (the document before the edits), matched by [`Finding::identity`]: each
1117/// baseline finding vouches for one finding of `new` with its identity, so
1118/// a second finding with the same identity is new, and a finding that
1119/// replaced another is new while the one it replaced is resolved, whatever
1120/// the counts. Each list keeps its input's order.
1121pub fn baseline(new: Vec<Finding>, base: Vec<Finding>) -> Baselined {
1122    let new_keys: Vec<FindingKey> = new.iter().map(Finding::identity).collect();
1123    let base_keys: Vec<FindingKey> = base.iter().map(Finding::identity).collect();
1124    baseline_keyed(new, &new_keys, base, &base_keys)
1125}
1126
1127/// [`baseline`] with each finding's key given, in step with its list:
1128/// [`identities`] reads them in the documents themselves. Two findings
1129/// match when their keys agree but for [`Place`] and they share a place,
1130/// tried strongest first: all of it, then the change they sit in, their
1131/// paragraph's id, their text with its neighbours, their text alone, and
1132/// last their neighbours (their paragraph rewritten). Each pass pairs the
1133/// findings left, in order, each with the earliest the baseline has left.
1134#[must_use]
1135pub fn baseline_keyed(
1136    new: Vec<Finding>,
1137    new_keys: &[FindingKey],
1138    base: Vec<Finding>,
1139    base_keys: &[FindingKey],
1140) -> Baselined {
1141    let mut paired = vec![false; new.len()];
1142    let mut matched = vec![false; base.len()];
1143    for pass in 0..PASSES {
1144        let mut open: HashMap<_, Vec<usize>> = HashMap::new();
1145        for (i, key) in base_keys.iter().enumerate().rev() {
1146            if !matched[i]
1147                && let Some(tier) = tier(pass, key)
1148            {
1149                open.entry(tier).or_default().push(i);
1150            }
1151        }
1152        for (j, key) in new_keys.iter().enumerate() {
1153            if !paired[j]
1154                && let Some(tier) = tier(pass, key)
1155                && let Some(i) = open.get_mut(&tier).and_then(Vec::pop)
1156            {
1157                paired[j] = true;
1158                matched[i] = true;
1159            }
1160        }
1161    }
1162    let mut out = Baselined::default();
1163    for (f, paired) in new.into_iter().zip(paired) {
1164        if paired {
1165            out.baseline.push(f);
1166        } else {
1167            out.new.push(f);
1168        }
1169    }
1170    out.resolved = base
1171        .into_iter()
1172        .zip(matched)
1173        .filter_map(|(f, matched)| (!matched).then_some(f))
1174        .collect();
1175    out
1176}
1177
1178/// How many passes [`baseline_keyed`] makes ([`tier`]).
1179const PASSES: usize = 6;
1180
1181/// What pass `pass` of [`baseline_keyed`] matches `key` by: the key but its
1182/// [`Place`], and the parts of the place the pass reads; `None` when `key`
1183/// lacks what the pass needs.
1184fn tier(pass: usize, key: &FindingKey) -> Option<([&str; 5], [Option<&str>; 5])> {
1185    let place = &key.place;
1186    let text = place.text.as_deref();
1187    let id = place.paragraph_id.as_deref();
1188    let change = place.revision.as_deref();
1189    let (previous, next) = (place.previous.as_deref(), place.next.as_deref());
1190    let read = match pass {
1191        // Nothing around it changed.
1192        0 => [text, id, change, previous, next],
1193        // The change it sits in.
1194        1 if change.is_some() => [None, None, change, None, None],
1195        // Its paragraph, by id.
1196        2 if id.is_some() => [None, id, None, None, None],
1197        // Its text, between the same neighbours.
1198        3 if text.is_some() => [text, None, None, previous, next],
1199        // Its text.
1200        4 if text.is_some() => [text, None, None, None, None],
1201        // Between the same neighbours, not both empty: its paragraph
1202        // rewritten.
1203        5 if previous.is_some() && next.is_some() && (previous != Some("") || next != Some("")) => {
1204            [None, None, None, previous, next]
1205        }
1206        _ => return None,
1207    };
1208    let kind = [
1209        key.code.as_str(),
1210        key.set.as_str(),
1211        key.part.as_str(),
1212        key.location.as_str(),
1213        key.message.as_str(),
1214    ];
1215    Some((kind, read))
1216}
1217
1218/// [`baseline`]'s split as `validate --baseline` prints it: the input's
1219/// resolved findings first (`resolved: N (in the input, not in this
1220/// file)` and their lines, when there are any — an agent reading the end
1221/// of the report must not stop on them, #1893), then `new: none` or
1222/// `new: N` and the new findings ([`findings_text`]'s lines), then
1223/// `already in the input: N (not yours)` (or `none`), then the author
1224/// summary (`markup_text`), and last the verdict (`verdict_text`).
1225/// The verdict states what the run checked: without an author, no
1226/// authorship was checked, and the line says so (#1893).
1227pub fn baselined_text(split: &Baselined, strict: bool) -> String {
1228    let count = |n: usize| {
1229        if n == 0 {
1230            "none".to_string()
1231        } else {
1232            n.to_string()
1233        }
1234    };
1235    let mut out = String::new();
1236    if !split.resolved.is_empty() {
1237        out.push_str(&format!(
1238            "resolved: {} (in the input, not in this file)\n",
1239            split.resolved.len()
1240        ));
1241        for f in &split.resolved {
1242            out.push_str(&finding_line(f));
1243        }
1244    }
1245    out.push_str(&format!("new: {}\n", count(split.new.len())));
1246    for f in &split.new {
1247        out.push_str(&finding_line(f));
1248    }
1249    out.push_str(&format!(
1250        "already in the input: {}{}\n",
1251        count(split.baseline.len()),
1252        if split.baseline.is_empty() {
1253            ""
1254        } else {
1255            " (not yours)"
1256        }
1257    ));
1258    out.push_str(&markup_text(split));
1259    out.push_str(&verdict_text(&split.verdict(strict)));
1260    out
1261}
1262
1263/// The author-summary lines of `validate --baseline` (#1893):
1264/// `new markup by:` with one entry per signing name (counts per logical
1265/// change as `changes` lists them, comments separately), then, when more
1266/// than one name signs, the one-`-a` warning, and when none of the names
1267/// is `--author`, the line that says so. The summary needs no expected
1268/// author: it names who signed, not who should have (#1893). Nothing when
1269/// the edit signed no new markup.
1270fn markup_text(split: &Baselined) -> String {
1271    if split.authors.is_empty() {
1272        return String::new();
1273    }
1274    let entries: Vec<String> = split
1275        .authors
1276        .iter()
1277        .map(|m| {
1278            let mut counts = Vec::new();
1279            if m.changes > 0 || m.comments == 0 {
1280                counts.push(plural(m.changes, "change", "changes"));
1281            }
1282            if m.comments > 0 {
1283                counts.push(plural(m.comments, "comment", "comments"));
1284            }
1285            format!("{} ({})", m.name, counts.join(", "))
1286        })
1287        .collect();
1288    let mut out = format!("new markup by: {}\n", entries.join(", "));
1289    if split.authors.len() > 1 {
1290        out.push_str(&format!(
1291            "{} sign the new markup; one session signs with one -a\n",
1292            plural(split.authors.len(), "name", "names")
1293        ));
1294    }
1295    if split
1296        .author
1297        .as_deref()
1298        .is_some_and(|author| !split.authors.iter().any(|m| m.name == author))
1299    {
1300        out.push_str(&format!(
1301            "none of it is signed {:?}\n",
1302            split.author.as_deref().unwrap_or_default()
1303        ));
1304    }
1305    out
1306}
1307
1308/// `n` with its noun, singular or plural: `1 change`, `2 findings`.
1309fn plural(n: usize, one: &str, many: &str) -> String {
1310    format!("{n} {}", if n == 1 { one } else { many })
1311}
1312
1313/// The verdict line, the report's last (#1893): PASS, or FAIL with the
1314/// findings counted on changes and comments.
1315fn verdict_text(verdict: &Verdict) -> String {
1316    if verdict.pass {
1317        if verdict.authored {
1318            "PASS: every difference from the baseline is yours and tracked\n".to_string()
1319        } else if verdict.findings == 0 {
1320            "PASS: no new finding (authorship not checked: pass --author NAME)\n".to_string()
1321        } else {
1322            format!(
1323                "PASS: {} did not fail the run (authorship not checked: pass --author NAME)\n",
1324                plural(verdict.findings, "finding", "findings")
1325            )
1326        }
1327    } else {
1328        format!(
1329            "FAIL: {} ({}, {}); not ready to deliver\n",
1330            plural(verdict.findings, "finding", "findings"),
1331            plural(verdict.changes, "change", "changes"),
1332            plural(verdict.comments, "comment", "comments")
1333        )
1334    }
1335}
1336
1337/// [`baseline`]'s split as JSON Lines: each finding of the document, new
1338/// ones first, as its JSON object with `"status": "new"` or `"baseline"`,
1339/// then one `{"resolved": [...]}` line with the baseline's findings the
1340/// document no longer has (an empty array when there are none), and last
1341/// one `{"authors": [...], "verdict": {...}}` line (#1893).
1342///
1343/// # Errors
1344///
1345/// A finding that does not serialise.
1346pub fn baselined_json(split: &Baselined, strict: bool) -> Result<String, serde_json::Error> {
1347    #[derive(Serialize)]
1348    struct Marked<'a> {
1349        #[serde(flatten)]
1350        finding: &'a Finding,
1351        status: &'static str,
1352    }
1353    /// The last line: who signed the new markup and how the run ended.
1354    #[derive(Serialize)]
1355    struct Summary<'a> {
1356        authors: &'a [AuthorMark],
1357        verdict: Verdict,
1358    }
1359    let mut out = String::new();
1360    for (findings, status) in [(&split.new, "new"), (&split.baseline, "baseline")] {
1361        for finding in findings {
1362            out.push_str(&serde_json::to_string(&Marked { finding, status })?);
1363            out.push('\n');
1364        }
1365    }
1366    out.push_str(&serde_json::to_string(
1367        &serde_json::json!({ "resolved": split.resolved }),
1368    )?);
1369    out.push('\n');
1370    out.push_str(&serde_json::to_string(&Summary {
1371        authors: &split.authors,
1372        verdict: split.verdict(strict),
1373    })?);
1374    out.push('\n');
1375    Ok(out)
1376}
1377
1378/// The one stderr line `read`, `changes` and `comments` give an input with
1379/// validity findings: `input has 2 validity warnings; jubarte validate FILE
1380/// lists them` (an `error` counts as an error, `info` not at all), or
1381/// `None` when there is nothing to say. `file` is the path as given, quoted
1382/// for a shell when it needs to be ([`crate::util::shell_word`]).
1383pub fn input_notice(findings: &[Finding], file: &str) -> Option<String> {
1384    input_notice_of(&input_validity(findings, file))
1385}
1386
1387/// [`input_notice`] from counts already taken, for a read that also
1388/// reports them in its JSON (`read -o FILE.json`).
1389pub fn input_notice_of(validity: &InputValidity) -> Option<String> {
1390    let InputValidity {
1391        errors,
1392        warnings,
1393        next,
1394    } = validity;
1395    let (errors, warnings) = (*errors, *warnings);
1396    let next = next.as_deref()?;
1397    let spell = |n: usize, noun: &str| format!("{n} {noun}{}", if n == 1 { "" } else { "s" });
1398    let what = match (errors, warnings) {
1399        (0, 0) => return None,
1400        (0, w) => spell(w, "validity warning"),
1401        (e, 0) => spell(e, "validity error"),
1402        (e, w) => format!("{} and {}", spell(e, "validity error"), spell(w, "warning")),
1403    };
1404    let them = if errors + warnings == 1 { "it" } else { "them" };
1405    Some(format!("input has {what}; {next} lists {them}"))
1406}
1407
1408/// The input's own validity findings as the JSON reads report them
1409/// (#1309): `read --json` in its snapshot's `summary`, `changes --json` and
1410/// `comments --json` in a JSON stderr status ([`input_validity_line`]),
1411/// suppressed by `--quiet` (#1925).
1412#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1413pub struct InputValidity {
1414    /// Findings of severity `error`.
1415    pub errors: usize,
1416    /// Findings of severity `warning`; `info` is not counted.
1417    pub warnings: usize,
1418    /// The command that lists them (`jubarte validate FILE`), when there
1419    /// are any.
1420    #[serde(default, skip_serializing_if = "Option::is_none")]
1421    pub next: Option<String>,
1422}
1423
1424/// What [`InputValidity`] says of `findings`; `file` is the path as given,
1425/// quoted for a shell when it needs to be ([`crate::util::shell_word`]).
1426#[must_use]
1427pub fn input_validity(findings: &[Finding], file: &str) -> InputValidity {
1428    let count = |severity: &str| findings.iter().filter(|f| f.severity == severity).count();
1429    let (errors, warnings) = (count("error"), count("warning"));
1430    InputValidity {
1431        errors,
1432        warnings,
1433        next: (errors + warnings > 0)
1434            .then(|| format!("jubarte validate {}", crate::util::shell_word(file))),
1435    }
1436}
1437
1438/// [`input_validity`] of the package `docx` read from `file`, as the CLI
1439/// and the bindings report it: a package that cannot be validated has no
1440/// findings to count.
1441#[must_use]
1442pub fn input_validity_of(docx: &[u8], file: &str) -> InputValidity {
1443    input_validity(&validate(docx).unwrap_or_default(), file)
1444}
1445
1446/// The status `changes --json` and `comments --json` print on stderr unless quiet:
1447/// `{"input_validity":{"errors":0,"warnings":2,"next":"jubarte validate FILE"}}`,
1448/// its keys in that order.
1449///
1450/// # Errors
1451/// When the validity does not serialize.
1452pub fn input_validity_line(validity: &InputValidity) -> Result<String, serde_json::Error> {
1453    Ok(format!(
1454        r#"{{"input_validity":{}}}"#,
1455        serde_json::to_string(validity)?
1456    ))
1457}
1458
1459impl From<crate::audit::AuditFinding> for Finding {
1460    /// The audit's finding in the shared shape: its part is the story's
1461    /// part for a paragraph id (`p3` → `word/document.xml`), else the
1462    /// location itself (a part name); it is never Word-fatal or repairable.
1463    fn from(f: crate::audit::AuditFinding) -> Self {
1464        let part = if crate::ids::paragraph_place(&f.location).is_some() {
1465            story_part(&f.location)
1466        } else {
1467            f.location.clone()
1468        };
1469        let r#ref = f.location.clone();
1470        Finding {
1471            code: f.code,
1472            set: f.rule_set,
1473            severity: f.severity,
1474            part,
1475            location: f.location,
1476            r#ref,
1477            message: f.message,
1478            word_fatal: false,
1479            repairable: false,
1480        }
1481    }
1482}
1483
1484/// Findings sorted by part, location, code and message (the same order every
1485/// run); an empty vector is a pass.
1486///
1487/// # Errors
1488///
1489/// [`ValidateError`] when the package is refused by admission or cannot be
1490/// read; a problem Word would have with a readable package is a finding.
1491pub fn validate(docx: &[u8]) -> Result<Vec<Finding>, ValidateError> {
1492    crate::admission::admit(docx, InputLimits::default())?;
1493    let pkg = PartFs::open(docx)?;
1494    let mut out = ring1(&pkg);
1495    let triage = crate::debug::findings(docx).map_err(ValidateError::Package)?;
1496    out.extend(
1497        triage
1498            .into_iter()
1499            .filter(|f| !RING1_CODES.contains(&f.code.as_str())),
1500    );
1501    // A total order: findings at one location (comment metadata gathered
1502    // from hash sets) would otherwise print in a different order each run.
1503    out.sort_by(|a, b| {
1504        (&a.part, &a.location, &a.code, &a.message).cmp(&(
1505            &b.part,
1506            &b.location,
1507            &b.code,
1508            &b.message,
1509        ))
1510    });
1511    Ok(out)
1512}
1513
1514/// The Ring-1 invariants alone, on an opened package: no admission, no
1515/// triage checks. [`validate`] is the full check.
1516pub fn ring1(pkg: &PartFs) -> Vec<Finding> {
1517    let mut out = Vec::new();
1518    check_content_types_and_xml(pkg, &mut out);
1519    check_relationship_integrity(pkg, &mut out);
1520    check_picture_bullets(pkg, &mut out);
1521    check_revision_and_drawing_ids(pkg, &mut out);
1522    check_doc_pr_ids_across_stories(pkg, &mut out);
1523    check_para_text_id_bounds(pkg, &mut out);
1524    check_del_text_under_del(pkg, &mut out);
1525    check_deleted_text_has_deletion(pkg, &mut out);
1526    check_bookmarks_outside_single_value_controls(pkg, &mut out);
1527    check_comment_graph(pkg, &mut out);
1528    check_namespace_qname_contexts(pkg, &mut out);
1529    check_runs_inside_paragraphs(pkg, &mut out);
1530    check_paragraph_ruby(pkg, &mut out);
1531    check_style_names(pkg, &mut out);
1532    check_style_change_carriers(pkg, &mut out);
1533    check_nested_text_boxes(pkg, &mut out);
1534    check_nested_ppr(pkg, &mut out);
1535    check_move_range_counts(pkg, &mut out);
1536    check_data_bindings_have_stores(pkg, &mut out);
1537    check_cell_final_marks(pkg, &mut out);
1538    check_deleted_section_page_fields(pkg, &mut out);
1539    check_inserted_text_before_deleted_tables(pkg, &mut out);
1540    check_non_finite_measures(pkg, &mut out);
1541    check_duplicate_num_durable_ids(pkg, &mut out);
1542    out
1543}
1544
1545/// A deleted section break that references a header or footer whose
1546/// closing paragraph holds a PAGE or NUMPAGES field. Word's own Compare
1547/// writes it when the revision drops the original's sections and
1548/// page-number footer. Word 16.115 crashed opening 9 of the 11 such
1549/// redlines in the 0.14.0 release sample, so it is a lead (#1833). Whether
1550/// Word crashes depends on the layout, not on the story's marks: the
1551/// story's text live, deleted, or deleted with every mark crashed alike
1552/// (s176, s472), and so did a live section referencing the story as well.
1553/// Word opened each of them once no deleted break referenced the story. A
1554/// story that ends in a content control has no closing paragraph here:
1555/// Word opened both such footers (25e6d4b508, 7c98e8f2b6), the field in
1556/// the control's last paragraph.
1557fn check_deleted_section_page_fields(pkg: &PartFs, out: &mut Vec<Finding>) {
1558    let Some(main) = main_part(pkg) else {
1559        return;
1560    };
1561    if !pkg
1562        .part_bytes(&main)
1563        .is_some_and(|bytes| bytes.windows(9).any(|w| w == b"Reference"))
1564    {
1565        return;
1566    }
1567    let Some((dom, root)) = parse_part(pkg, &main) else {
1568        return;
1569    };
1570    let sections = crate::document_comparer::section_story_parts(&dom, root, pkg, &main);
1571    let mut seen = HashSet::new();
1572    for part in sections
1573        .iter()
1574        .filter(|(deleted, _)| *deleted)
1575        .flat_map(|(_, parts)| parts)
1576    {
1577        if !seen.insert(part) {
1578            continue;
1579        }
1580        let Some((dom, root)) = parse_part(pkg, part) else {
1581            continue;
1582        };
1583        let Some(last) = closing_paragraph(&dom, root).filter(|&p| holds_page_field(&dom, p))
1584        else {
1585            continue;
1586        };
1587        out.push(Finding::new(
1588            "DELETED_SECTION_PAGE_FIELD",
1589            part,
1590            element_path(&dom, last),
1591            "a deleted section break references this story, whose closing paragraph holds a PAGE or NUMPAGES field; Word 16.115 crashed opening such redlines whatever the story's marks (#1833). Word opened them once no deleted section break referenced the story".to_string(),
1592        ));
1593    }
1594}
1595
1596/// A body paragraph whose mark is deleted while it keeps inserted words,
1597/// then a table every row of which is deleted, then the paragraph Accept
1598/// All joins those words to ([`inserted_text_before_deleted_tables`]).
1599/// Word's own Compare writes it. Word 16.115 crashed opening 6 of the 16
1600/// release-sample redlines (0.14.0) whose paragraph sat right before the
1601/// table, its table cache corrupt at the deleted row's end, and opened the
1602/// other 10: a lead (#1851). It opened w06, w10, w14 and w17 once the
1603/// words started the paragraph they join (fix23 probe33).
1604fn check_inserted_text_before_deleted_tables(pkg: &PartFs, out: &mut Vec<Finding>) {
1605    let Some(main) = main_part(pkg) else {
1606        return;
1607    };
1608    // A deleted row's `w:trPr`, whatever its prefix.
1609    if !pkg
1610        .part_bytes(&main)
1611        .is_some_and(|bytes| bytes.windows(5).any(|w| w == b"trPr>"))
1612    {
1613        return;
1614    }
1615    let Some((dom, root)) = parse_part(pkg, &main) else {
1616        return;
1617    };
1618    let Some(body) = dom.element(root, &W::body()) else {
1619        return;
1620    };
1621    for (paragraph, _) in inserted_text_before_deleted_tables(&dom, body) {
1622        out.push(Finding::new(
1623            "INSERTED_TEXT_BEFORE_DELETED_TABLE",
1624            &main,
1625            element_path(&dom, paragraph),
1626            "this paragraph's mark is deleted while it keeps inserted words, and a table every row of which is deleted follows it: Accept All joins those words to the paragraph after the table. Word 16.115 crashed opening such redlines (#1851); it opened them once the words started the paragraph they join".to_string(),
1627        ));
1628    }
1629}
1630
1631#[doc(hidden)]
1632pub use crate::validate_dom::container_blocks;
1633pub(crate) use crate::validate_dom::holds_page_field;
1634pub(crate) use crate::validate_dom::{
1635    closing_paragraph, has_unique_revision_id, inserted_text_before_deleted_tables,
1636    uncovered_final_marks,
1637};
1638
1639/// A table cell's final paragraph mark inserted or deleted while its row
1640/// is not: Word opens the file, but Accept All or Reject All never returns
1641/// (#1669, Word 16, 2026-10-23). Word's Compare puts such a revision on the
1642/// mark before, and revises every mark of a row it inserts or deletes with
1643/// the row (`w:trPr/w:ins`, `w:trPr/w:del`). A nested table's cells in a
1644/// revised outer row pass whether or not their own rows repeat the
1645/// revision, as Open-Xml-PowerTools writes them: Word resolves those
1646/// (2026-10-23). The body's final mark is not flagged: Word resolves it.
1647/// Only the stories Accept and Reject All walk are read, the parts the
1648/// comparer's settle pass sweeps: a glossary's building blocks or a
1649/// custom XML data item is no story (#1680).
1650fn check_cell_final_marks(pkg: &PartFs, out: &mut Vec<Finding>) {
1651    for (part, styles) in crate::revision_processor::revision_bearing_parts(pkg) {
1652        if styles {
1653            continue;
1654        }
1655        // A cell's start tag, whatever its prefix (none included) and
1656        // whatever follows its name: `<w:tc>`, `<tc `, `<w:tc\n>`.
1657        if !pkg.part_bytes(&part).is_some_and(|bytes| {
1658            bytes.windows(4).any(|w| {
1659                matches!(w[0], b'<' | b':')
1660                    && &w[1..3] == b"tc"
1661                    && matches!(w[3], b'>' | b'/' | b' ' | b'\t' | b'\r' | b'\n')
1662            })
1663        }) {
1664            continue;
1665        }
1666        let Some((dom, root)) = parse_part(pkg, &part) else {
1667            continue;
1668        };
1669        for cell in dom.descendants(root, Some(&W::tc())) {
1670            for (last, kind) in uncovered_final_marks(&dom, cell) {
1671                out.push(Finding::new(
1672                    "CELL_FINAL_MARK_REVISION",
1673                    &part,
1674                    element_path(&dom, last),
1675                    format!("a table cell's final paragraph mark carries w:{kind} while its row does not; Word opens it, but Accept All or Reject All never returns (#1669). Word puts the revision on the mark before"),
1676                ));
1677            }
1678        }
1679    }
1680}
1681
1682fn check_data_bindings_have_stores(pkg: &PartFs, out: &mut Vec<Finding>) {
1683    use crate::data_stores::{built_in, stores};
1684    let Some(main) = main_part(pkg) else {
1685        return;
1686    };
1687    let mut held: Option<Vec<String>> = None;
1688    for part in xml_parts(pkg) {
1689        if part.starts_with("customXml/")
1690            || !pkg
1691                .part_bytes(&part)
1692                .is_some_and(|bytes| bytes.windows(11).any(|w| w == b"dataBinding"))
1693        {
1694            continue;
1695        }
1696        let Some((dom, root)) = parse_part(pkg, &part) else {
1697            continue;
1698        };
1699        for binding in dom.descendants(root, Some(&W::name("dataBinding"))) {
1700            let Some(store) = dom.attribute(binding, &W::name("storeItemID")) else {
1701                continue;
1702            };
1703            if built_in(store)
1704                || held
1705                    .get_or_insert_with(|| stores(pkg, &main))
1706                    .contains(&store.to_ascii_uppercase())
1707            {
1708                continue;
1709            }
1710            out.push(Finding::new(
1711                "DATA_BINDING_WITHOUT_STORE",
1712                &part,
1713                element_path(&dom, binding),
1714                format!("{store}: no custom XML store the main part reaches holds it; Word shows the bound control empty (#1427)"),
1715            ));
1716        }
1717    }
1718}
1719
1720/// Word opens unequal per-name move ranges cleanly, but Reject All can
1721/// restore the destination over only one source range and duplicate text.
1722/// A start whose `w:name` is missing or empty cannot be paired. The
1723/// attribute is schema-required; Word's reaction is unverified, so that
1724/// finding is a warning lead (#1939).
1725fn check_move_range_counts(pkg: &PartFs, out: &mut Vec<Finding>) {
1726    for part in xml_parts(pkg) {
1727        let Some((dom, root)) = parse_part(pkg, &part) else {
1728            continue;
1729        };
1730        let mut moves = std::collections::BTreeMap::new();
1731        for (side, source) in [("moveFromRangeStart", true), ("moveToRangeStart", false)] {
1732            for start in dom.descendants(root, Some(&W::name(side))) {
1733                let Some(name) = dom
1734                    .attribute(start, &W::name("name"))
1735                    .filter(|n| !n.is_empty())
1736                else {
1737                    out.push(Finding::new(
1738                        "MOVE_RANGE_NAME_MISSING",
1739                        &part,
1740                        element_path(&dom, start),
1741                        format!(
1742                            "w:{side} has no w:name; the attribute is required to pair the range (#1939)"
1743                        ),
1744                    ));
1745                    continue;
1746                };
1747                let counts = moves
1748                    .entry(name.to_string())
1749                    .or_insert((0_usize, 0_usize, start));
1750                if source {
1751                    counts.0 += 1;
1752                } else {
1753                    counts.1 += 1;
1754                }
1755            }
1756        }
1757        for (name, (source, destination, start)) in moves {
1758            if source != destination {
1759                out.push(Finding::new(
1760                    "MOVE_RANGE_COUNT_MISMATCH",
1761                    &part,
1762                    element_path(&dom, start),
1763                    format!("{name}: {source} source ranges, {destination} destination ranges; Word opens it but Reject All can duplicate moved text (#1214)"),
1764                ));
1765            }
1766        }
1767    }
1768}
1769
1770/// A `w:pPr` inside a `w:pPr`: `CT_PPr`'s children are `CT_PPrBase`'s, then
1771/// `w:rPr`, `w:sectPr` and `w:pPrChange`, so it takes none of their own (the
1772/// previous properties of a `w:pPrChange` sit one level down, under the
1773/// change, and are Word's own shape). `tools/validate-docx` refuses the part
1774/// with `Sch_InvalidElementContentExpectingComplex`, so it is OOXML-invalid
1775/// whatever Word does with it; no Word probe is recorded, so it is a lead
1776/// and not Word-fatal (#1595 review).
1777fn check_nested_ppr(pkg: &PartFs, out: &mut Vec<Finding>) {
1778    for part in xml_parts(pkg) {
1779        let Some((dom, root)) = parse_part(pkg, &part) else {
1780            continue;
1781        };
1782        for ppr in dom.descendants(root, Some(&W::p_pr())) {
1783            for inner in dom.elements(ppr, Some(&W::p_pr())) {
1784                out.push(Finding::new(
1785                    "NESTED_PPR",
1786                    &part,
1787                    element_path(&dom, inner),
1788                    format!("a w:pPr sits inside another ({})", element_path(&dom, ppr)),
1789                ));
1790            }
1791        }
1792    }
1793}
1794
1795/// Word crashes or refuses a box in another box's readable content, even
1796/// though OpenXmlValidator passes it. The 2026-10-18 A–H probes (#1132)
1797/// establish that a nest only in an ignored MC Fallback is harmless.
1798fn check_nested_text_boxes(pkg: &PartFs, out: &mut Vec<Finding>) {
1799    let dml_box = XName::get(
1800        "txbx",
1801        "http://schemas.microsoft.com/office/word/2010/wordprocessingShape",
1802    );
1803    let vml_box = VML::name("textbox");
1804    for part in nested_text_box_parts(pkg) {
1805        let Some((dom, root)) = parse_part(pkg, &part) else {
1806            continue;
1807        };
1808        for node in dom.descendants(root, None) {
1809            if !dom
1810                .name(node)
1811                .is_some_and(|name| name == dml_box || name == vml_box)
1812            {
1813                continue;
1814            }
1815            let ancestors = dom.ancestors(node, None);
1816            if crate::comparer::finalize::in_unselected_alternate(&dom, node) {
1817                continue;
1818            }
1819            if let Some(&outer) = ancestors
1820                .iter()
1821                .find(|&&a| dom.name(a).is_some_and(|n| n == W::txbx_content()))
1822            {
1823                out.push(Finding::new(
1824                    "NESTED_TEXT_BOX",
1825                    &part,
1826                    element_path(&dom, node),
1827                    format!(
1828                        "text box {} holds another text box ({}); Word cannot open this document",
1829                        text_box_name(&dom, outer),
1830                        text_box_name(&dom, node)
1831                    ),
1832                ));
1833            }
1834        }
1835    }
1836}
1837
1838/// Prefer the shape's own name, with its stable element path as a fallback.
1839fn text_box_name(dom: &Dom, node: NodeId) -> String {
1840    for ancestor in dom.ancestors(node, None) {
1841        if dom.name(ancestor).is_some_and(|n| n == W::drawing()) {
1842            if let Some(name) = dom
1843                .descendants(ancestor, Some(&WP::doc_pr()))
1844                .into_iter()
1845                .find_map(|id| dom.attribute(id, &XName::get("name", "")))
1846                .filter(|name| !name.is_empty())
1847            {
1848                return name.to_string();
1849            }
1850        } else if dom.name(ancestor).is_some_and(|n| n == VML::shape())
1851            && let Some(name) = dom.attribute(ancestor, &XName::get("id", ""))
1852            && !name.is_empty()
1853        {
1854            return name.to_string();
1855        }
1856    }
1857    element_path(dom, node)
1858}
1859
1860/// Parts whose text Word renders as a story: the main document, a header,
1861/// footer, footnote, endnote or comment part under its usual name, and any
1862/// part the main document relates as one of those. Custom XML is not one.
1863fn nested_text_box_parts(pkg: &PartFs) -> Vec<String> {
1864    let mut out: Vec<String> = xml_parts(pkg)
1865        .into_iter()
1866        .filter(|name| conventional_story(name))
1867        .collect();
1868    let main = pkg.main_document_part().or_else(|| {
1869        pkg.parts()
1870            .into_iter()
1871            .find(|name| name.eq_ignore_ascii_case("word/document.xml"))
1872    });
1873    let Some(main) = main else {
1874        return out;
1875    };
1876    if !out.iter().any(|have| have.eq_ignore_ascii_case(&main)) {
1877        out.push(main.clone());
1878    }
1879    let Some(rels) = pkg.read_rels_for(&main) else {
1880        return out;
1881    };
1882    for rel in &rels.items {
1883        if rel.target_mode.as_deref() == Some("External") {
1884            continue;
1885        }
1886        let story = ["/header", "/footer", "/footnotes", "/endnotes", "/comments"]
1887            .iter()
1888            .any(|kind| rel.rel_type.ends_with(kind));
1889        if !story {
1890            continue;
1891        }
1892        let part = pkg.resolve_rel_target(&main, &rel.target);
1893        if !out.iter().any(|have| have.eq_ignore_ascii_case(&part)) {
1894            out.push(part);
1895        }
1896    }
1897    out
1898}
1899
1900/// `word/document.xml`, the note and comment parts, and `word/headerN.xml`
1901/// / `word/footerN.xml`.
1902fn conventional_story(name: &str) -> bool {
1903    let name = name.trim_start_matches('/');
1904    if name.eq_ignore_ascii_case("word/document.xml")
1905        || name.eq_ignore_ascii_case("word/footnotes.xml")
1906        || name.eq_ignore_ascii_case("word/endnotes.xml")
1907        || name.eq_ignore_ascii_case("word/comments.xml")
1908    {
1909        return true;
1910    }
1911    let Some((dir, file)) = name.rsplit_once('/') else {
1912        return false;
1913    };
1914    if !dir.eq_ignore_ascii_case("word") {
1915        return false;
1916    }
1917    let stem = file.split('.').next().unwrap_or(file);
1918    numbered_story(stem, "header") || numbered_story(stem, "footer")
1919}
1920
1921/// `header`, `header1`, `footer2`: the kind, or the kind plus digits.
1922/// Compared byte-wise, without lowering a copy of every part's stem.
1923fn numbered_story(stem: &str, kind: &str) -> bool {
1924    let (stem, kind) = (stem.as_bytes(), kind.as_bytes());
1925    stem.len() >= kind.len() && {
1926        let (prefix, rest) = stem.split_at(kind.len());
1927        prefix.eq_ignore_ascii_case(kind) && rest.iter().all(u8::is_ascii_digit)
1928    }
1929}
1930
1931#[cfg(test)]
1932mod numbered_story_tests {
1933    #[test]
1934    fn a_story_stem_is_its_kind_with_digits() {
1935        for (stem, kind, expected) in [
1936            ("header", "header", true),
1937            ("Header12", "header", true),
1938            ("FOOTER2", "footer", true),
1939            ("header1a", "header", false),
1940            ("head", "header", false),
1941            ("headér1", "header", false),
1942            ("footer", "header", false),
1943        ] {
1944            assert_eq!(super::numbered_story(stem, kind), expected, "{stem} {kind}");
1945        }
1946    }
1947}
1948
1949/// A style's `w:name` holds no comma: the schema's pattern is `[^,]*`
1950/// (Word reads a comma there as the start of an alias list), while its
1951/// `w:styleId` may hold one. The OOXML validator refuses the part; Word
1952/// opens it (`List,Para`, probed 2026-10-15), so it is no Word-fatal.
1953fn check_style_names(pkg: &PartFs, out: &mut Vec<Finding>) {
1954    for part in xml_parts(pkg) {
1955        let Some((dom, root)) = parse_part(pkg, &part) else {
1956            continue;
1957        };
1958        if dom.name(root).is_none_or(|n| n.local_name() != "styles") {
1959            continue;
1960        }
1961        for name in dom.descendants(root, Some(&W::name("name"))) {
1962            let in_style = dom
1963                .parent(name)
1964                .and_then(|p| dom.name(p))
1965                .is_some_and(|p| p.local_name() == "style");
1966            if let Some(value) = dom.attribute(name, &W::val())
1967                && in_style
1968                && value.contains(',')
1969            {
1970                out.push(Finding::new(
1971                    "STYLE_NAME_COMMA",
1972                    &part,
1973                    element_path(&dom, name),
1974                    format!("style name '{value}' holds a comma, which w:name forbids"),
1975                ));
1976            }
1977        }
1978    }
1979}
1980
1981/// Two or more same-kind change carriers under one style property, or a
1982/// change carrier in the document defaults. The schema allows one
1983/// `w:pPrChange` in `w:pPr` and one `w:rPrChange` in `w:rPr`, and the run
1984/// defaults' `w:rPr` has no change child. Word opens both shapes, so neither
1985/// finding is Word-fatal, and a repair would drop revision data.
1986fn check_style_change_carriers(pkg: &PartFs, out: &mut Vec<Finding>) {
1987    for part in xml_parts(pkg) {
1988        let Some((dom, root)) = parse_part(pkg, &part) else {
1989            continue;
1990        };
1991        if dom
1992            .name(root)
1993            .is_none_or(|name| name.local_name() != "styles")
1994        {
1995            continue;
1996        }
1997        for (holder_name, change_name) in [("pPr", "pPrChange"), ("rPr", "rPrChange")] {
1998            for holder in dom.descendants(root, Some(&W::name(holder_name))) {
1999                let count = dom.elements(holder, Some(&W::name(change_name))).len();
2000                if count < 2 {
2001                    continue;
2002                }
2003                let style = style_id_of(&dom, holder);
2004                out.push(Finding::new(
2005                    "STYLE_CHANGE_SIBLINGS",
2006                    &part,
2007                    element_path(&dom, holder),
2008                    format!(
2009                        "style '{style}' has {count} {change_name} carriers under one {holder_name}"
2010                    ),
2011                ));
2012            }
2013        }
2014        for defaults in dom.elements(root, Some(&W::name("docDefaults"))) {
2015            for run_default in dom.elements(defaults, Some(&W::name("rPrDefault"))) {
2016                for run in dom.elements(run_default, Some(&W::name("rPr"))) {
2017                    if dom.elements(run, Some(&W::name("rPrChange"))).is_empty() {
2018                        continue;
2019                    }
2020                    out.push(Finding::new(
2021                        "DOC_DEFAULTS_CHANGE",
2022                        &part,
2023                        element_path(&dom, run),
2024                        "document defaults have a run-property change, which w:rPrDefault's w:rPr does not allow",
2025                    ));
2026                }
2027            }
2028        }
2029    }
2030}
2031
2032/// The `w:styleId` of the style that contains `node`, when it has one.
2033fn style_id_of(dom: &Dom, node: NodeId) -> String {
2034    let mut current = Some(node);
2035    while let Some(at) = current {
2036        if dom
2037            .name(at)
2038            .is_some_and(|name| name.local_name() == "style")
2039        {
2040            return dom
2041                .attribute(at, &W::name("styleId"))
2042                .unwrap_or("")
2043                .to_string();
2044        }
2045        current = dom.parent(at);
2046    }
2047    String::new()
2048}
2049
2050/// A run outside any paragraph: Word loads the document empty. Probed
2051/// 2026-10-10 with a comment's reference run straight in `w:body`, in a
2052/// `w:tc`, and in a body-level `w:ins`, `w:del`, `w:moveTo`, block
2053/// `w:sdtContent` or block `w:customXml`; and with a run straight under a
2054/// part's root (`w:document`, `w:comments`, `w:footnotes`) or a footnote.
2055fn check_runs_inside_paragraphs(pkg: &PartFs, out: &mut Vec<Finding>) {
2056    // Story and cell containers: a run reaching one before any paragraph is
2057    // outside a paragraph, whatever wraps it on the way.
2058    const BLOCKS: [&str; 9] = [
2059        "body",
2060        "tc",
2061        "hdr",
2062        "ftr",
2063        "footnote",
2064        "endnote",
2065        "comment",
2066        "txbxContent",
2067        "docPartBody",
2068    ];
2069    for name in xml_parts(pkg) {
2070        let Some((dom, root)) = parse_part(pkg, &name) else {
2071            continue;
2072        };
2073        for run in dom.descendants(root, Some(&W::r())) {
2074            let mut up = dom.parent(run);
2075            let outside = loop {
2076                let Some(node) = up else { break true };
2077                if dom.name_is(node, &W::p()) {
2078                    break false;
2079                }
2080                if BLOCKS
2081                    .iter()
2082                    .any(|block| dom.name_is(node, &W::name(block)))
2083                {
2084                    break true;
2085                }
2086                up = dom.parent(node);
2087            };
2088            if outside {
2089                out.push(Finding::new(
2090                    "RUN_OUTSIDE_PARAGRAPH",
2091                    &name,
2092                    element_path(&dom, run),
2093                    format!("a run outside any paragraph in '{name}'"),
2094                ));
2095            }
2096        }
2097    }
2098}
2099
2100/// OpenXmlValidator (Office 2019) rejects `w:p > w:ruby`, while the same
2101/// ruby inside `w:r` passes. Word opening and repair behavior are unverified;
2102/// report the schema error without claiming Word-fatal or choosing a repair.
2103fn check_paragraph_ruby(pkg: &PartFs, out: &mut Vec<Finding>) {
2104    for name in xml_parts(pkg) {
2105        let Some((dom, root)) = parse_part(pkg, &name) else {
2106            continue;
2107        };
2108        for ruby in dom.descendants(root, Some(&W::name("ruby"))) {
2109            if dom
2110                .parent(ruby)
2111                .is_some_and(|parent| dom.name_is(parent, &W::p()))
2112            {
2113                out.push(Finding::new(
2114                    "RUBY_OUTSIDE_RUN",
2115                    &name,
2116                    element_path(&dom, ruby),
2117                    "w:ruby is a direct child of w:p; OOXML requires ruby inside w:r",
2118                ));
2119            }
2120        }
2121    }
2122}
2123
2124/// `w:body[0]/w:p[3]/w:r[2]`: conventional prefix and local name with the
2125/// index among same-named siblings, root excluded.
2126pub(crate) fn element_path(dom: &Dom, node: NodeId) -> String {
2127    let mut parts = Vec::new();
2128    let mut cur = Some(node);
2129    while let Some(n) = cur {
2130        let Some(parent) = dom.parent(n) else { break };
2131        if dom.parent(parent).is_none() {
2132            break;
2133        }
2134        let Some(name) = dom.name(n) else { break };
2135        let index = dom
2136            .elements(parent, Some(&name))
2137            .iter()
2138            .position(|&e| e == n)
2139            .unwrap_or(0);
2140        let prefix = well_known_prefix(name.namespace_name())
2141            .map(|p| format!("{p}:"))
2142            .unwrap_or_default();
2143        parts.push(format!("{prefix}{}[{index}]", name.local_name()));
2144        cur = Some(parent);
2145    }
2146    parts.reverse();
2147    parts.join("/")
2148}
2149
2150fn parse_part(pkg: &PartFs, name: &str) -> Option<(Dom, NodeId)> {
2151    let xml = pkg.part_string(name)?;
2152    // Strict parts are read as the Transitional names these checks compare.
2153    let xml = crate::strict_translation::transitional_part(name, &xml);
2154    let mut dom = Dom::new();
2155    let doc = dom.parse_xdocument(&xml);
2156    let root = dom.root(doc)?;
2157    Some((dom, root))
2158}
2159
2160/// The package's XML parts: by name, or by content type (a main document
2161/// part may be `word/main.dat`).
2162fn xml_parts(pkg: &PartFs) -> Vec<String> {
2163    pkg.parts()
2164        .into_iter()
2165        .filter(|name| {
2166            crate::opc::ends_with_ignore_case(name, ".xml")
2167                || pkg
2168                    .content_type_for(name)
2169                    .is_some_and(|ct| crate::opc::is_xml_content_type(&ct))
2170        })
2171        .collect()
2172}
2173
2174/// The XML parts that hold WordprocessingML: every XML part but custom XML
2175/// data, which holds the application's own XML whatever its name
2176/// ([`crate::opc::custom_xml_data`]: a part only `customXml` relationships
2177/// reach, the package's own included). OpenXmlValidator checks no revision
2178/// id there, and no paragraph id (#1666).
2179fn wordml_parts(pkg: &PartFs) -> Vec<String> {
2180    let parts = pkg.parts();
2181    let data =
2182        crate::opc::custom_xml_data(std::iter::once(("", pkg.package_relationships())).chain(
2183            parts.iter().filter_map(|source| {
2184                pkg.read_rels_for(source)
2185                    .map(|rels| (source.as_str(), rels))
2186            }),
2187        ));
2188    xml_parts(pkg)
2189        .into_iter()
2190        .filter(|name| !data.iter().any(|item| item.eq_ignore_ascii_case(name)))
2191        .collect()
2192}
2193
2194/// `w:w` on `w:gridCol`, `w:tcW` and `w:tblW` when `f32`'s parser accepts
2195/// the value and the value is not finite. That is `NaN`, `inf`,
2196/// `infinity` (any sign and case) and a magnitude that overflows `f32`
2197/// (`1e40` is `Ok(inf)`). A token the parser rejects is not this
2198/// finding: `12pt` is a legal universal measure on `tblW` and `tcW`,
2199/// and plain garbage such as `abc` is not already a Ring-1 code, but
2200/// folding it in would report that legal measure too.
2201///
2202/// `word_fatal` follows the element. Word 16.115, 2026-10-31 (#1737):
2203/// `gridcol-NaN`, `gridcol-inf` and `gridcol-1e40` were unreadable
2204/// content. `tcw-NaN`, `tcw-inf`, `tcw-1e40`, `tblw-NaN`, `tblw-inf`,
2205/// `tblw-1e40` and `valid-control` opened cleanly. No repair was
2206/// verified, so `repairable` stays false.
2207fn check_non_finite_measures(pkg: &PartFs, out: &mut Vec<Finding>) {
2208    for part in wordml_parts(pkg) {
2209        let Some((dom, root)) = parse_part(pkg, &part) else {
2210            continue;
2211        };
2212        dom.for_each_descendant_element(root, None, |node| {
2213            let local = if dom.name_is(node, &W::grid_col()) {
2214                "gridCol"
2215            } else if dom.name_is(node, &W::tc_w()) {
2216                "tcW"
2217            } else if dom.name_is(node, &W::tbl_w()) {
2218                "tblW"
2219            } else {
2220                return;
2221            };
2222            let Some(value) = dom.attribute(node, &W::w()) else {
2223                return;
2224            };
2225            if !f32_parses_non_finite(value) {
2226                return;
2227            }
2228            let mut finding = Finding::new(
2229                "NON_FINITE_MEASURE",
2230                &part,
2231                element_path(&dom, node),
2232                format!("w:{local}/@w:w value '{value}' parses as f32 and is not finite"),
2233            );
2234            // Word 16.115, 2026-10-31 (#1737): gridcol-NaN, gridcol-inf and
2235            // gridcol-1e40 were unreadable content. tcw-* and tblw-* of
2236            // those tokens, and valid-control, opened cleanly.
2237            if local != "gridCol" {
2238                finding.word_fatal = false;
2239                finding.severity = "warning".to_string();
2240            }
2241            out.push(finding);
2242        });
2243    }
2244}
2245
2246/// A measure token `str::parse::<f32>` accepts that is not finite.
2247fn f32_parses_non_finite(value: &str) -> bool {
2248    matches!(value.parse::<f32>(), Ok(number) if !number.is_finite())
2249}
2250
2251// ── Ring-1 checks ─────────────────────────────────────────────────────────
2252
2253/// Every prefix an MC prefix list names (`mc:Choice/@Requires`,
2254/// `mc:Ignorable`, …) is bound where it is named, in every XML part: Word
2255/// rejects a header whose `mc:Choice Requires="wps"` names an unbound `wps`.
2256fn check_namespace_qname_contexts(pkg: &PartFs, out: &mut Vec<Finding>) {
2257    for part in xml_parts(pkg) {
2258        check_namespace_qname_context(pkg, &part, out);
2259    }
2260}
2261
2262fn check_content_types_and_xml(pkg: &PartFs, out: &mut Vec<Finding>) {
2263    for name in pkg.parts() {
2264        // Every part should have a content type (default or override).
2265        if pkg.content_type_for(&name).is_none()
2266            && name != "[Content_Types].xml"
2267            && !name.starts_with(crate::debug::OFFICE_TRASH)
2268        {
2269            out.push(Finding::new(
2270                "MISSING_CONTENT_TYPE",
2271                &name,
2272                "",
2273                format!("part '{name}' has no content type"),
2274            ));
2275        }
2276        // XML-ish parts must parse.
2277        if name.ends_with(".xml") || name.ends_with(".rels") {
2278            let Some(xml) = pkg.part_string(&name) else {
2279                out.push(Finding::new(
2280                    "MALFORMED_XML",
2281                    &name,
2282                    "",
2283                    format!("part '{name}' unreadable as string"),
2284                ));
2285                continue;
2286            };
2287            let mut reader = quick_xml::NsReader::from_str(&xml);
2288            reader.config_mut().trim_text(false);
2289            let mut buf = Vec::new();
2290            // A part with no element at all (empty, or only a prolog and
2291            // comments) is not well-formed XML, and Word refuses the
2292            // package (#2479).
2293            let mut has_root = false;
2294            loop {
2295                match reader.read_event_into(&mut buf) {
2296                    Ok(Event::Eof) => {
2297                        if !has_root {
2298                            out.push(Finding::new(
2299                                "MALFORMED_XML",
2300                                &name,
2301                                "",
2302                                format!("part '{name}' is not well-formed XML: no root element"),
2303                            ));
2304                        }
2305                        break;
2306                    }
2307                    Ok(Event::Start(tag) | Event::Empty(tag)) => {
2308                        has_root = true;
2309                        let mut expanded = HashSet::new();
2310                        for attr in tag.attributes().with_checks(false).flatten() {
2311                            if attr.key.as_ref() == "xmlns"
2312                                || attr.key.as_ref().starts_with("xmlns:")
2313                            {
2314                                continue;
2315                            }
2316                            let (namespace, local) = reader.resolver().resolve_attribute(attr.key);
2317                            let namespace = match namespace {
2318                                quick_xml::name::ResolveResult::Bound(ns) => {
2319                                    quick_xml::escape::unescape(ns.as_ref()).map_or_else(
2320                                        |_| ns.as_ref().to_string(),
2321                                        |uri| uri.into_owned(),
2322                                    )
2323                                }
2324                                quick_xml::name::ResolveResult::Unbound => String::new(),
2325                                quick_xml::name::ResolveResult::Unknown(_) => continue,
2326                            };
2327                            if !expanded.insert((namespace, local.as_ref().to_string())) {
2328                                let element = tag.name().as_ref().to_string();
2329                                out.push(Finding::new(
2330                                    "DUPLICATE_EXPANDED_ATTRIBUTE",
2331                                    &name,
2332                                    &element,
2333                                    format!("part '{name}', element <{element}>: attribute {} repeats an expanded name", attr.key.as_ref()),
2334                                ));
2335                            }
2336                        }
2337                    }
2338                    Ok(_) => {}
2339                    Err(e) => {
2340                        out.push(Finding::new(
2341                            "MALFORMED_XML",
2342                            &name,
2343                            "",
2344                            format!("part '{name}' is not well-formed XML: {e}"),
2345                        ));
2346                        break;
2347                    }
2348                }
2349                buf.clear();
2350            }
2351        }
2352    }
2353}
2354
2355/// Every attribute in the officeDocument relationships namespace resolves in
2356/// that part's `.rels`;
2357/// no duplicate rIds; no dangling internal targets.
2358fn check_relationship_integrity(pkg: &PartFs, out: &mut Vec<Finding>) {
2359    let mut reported_missing = HashSet::new();
2360    // Opening kept one copy of each identical repeat; the source still
2361    // repeats it, which Word refuses (docxide case8).
2362    for (part, id) in pkg.repaired_duplicate_ids() {
2363        let owner = if part.is_empty() {
2364            "_rels/.rels"
2365        } else {
2366            part.as_str()
2367        };
2368        out.push(Finding::new(
2369            "DUPLICATE_RID",
2370            owner,
2371            "",
2372            format!("duplicate rId '{id}' in relationships of '{owner}' (identical; one kept)"),
2373        ));
2374    }
2375    for name in pkg.parts() {
2376        // Part names are case-insensitive, so `document.XML` owns its
2377        // references as `document.xml` does.
2378        let extension = name.rsplit_once('.').map_or("", |(_, ext)| ext);
2379        if !extension.eq_ignore_ascii_case("xml") {
2380            continue;
2381        }
2382        let rels = pkg.read_rels_for(&name);
2383        let mut ids: HashSet<String> = HashSet::new();
2384        let mut targets: HashMap<String, (String, bool)> = HashMap::new();
2385        if let Some(r) = rels {
2386            let mut seen_ids = HashSet::new();
2387            for item in &r.items {
2388                if !seen_ids.insert(item.id.clone()) {
2389                    out.push(Finding::new(
2390                        "DUPLICATE_RID",
2391                        &name,
2392                        "",
2393                        format!("duplicate rId '{}' in relationships of '{name}'", item.id),
2394                    ));
2395                }
2396                ids.insert(item.id.clone());
2397                let external = item.target_mode.as_deref() == Some("External");
2398                targets.insert(item.id.clone(), (item.target.clone(), external));
2399            }
2400        }
2401        let Some((dom, root)) = parse_part(pkg, &name) else {
2402            continue;
2403        };
2404        for element in dom.descendants_and_self(root, None) {
2405            for (attribute, rid) in dom.attributes_iter(element) {
2406                if attribute.namespace_name() != R::URI || rid.is_empty() {
2407                    continue;
2408                }
2409                if !ids.contains(rid) {
2410                    let mut finding = Finding::new(
2411                        "DANGLING_RELATIONSHIP",
2412                        &name,
2413                        "",
2414                        format!("dangling relationship id '{rid}' referenced from '{name}'"),
2415                    );
2416                    // `id`, `embed` and `link` keep the Word-fatal finding they
2417                    // always had; the names this walk added remain repairable
2418                    // leads until probed in Word (#1937).
2419                    if !matches!(attribute.local_name(), "id" | "embed" | "link") {
2420                        finding.word_fatal = false;
2421                        finding.severity = "warning".to_string();
2422                    }
2423                    out.push(finding);
2424                } else if let Some((target, external)) = targets.get(rid)
2425                    && !external
2426                    && let Some(resolved) = missing_relationship_target(pkg, &name, target)
2427                    && reported_missing.insert((name.to_ascii_lowercase(), rid.to_string()))
2428                {
2429                    out.push(Finding::new(
2430                        "MISSING_REL_TARGET",
2431                        &name,
2432                        "",
2433                        format!(
2434                            "relationship '{rid}' on '{name}' targets missing part '{target}' (resolved '{resolved}')"
2435                        ),
2436                    ));
2437                }
2438            }
2439        }
2440    }
2441    // PartFs keeps parsed .rels separately from parts(), including the
2442    // package's _rels/.rels and relationships of missing/non-XML owners.
2443    for (source, rels) in pkg.relationship_parts() {
2444        for item in &rels.items {
2445            if item.target_mode.as_deref() == Some("External")
2446                || reported_missing.contains(&(source.to_ascii_lowercase(), item.id.clone()))
2447            {
2448                continue;
2449            }
2450            let Some(resolved) = missing_relationship_target(pkg, source, &item.target) else {
2451                continue;
2452            };
2453            let rels_part = if let Some((dir, file)) = source.rsplit_once('/') {
2454                format!("{dir}/_rels/{file}.rels")
2455            } else {
2456                format!("_rels/{source}.rels")
2457            };
2458            let mut finding = Finding::new(
2459                "MISSING_REL_TARGET",
2460                &rels_part,
2461                "",
2462                format!(
2463                    "unused relationship '{}' in '{rels_part}' targets missing part '{}' (resolved '{resolved}')",
2464                    item.id, item.target
2465                ),
2466            );
2467            // Word has not been probed for the unused variant (#1938), and
2468            // repair does not drop relationships, so it is a plain lead.
2469            finding.word_fatal = false;
2470            finding.repairable = false;
2471            finding.severity = "warning".to_string();
2472            out.push(finding);
2473        }
2474    }
2475}
2476
2477/// A target that is not an OPC part: an absolute URI, a Windows path, or a
2478/// UNC share. A doubled slash in front of a package root (`//word/...`, in
2479/// any ASCII case, as part names are) still names a part.
2480fn external_uri_target(target: &str) -> bool {
2481    if target.starts_with("http://")
2482        || target.starts_with("https://")
2483        || target.starts_with("mailto:")
2484        || target.starts_with("file:")
2485        || target.contains('\\')
2486    {
2487        return true;
2488    }
2489    let Some(rest) = target.strip_prefix("//") else {
2490        return false;
2491    };
2492    let host = rest.split('/').next().unwrap_or("");
2493    !host.is_empty()
2494        && !["word", "docProps", "customXml", "_rels", "ppt", "xl"]
2495            .iter()
2496            .any(|root| host.eq_ignore_ascii_case(root))
2497}
2498
2499/// Internal targets must name a part at their resolved package path.
2500fn missing_relationship_target(pkg: &PartFs, source: &str, target: &str) -> Option<String> {
2501    if external_uri_target(target) {
2502        return None;
2503    }
2504    let resolved = pkg.resolve_rel_target(source, target);
2505    // A target written as a package path from the root names its part too.
2506    (pkg.part_bytes(&resolved).is_none()
2507        && pkg.part_bytes(target.trim_start_matches('/')).is_none())
2508    .then_some(resolved)
2509}
2510
2511/// Every `w:lvlPicBulletId` names a `w:numPicBullet` of the same numbering
2512/// part: Word refuses the whole package otherwise ("document loaded empty").
2513fn check_picture_bullets(pkg: &PartFs, out: &mut Vec<Finding>) {
2514    const PART: &str = "word/numbering.xml";
2515    let Some((dom, root)) = parse_part(pkg, PART) else {
2516        return;
2517    };
2518    let defined: HashSet<&str> = dom
2519        .elements(root, Some(&W::name("numPicBullet")))
2520        .into_iter()
2521        .filter_map(|b| dom.attribute(b, &W::name("numPicBulletId")))
2522        .collect();
2523    for pic in dom.descendants(root, Some(&W::name("lvlPicBulletId"))) {
2524        if let Some(id) = dom.attribute(pic, &W::val())
2525            && !defined.contains(id)
2526        {
2527            out.push(Finding::new(
2528                "PICTURE_BULLET_UNDEFINED",
2529                PART,
2530                element_path(&dom, pic),
2531                format!("lvlPicBulletId '{id}' names no numPicBullet in word/numbering.xml"),
2532            ));
2533        }
2534    }
2535}
2536
2537/// Two `w:num` elements that share one numbering `w16cid:durableId`. A copy
2538/// takes a fresh id, and the editor writes none, so a repeat is a warning.
2539fn check_duplicate_num_durable_ids(pkg: &PartFs, out: &mut Vec<Finding>) {
2540    const PART: &str = "word/numbering.xml";
2541    const CID: &str = "http://schemas.microsoft.com/office/word/2016/wordml/cid";
2542    let Some((dom, root)) = parse_part(pkg, PART) else {
2543        return;
2544    };
2545    let mut seen: HashSet<String> = HashSet::new();
2546    let mut reported: HashSet<String> = HashSet::new();
2547    for num in dom.elements(root, Some(&W::name("num"))) {
2548        let Some(id) = num_durable_id(&dom, num, CID) else {
2549            continue;
2550        };
2551        if !seen.insert(id.to_string()) && reported.insert(id.to_string()) {
2552            out.push(Finding::new(
2553                "DUPLICATE_DURABLE_ID",
2554                PART,
2555                element_path(&dom, num),
2556                format!("w:num repeats durableId '{id}'"),
2557            ));
2558        }
2559    }
2560}
2561
2562fn num_durable_id<'a>(dom: &'a Dom, num: NodeId, namespace: &str) -> Option<&'a str> {
2563    for index in 0..dom.attr_count(num) {
2564        let (name, value) = dom.attr_at(num, index);
2565        if name.local_name() == "durableId" && name.namespace_name() == namespace {
2566            return Some(value);
2567        }
2568    }
2569    None
2570}
2571
2572/// `wp:docPr` ids are document-wide, not per part. A header or footer
2573/// drawing that repeats a body drawing's id, or a header or footer with
2574/// drawings that two sections reference (Word loads it once per section, so
2575/// its ids repeat), made Windows Word 2024 refuse 16 jubarte 0.19.0 redlines
2576/// as corrupt (remote Word, 2026-11-23); a copy with fresh ids opened each.
2577/// Word opened 24 others that also repeat ids across parts, so this stays a
2578/// lead, like the in-part repeat. `mc:Fallback` twins are Word's own and
2579/// stay out, as in [`collect_ids`].
2580fn check_doc_pr_ids_across_stories(pkg: &PartFs, out: &mut Vec<Finding>) {
2581    let Some(main) = main_part(pkg) else {
2582        return;
2583    };
2584    let mut stories = vec![main.clone()];
2585    stories.extend(crate::document_comparer::drawing_story_parts(pkg, &main));
2586    let mut holder: HashMap<String, String> = HashMap::new();
2587    let mut with_drawings: HashSet<String> = HashSet::new();
2588    for part in &stories {
2589        if !pkg
2590            .part_bytes(part)
2591            .is_some_and(|b| b.windows(6).any(|w| w == b":docPr"))
2592        {
2593            continue;
2594        }
2595        let Some((dom, root)) = parse_part(pkg, part) else {
2596            continue;
2597        };
2598        let mut own: HashSet<String> = HashSet::new();
2599        for e in dom.descendants(root, None) {
2600            if !dom.name(e).is_some_and(|n| n.local_name() == "docPr")
2601                || !dom.ancestors(e, Some(&MC::name("Fallback"))).is_empty()
2602            {
2603                continue;
2604            }
2605            with_drawings.insert(part.clone());
2606            let Some(id) = dom
2607                .attributes(e)
2608                .into_iter()
2609                .find(|(n, _)| n.local_name() == "id")
2610                .map(|(_, v)| v)
2611            else {
2612                continue;
2613            };
2614            if !own.insert(id.clone()) {
2615                continue; // an in-part repeat: collect_ids reports it
2616            }
2617            match holder.get(&id) {
2618                Some(first) => out.push(Finding::new(
2619                    "DUPLICATE_DOCPR_ID",
2620                    part,
2621                    element_path(&dom, e),
2622                    format!("wp:docPr id '{id}' in '{part}' repeats a drawing's id in '{first}'"),
2623                )),
2624                None => {
2625                    holder.insert(id, part.clone());
2626                }
2627            }
2628        }
2629    }
2630    if with_drawings.len() <= usize::from(with_drawings.contains(&main)) {
2631        return;
2632    }
2633    let Some((dom, root)) = parse_part(pkg, &main) else {
2634        return;
2635    };
2636    let mut sections: HashMap<String, usize> = HashMap::new();
2637    for (_, parts) in crate::document_comparer::section_story_parts(&dom, root, pkg, &main) {
2638        for part in parts {
2639            *sections.entry(part).or_default() += 1;
2640        }
2641    }
2642    let mut shared: Vec<_> = sections
2643        .into_iter()
2644        .filter(|(part, n)| *n > 1 && with_drawings.contains(part))
2645        .collect();
2646    shared.sort();
2647    for (part, n) in shared {
2648        out.push(Finding::new(
2649            "DUPLICATE_DOCPR_ID",
2650            &part,
2651            "",
2652            format!(
2653                "'{part}' holds drawings and {n} sections reference it: Word loads it once per section, so its wp:docPr ids repeat"
2654            ),
2655        ));
2656    }
2657}
2658
2659fn check_revision_and_drawing_ids(pkg: &PartFs, out: &mut Vec<Finding>) {
2660    for name in wordml_parts(pkg) {
2661        let Some((dom, root)) = parse_part(pkg, &name) else {
2662            continue;
2663        };
2664        let mut rev_ids: HashSet<String> = HashSet::new();
2665        let mut docpr_ids: HashSet<String> = HashSet::new();
2666        collect_ids(&dom, root, &mut rev_ids, &mut docpr_ids, out, &name);
2667        // Word writes repeated ids (including AlternateContent twins). Only
2668        // a self-reference or a type absent from this part is diagnostic.
2669        // The maintainer's six #1800 probes all opened cleanly, so this is
2670        // a warning, never a Word-fatal uniqueness invariant.
2671        let id_attr = XName::get("id", "");
2672        let active: Vec<_> = dom
2673            .descendants(root, None)
2674            .into_iter()
2675            .filter(|&n| {
2676                (dom.name_is(n, &VML::shape()) || dom.name_is(n, &VML::shapetype()))
2677                    && dom.ancestors(n, Some(&MC::name("Fallback"))).is_empty()
2678            })
2679            .collect();
2680        let types: HashSet<_> = active
2681            .iter()
2682            .filter(|&&n| dom.name_is(n, &VML::shapetype()))
2683            .filter_map(|&n| dom.attribute(n, &id_attr))
2684            .collect();
2685        for node in active {
2686            if dom.name_is(node, &VML::shape())
2687                && let Some(target) = dom
2688                    .attribute(node, &XName::get("type", ""))
2689                    .and_then(|s| s.strip_prefix('#'))
2690                && (dom.attribute(node, &id_attr) == Some(target) || !types.contains(target))
2691            {
2692                out.push(Finding::new(
2693                    "VML_SHAPE_TYPE_INVALID",
2694                    &name,
2695                    element_path(&dom, node),
2696                    format!(
2697                        "VML shape type '#{target}' names its own id or no shapetype in '{name}'"
2698                    ),
2699                ));
2700            }
2701        }
2702    }
2703}
2704
2705/// The SDK distinguishes run revisions from row/paragraph-mark revisions,
2706/// even though both use `ins`, `del`, `moveFrom` or `moveTo`. Row and
2707/// paragraph marks share their own scope; the immediate parent alone is
2708/// therefore not the scope. Keep detection and repair on the same key.
2709/// The SDK compares some kinds' ids case-blind (`ABC` repeats `abc`).
2710fn revision_id_key(dom: &Dom, node: NodeId, local: &str, id: &str) -> String {
2711    let property_mark = matches!(local, "ins" | "del" | "moveFrom" | "moveTo")
2712        && dom.parent(node).is_some_and(|parent| {
2713            dom.name(parent).is_some_and(|parent| {
2714                parent.namespace_name() == W::URI && matches!(parent.local_name(), "rPr" | "trPr")
2715            })
2716        });
2717    if id_case_blind(local) {
2718        format!("{local}:{property_mark}:{}", id.to_lowercase())
2719    } else {
2720        format!("{local}:{property_mark}:{id}")
2721    }
2722}
2723
2724/// Whether the SDK compares a kind's ids case-blind (`ABC` repeats `abc`).
2725fn id_case_blind(local: &str) -> bool {
2726    matches!(
2727        local,
2728        "customXmlDelRangeStart" | "customXmlDelRangeEnd" | "moveToRangeStart"
2729    )
2730}
2731
2732/// Two ids compared as [`revision_id_key`] compares them, without building
2733/// either key.
2734fn same_revision_id(case_blind: bool, a: &str, b: &str) -> bool {
2735    if !case_blind {
2736        a == b
2737    } else if a.is_ascii() && b.is_ascii() {
2738        a.eq_ignore_ascii_case(b)
2739    } else {
2740        a.to_lowercase() == b.to_lowercase()
2741    }
2742}
2743
2744/// The end that closes a range start of this kind.
2745fn range_end_of(start: &str) -> Option<&'static str> {
2746    Some(match start {
2747        "moveFromRangeStart" => "moveFromRangeEnd",
2748        "moveToRangeStart" => "moveToRangeEnd",
2749        "customXmlInsRangeStart" => "customXmlInsRangeEnd",
2750        "customXmlDelRangeStart" => "customXmlDelRangeEnd",
2751        "customXmlMoveFromRangeStart" => "customXmlMoveFromRangeEnd",
2752        "customXmlMoveToRangeStart" => "customXmlMoveToRangeEnd",
2753        _ => return None,
2754    })
2755}
2756
2757/// The range start a range end of this kind closes.
2758fn range_start_of(end: &str) -> Option<&'static str> {
2759    Some(match end {
2760        "moveFromRangeEnd" => "moveFromRangeStart",
2761        "moveToRangeEnd" => "moveToRangeStart",
2762        "customXmlInsRangeEnd" => "customXmlInsRangeStart",
2763        "customXmlDelRangeEnd" => "customXmlDelRangeStart",
2764        "customXmlMoveFromRangeEnd" => "customXmlMoveFromRangeStart",
2765        "customXmlMoveToRangeEnd" => "customXmlMoveToRangeStart",
2766        _ => return None,
2767    })
2768}
2769
2770/// How often each revision id occurs, by the scope `DUPLICATE_REVISION_ID`
2771/// checks: part, then record type and id ([`revision_id_key`]). A Strict
2772/// package is read as the Transitional one an edit writes.
2773#[doc(hidden)]
2774pub fn revision_id_occurrences(
2775    docx: &[u8],
2776) -> Result<HashMap<(String, String), usize>, ValidateError> {
2777    let transitional = crate::strict_translation::strict_to_transitional_docx(docx)
2778        .map_err(|e| ValidateError::Package(e.to_string()))?;
2779    let pkg = PartFs::open(&transitional)?;
2780    let mut out = HashMap::new();
2781    for part in wordml_parts(&pkg) {
2782        let Some((dom, root)) = parse_part(&pkg, &part) else {
2783            continue;
2784        };
2785        let mut counts: HashMap<String, usize> = HashMap::new();
2786        let id_name = W::id();
2787        for e in dom.descendants(root, None) {
2788            if let Some(name) = dom.name(e)
2789                && has_unique_revision_id(&name)
2790                && let Some(id) = dom.attribute(e, &id_name)
2791            {
2792                *counts
2793                    .entry(revision_id_key(&dom, e, name.local_name(), id))
2794                    .or_default() += 1;
2795            }
2796        }
2797        out.extend(
2798            counts
2799                .into_iter()
2800                .map(|(key, count)| ((part.clone(), key), count)),
2801        );
2802    }
2803    Ok(out)
2804}
2805
2806fn collect_ids(
2807    dom: &Dom,
2808    root: NodeId,
2809    rev_ids: &mut HashSet<String>,
2810    docpr_ids: &mut HashSet<String>,
2811    out: &mut Vec<Finding>,
2812    part: &str,
2813) {
2814    // Repeated range starts not yet paired with a repeated end, by key.
2815    let mut repeated_starts: HashMap<String, usize> = HashMap::new();
2816    let id_name = W::id();
2817    for e in dom.descendants(root, None) {
2818        let Some(name) = dom.name(e) else {
2819            continue;
2820        };
2821        let local = name.local_name();
2822        // Revision ids are scoped by record type, not by the union of
2823        // ins/del/move/property records. Comment ids have a separate scope.
2824        if has_unique_revision_id(&name)
2825            && let Some(id) = dom.attribute(e, &id_name)
2826        {
2827            let key = revision_id_key(dom, e, name.local_name(), id);
2828            if rev_ids.insert(key.clone()) {
2829                continue;
2830            }
2831            let mut finding = Finding::new(
2832                "DUPLICATE_REVISION_ID",
2833                part,
2834                element_path(dom, e),
2835                format!("duplicate w:id '{id}' on revision markup in '{part}' ({local}:{id})"),
2836            );
2837            // Repair renames an end only with a repeated start before it
2838            // ([`renumber_duplicate_revision_ids`]); an end with none stays
2839            // as it was (#1666).
2840            if local.ends_with("RangeStart") {
2841                *repeated_starts.entry(key).or_default() += 1;
2842            } else if let Some(start) = range_start_of(local) {
2843                match repeated_starts.get_mut(&revision_id_key(dom, e, start, id)) {
2844                    Some(n) if *n > 0 => *n -= 1,
2845                    _ => finding.repairable = false,
2846                }
2847            }
2848            out.push(finding);
2849        }
2850        // Word reads one branch of a dual-saved shape: a picture repeated in
2851        // its `mc:Fallback` copy keeps the choice's docPr id, and Word opens
2852        // that twin clean (w12's header, 2026-10-27).
2853        if local == "docPr" && dom.ancestors(e, Some(&MC::name("Fallback"))).is_empty() {
2854            let wp_id = XName::get(
2855                "id",
2856                "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
2857            );
2858            let id = dom.attribute(e, &wp_id).map(str::to_string).or_else(|| {
2859                dom.attributes(e)
2860                    .into_iter()
2861                    .find(|(n, _)| n.local_name() == "id")
2862                    .map(|(_, v)| v)
2863            });
2864            if let Some(id) = id
2865                && !docpr_ids.insert(id.clone())
2866            {
2867                out.push(Finding::new(
2868                    "DUPLICATE_DOCPR_ID",
2869                    part,
2870                    element_path(dom, e),
2871                    format!("duplicate wp:docPr id '{id}' in '{part}'"),
2872                ));
2873            }
2874        }
2875    }
2876}
2877
2878/// `(attribute, value)` pairs of `w14:paraId` / `w14:textId` values at or
2879/// above Word's `0x80000000` bound, in `xml`.
2880/// Every `w14:paraId` / `w14:textId` value in a part, parsed.
2881fn para_id_values(xml: &str) -> Vec<u32> {
2882    let mut found = Vec::new();
2883    for attr in ["w14:paraId=\"", "w14:textId=\""] {
2884        let mut rest = xml;
2885        while let Some(i) = rest.find(attr) {
2886            let after = &rest[i + attr.len()..];
2887            let Some(end) = after.find('"') else { break };
2888            if let Ok(n) = u32::from_str_radix(&after[..end], 16) {
2889                found.push(n);
2890            }
2891            rest = &after[end + 1..];
2892        }
2893    }
2894    found
2895}
2896
2897fn out_of_range_para_ids(xml: &str) -> Vec<(&'static str, String)> {
2898    let mut found = Vec::new();
2899    for attr in ["w14:paraId=\"", "w14:textId=\""] {
2900        let mut rest = xml;
2901        while let Some(i) = rest.find(attr) {
2902            let after = &rest[i + attr.len()..];
2903            let Some(end) = after.find('"') else { break };
2904            let val = &after[..end];
2905            if let Ok(n) = u32::from_str_radix(val, 16)
2906                && (n >= 0x8000_0000 || n == 0)
2907            {
2908                found.push((attr, val.to_string()));
2909            }
2910            rest = &after[end + 1..];
2911        }
2912    }
2913    found
2914}
2915
2916fn check_para_text_id_bounds(pkg: &PartFs, out: &mut Vec<Finding>) {
2917    for name in wordml_parts(pkg) {
2918        let Some(xml) = pkg.part_string(&name) else {
2919            continue;
2920        };
2921        for (attr, val) in out_of_range_para_ids(&xml) {
2922            out.push(Finding::new(
2923                "PARA_ID_OUT_OF_RANGE",
2924                &name,
2925                "",
2926                format!(
2927                    "{attr} value '{val}' outside Word's range 1..0x7FFFFFFF (>= 0x80000000 or zero) in '{name}' (id-paraid-overflow)"
2928                ),
2929            ));
2930        }
2931    }
2932}
2933
2934/// `w:del` must carry `w:delText` (never `w:t`).
2935/// `w:moveFrom` must carry `w:t` (never `w:delText`) — Word-required contract
2936/// settled by Ring-3 probe 2026-07-16 (delText-under-moveFrom failed open).
2937/// The nearest deletion owns the text: an insertion inside the move source
2938/// does not shelter `w:delText` (Word refuses it), a `w:del` inside it does
2939/// (Word opens it; probes M1/M5, 2026-10-18). A deletion outside the move
2940/// source owns the text as well, so that `w:delText` stays.
2941fn check_del_text_under_del(pkg: &PartFs, out: &mut Vec<Finding>) {
2942    for name in xml_parts(pkg) {
2943        let Some((dom, root)) = parse_part(pkg, &name) else {
2944            continue;
2945        };
2946        for (live, deleted, code) in [
2947            ("t", "delText", "TEXT_INSIDE_DELETION"),
2948            ("instrText", "delInstrText", "INSTR_TEXT_INSIDE_DELETION"),
2949        ] {
2950            for t in dom.descendants(root, Some(&W::name(live))) {
2951                if under_deletion(&dom, t) {
2952                    out.push(Finding::new(
2953                        code,
2954                        &name,
2955                        element_path(&dom, t),
2956                        format!("w:{live} under w:del in '{name}' (must be w:{deleted})"),
2957                    ));
2958                }
2959            }
2960        }
2961        let move_from = W::move_from();
2962        for mf in dom.descendants(root, Some(&move_from)) {
2963            for dt in dom.descendants(mf, Some(&W::del_text())) {
2964                if ancestor_has(&dom, dt, mf, "del") || under_deletion(&dom, dt) {
2965                    continue;
2966                }
2967                out.push(Finding::new(
2968                    "MOVEFROM_WITH_DELTEXT",
2969                    &name,
2970                    element_path(&dom, dt),
2971                    format!("w:delText under w:moveFrom in '{name}' (Word requires w:t)"),
2972                ));
2973            }
2974        }
2975    }
2976}
2977
2978/// Any enclosing deletion counts, even through an insertion, but only
2979/// within the run's own story (#1134, Word probe 2026-10-17).
2980fn under_deletion(dom: &Dom, node: NodeId) -> bool {
2981    // Walks the parent links rather than collecting the ancestors: the
2982    // checks call this once per `w:delText` of a move source.
2983    let mut cur = dom.parent(node);
2984    while let Some(p) = cur {
2985        match dom.name(p) {
2986            Some(n) if n.local_name() == "txbxContent" => return false,
2987            Some(n) if n == W::del() => return true,
2988            _ => cur = dom.parent(p),
2989        }
2990    }
2991    false
2992}
2993
2994/// True when a `w:del` or `w:moveFrom` covers `node` in its own story (a
2995/// text box's `w:txbxContent` is a separate story).
2996fn covered_by_deletion(dom: &Dom, node: NodeId) -> bool {
2997    let mut cur = dom.parent(node);
2998    while let Some(p) = cur {
2999        match dom.name(p).as_ref().map(|n| n.local_name()) {
3000            Some("del" | "moveFrom") => return true,
3001            Some("txbxContent") => return false,
3002            _ => cur = dom.parent(p),
3003        }
3004    }
3005    false
3006}
3007
3008/// `w:delText` / `w:delInstrText` must sit under a `w:del` (or `w:moveFrom`)
3009/// in its OWN story. A text box's `w:txbxContent` is a separate story: the
3010/// `w:del` around its anchor run does not cover it. Word refuses a deleted text
3011/// box whose field code is `w:delInstrText` in a run no deletion wraps (en
3012/// 30ff840c/bb113e88); Word's own redline wraps the whole field in a `w:del`
3013/// inside the text box. The OpenXmlValidator passes the file.
3014fn check_deleted_text_has_deletion(pkg: &PartFs, out: &mut Vec<Finding>) {
3015    for name in xml_parts(pkg) {
3016        let Some((dom, root)) = parse_part(pkg, &name) else {
3017            continue;
3018        };
3019        for kind in ["delText", "delInstrText"] {
3020            for t in dom.descendants(root, Some(&W::name(kind))) {
3021                if !covered_by_deletion(&dom, t) {
3022                    out.push(Finding::new(
3023                        "DELTEXT_OUTSIDE_DELETION",
3024                        &name,
3025                        element_path(&dom, t),
3026                        format!(
3027                            "w:{kind} in '{name}' has no w:del in its own story (text boxes are separate stories)"
3028                        ),
3029                    ));
3030                }
3031            }
3032        }
3033    }
3034}
3035
3036/// Content controls whose content is a single value: Word keeps no bookmark
3037/// in them.
3038const SINGLE_VALUE_CONTROLS: [&str; 6] = [
3039    "text",
3040    "dropDownList",
3041    "comboBox",
3042    "date",
3043    "picture",
3044    "checkbox",
3045];
3046
3047/// `(bookmark mark, kind, control)` for every bookmark start or end inside a
3048/// single-value content control.
3049fn bookmarks_in_single_value_controls(
3050    dom: &Dom,
3051    root: NodeId,
3052) -> Vec<(NodeId, &'static str, String)> {
3053    let mut found = Vec::new();
3054    for kind in ["bookmarkStart", "bookmarkEnd"] {
3055        for m in dom.descendants(root, Some(&W::name(kind))) {
3056            for sdt in dom.ancestors(m, Some(&W::sdt())) {
3057                let control = dom
3058                    .element(sdt, &W::sdt_pr())
3059                    .into_iter()
3060                    .flat_map(|pr| dom.elements(pr, None))
3061                    .filter_map(|c| dom.name(c).map(|n| n.local_name().to_string()))
3062                    .find(|c| SINGLE_VALUE_CONTROLS.contains(&c.as_str()));
3063                if let Some(control) = control {
3064                    found.push((m, kind, control));
3065                }
3066            }
3067        }
3068    }
3069    found
3070}
3071
3072/// No bookmark start or end in a plain-text, dropdown, combo box, date,
3073/// picture or checkbox content control. Jubarte carried B's bookmarks into a
3074/// data-bound title control (en 7b649361) and a dropdown cell (en 57c181da);
3075/// Word refused both files and opened each once those bookmarks were
3076/// dropped. No bookmark in the 1000 English sources sits in such a control.
3077/// The OpenXmlValidator passes the files.
3078fn check_bookmarks_outside_single_value_controls(pkg: &PartFs, out: &mut Vec<Finding>) {
3079    for name in xml_parts(pkg) {
3080        let Some(xml) = pkg.part_string(&name) else {
3081            continue;
3082        };
3083        if !xml.contains("bookmark") || !xml.contains("sdtContent") {
3084            continue;
3085        }
3086        let mut dom = Dom::new();
3087        let doc = dom.parse_xdocument(&xml);
3088        let Some(root) = dom.root(doc) else {
3089            continue;
3090        };
3091        for (m, kind, control) in bookmarks_in_single_value_controls(&dom, root) {
3092            out.push(Finding::new(
3093                "BOOKMARK_IN_SINGLE_VALUE_CONTROL",
3094                &name,
3095                element_path(&dom, m),
3096                format!(
3097                    "w:{kind} in '{name}' sits in a {control} content control (Word keeps no bookmark there)"
3098                ),
3099            ));
3100        }
3101    }
3102}
3103
3104fn ancestor_has(dom: &Dom, node: NodeId, stop: NodeId, local: &str) -> bool {
3105    let mut cur = dom.parent(node);
3106    while let Some(p) = cur {
3107        if p == stop {
3108            break;
3109        }
3110        if let Some(n) = dom.name(p)
3111            && n.local_name() == local
3112        {
3113            return true;
3114        }
3115        cur = dom.parent(p);
3116    }
3117    false
3118}
3119
3120const COMMENT_FAMILY: [(&str, &str, &str); 4] = [
3121    (
3122        "word/comments.xml",
3123        "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml",
3124        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
3125    ),
3126    (
3127        "word/commentsExtended.xml",
3128        "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml",
3129        "http://schemas.microsoft.com/office/2011/relationships/commentsExtended",
3130    ),
3131    (
3132        "word/commentsIds.xml",
3133        "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsIds+xml",
3134        "http://schemas.microsoft.com/office/2016/09/relationships/commentsIds",
3135    ),
3136    (
3137        "word/commentsExtensible.xml",
3138        "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtensible+xml",
3139        "http://schemas.microsoft.com/office/2018/08/relationships/commentsExtensible",
3140    ),
3141];
3142
3143const COMMENTS_PART: &str = "word/comments.xml";
3144
3145/// The comments part as Word finds it: the first relationship of the
3146/// comments type whose target part exists (`word/comments.xml` is only the
3147/// conventional name — Word follows the relationship, so a differently
3148/// named part is the comments part), else the conventional name when it
3149/// exists unlinked. A relationship whose target is missing does not stop
3150/// the walk: a later live relationship still names the part.
3151fn comments_part(pkg: &PartFs, main: &str) -> Option<String> {
3152    if let Some(name) = pkg
3153        .read_rels_for(main)
3154        .into_iter()
3155        .flat_map(|relationships| &relationships.items)
3156        .filter(|r| {
3157            r.rel_type == COMMENT_FAMILY[0].2 && r.target_mode.as_deref() != Some("External")
3158        })
3159        .map(|r| {
3160            pkg.resolve_rel_target(main, &r.target)
3161                .trim_start_matches('/')
3162                .to_string()
3163        })
3164        .find(|name| pkg.part_bytes(name).is_some())
3165    {
3166        return Some(name);
3167    }
3168    pkg.part_bytes(COMMENTS_PART)
3169        .map(|_| COMMENTS_PART.to_string())
3170}
3171
3172fn main_part(pkg: &PartFs) -> Option<String> {
3173    pkg.main_document_part().or_else(|| {
3174        pkg.part_bytes("word/document.xml")
3175            .map(|_| "word/document.xml".to_string())
3176    })
3177}
3178
3179/// A finding of the comment family: `code` on `part`, no path.
3180fn comment_finding(out: &mut Vec<Finding>, code: &str, part: &str, message: String) {
3181    out.push(Finding::new(code, part, "", message));
3182}
3183
3184fn check_comment_graph(pkg: &PartFs, out: &mut Vec<Finding>) {
3185    let Some(main) = main_part(pkg) else {
3186        return;
3187    };
3188    let Some((main_dom, main_root)) = parse_part(pkg, &main) else {
3189        return;
3190    };
3191    let starts = comment_id_counts(&main_dom, main_root, "commentRangeStart");
3192    let ends = comment_id_counts(&main_dom, main_root, "commentRangeEnd");
3193    let references = comment_id_counts(&main_dom, main_root, "commentReference");
3194
3195    let Some(comments_name) = comments_part(pkg, &main) else {
3196        for (kind, counts) in [
3197            ("commentRangeStart", &starts),
3198            ("commentRangeEnd", &ends),
3199            ("commentReference", &references),
3200        ] {
3201            for id in counts.keys() {
3202                comment_finding(
3203                    out,
3204                    "COMMENT_ANCHOR_ORPHAN",
3205                    &main,
3206                    format!("{kind} id '{id}' has no entry in word/comments.xml"),
3207                );
3208            }
3209        }
3210        for (part, _, _) in &COMMENT_FAMILY[1..] {
3211            if pkg.part_bytes(part).is_some() {
3212                comment_finding(
3213                    out,
3214                    "COMMENT_METADATA_MISMATCH",
3215                    part,
3216                    format!("'{part}' exists without word/comments.xml"),
3217                );
3218            }
3219        }
3220        return;
3221    };
3222    let Some((comments_dom, comments_root)) = parse_part(pkg, &comments_name) else {
3223        return;
3224    };
3225
3226    let definitions = comment_id_counts(&comments_dom, comments_root, "comment");
3227    for (kind, counts, part) in [
3228        ("comment definition", &definitions, comments_name.as_str()),
3229        ("commentRangeStart", &starts, main.as_str()),
3230        ("commentRangeEnd", &ends, main.as_str()),
3231        ("commentReference", &references, main.as_str()),
3232    ] {
3233        // Word hangs on two references for one comment; it opens repeated
3234        // range markers or definitions, showing the first definition.
3235        let code = if kind == "commentReference" {
3236            "COMMENT_PARTS_INCONSISTENT"
3237        } else {
3238            "COMMENT_ID_REPEATED"
3239        };
3240        for (id, count) in counts {
3241            if *count != 1 {
3242                comment_finding(
3243                    out,
3244                    code,
3245                    part,
3246                    format!("{kind} id '{id}' occurs {count} times"),
3247                );
3248            }
3249        }
3250    }
3251    // Word shows a comment from its reference in a paragraph and from
3252    // nothing else; without one the file opens and the comment is not shown
3253    // (2026-10-10), so it is a lead. Missing range markers are no finding:
3254    // the reference alone shows a point comment.
3255    for id in definitions
3256        .keys()
3257        .filter(|id| !references.contains_key(*id))
3258    {
3259        comment_finding(
3260            out,
3261            "COMMENT_UNANCHORED",
3262            &comments_name,
3263            format!(
3264                "comment definition id '{id}' has no commentReference in the document: Word opens it and shows no comment"
3265            ),
3266        );
3267    }
3268    // A reference to no definition is refused; a range marker to none is
3269    // opened as it is.
3270    for (kind, counts, code) in [
3271        ("commentRangeStart", &starts, "COMMENT_RANGE_ORPHAN"),
3272        ("commentRangeEnd", &ends, "COMMENT_RANGE_ORPHAN"),
3273        ("commentReference", &references, "COMMENT_ANCHOR_ORPHAN"),
3274    ] {
3275        for id in counts.keys().filter(|id| !definitions.contains_key(*id)) {
3276            comment_finding(
3277                out,
3278                code,
3279                &main,
3280                format!("{kind} id '{id}' has no entry in {comments_name}"),
3281            );
3282        }
3283    }
3284
3285    check_comment_family_packaging(pkg, &main, out);
3286
3287    let aux_present = COMMENT_FAMILY[1..]
3288        .iter()
3289        .any(|(part, _, _)| pkg.part_bytes(part).is_some());
3290    let mut all_para_ids = HashSet::new();
3291    let mut last_para_ids = HashSet::new();
3292    for comment in comments_dom.elements(comments_root, Some(&W::comment())) {
3293        let comment_id = comments_dom
3294            .attribute(comment, &W::id())
3295            .unwrap_or("<missing>");
3296        let mut comment_para_ids = Vec::new();
3297        for paragraph in comments_dom.descendants(comment, Some(&W::p())) {
3298            let Some(para_id) = comments_dom.attribute(paragraph, &W14::name("paraId")) else {
3299                continue;
3300            };
3301            let key = para_id.to_ascii_uppercase();
3302            check_hex_id("paraId", para_id, true, &comments_name, out);
3303            if !all_para_ids.insert(key.clone()) {
3304                comment_finding(
3305                    out,
3306                    "COMMENT_METADATA_MISMATCH",
3307                    &comments_name,
3308                    format!("duplicate comment paraId '{para_id}' in {comments_name}"),
3309                );
3310            }
3311            comment_para_ids.push(key);
3312        }
3313        if aux_present && comment_para_ids.is_empty() {
3314            comment_finding(
3315                out,
3316                "COMMENT_METADATA_MISMATCH",
3317                &comments_name,
3318                format!("comment id '{comment_id}' has no w14:paraId for its auxiliary metadata"),
3319            );
3320        }
3321        if let Some(last) = comment_para_ids.last() {
3322            last_para_ids.insert(last.clone());
3323        }
3324    }
3325
3326    let extended_para_ids = check_comments_extended(pkg, &last_para_ids, out);
3327    let durable_ids = check_comments_ids(pkg, &last_para_ids, out);
3328    check_comments_extensible(pkg, durable_ids.as_ref(), out);
3329    if let Some(extended) = extended_para_ids {
3330        for parent in extended.parents.values() {
3331            if !extended.keys.contains(parent) {
3332                comment_finding(
3333                    out,
3334                    "COMMENT_METADATA_MISMATCH",
3335                    "word/commentsExtended.xml",
3336                    format!("commentsExtended paraIdParent '{parent}' does not resolve"),
3337                );
3338            }
3339        }
3340        check_parent_cycles(&extended.parents, out);
3341    }
3342}
3343
3344/// How often each id occurs on `local` elements. An `mc:Fallback` copy is
3345/// not counted: Word reads one branch of a dual-saved shape, so markers
3346/// repeated in its fallback are no second anchor (probe k05, 2026-10-10).
3347fn comment_id_counts(dom: &Dom, root: NodeId, local: &str) -> HashMap<String, usize> {
3348    let mut counts = HashMap::new();
3349    for element in dom.descendants(root, Some(&W::name(local))) {
3350        if !dom
3351            .ancestors(element, Some(&MC::name("Fallback")))
3352            .is_empty()
3353        {
3354            continue;
3355        }
3356        if let Some(id) = dom.attribute(element, &W::id()) {
3357            *counts.entry(id.to_string()).or_default() += 1;
3358        }
3359    }
3360    counts
3361}
3362
3363fn check_comment_family_packaging(pkg: &PartFs, main: &str, out: &mut Vec<Finding>) {
3364    let rels = pkg.read_rels_for(main);
3365    for (part, content_type, relationship_type) in COMMENT_FAMILY {
3366        let part_present = pkg.part_bytes(part).is_some();
3367        let matching: Vec<_> = rels
3368            .into_iter()
3369            .flat_map(|relationships| &relationships.items)
3370            .filter(|relationship| relationship.rel_type == relationship_type)
3371            .collect();
3372        if part_present {
3373            if pkg.content_type_for(part).as_deref() != Some(content_type) {
3374                comment_finding(
3375                    out,
3376                    "COMMENT_PARTS_INCONSISTENT",
3377                    part,
3378                    format!("'{part}' has the wrong content type (expected '{content_type}')"),
3379                );
3380            }
3381            if matching.len() != 1 {
3382                comment_finding(
3383                    out,
3384                    "COMMENT_PARTS_INCONSISTENT",
3385                    main,
3386                    format!(
3387                        "'{main}' needs exactly one relationship to '{part}', found {}",
3388                        matching.len()
3389                    ),
3390                );
3391            }
3392            for relationship in matching {
3393                let resolved = pkg
3394                    .resolve_rel_target(main, &relationship.target)
3395                    .trim_start_matches('/')
3396                    .to_string();
3397                if relationship.target_mode.as_deref() == Some("External") || resolved != part {
3398                    comment_finding(
3399                        out,
3400                        "COMMENT_PARTS_INCONSISTENT",
3401                        main,
3402                        format!(
3403                            "comment relationship '{}' on '{main}' resolves to '{}' instead of '{part}'",
3404                            relationship.id, relationship.target
3405                        ),
3406                    );
3407                }
3408            }
3409        } else if !matching.is_empty() {
3410            comment_finding(
3411                out,
3412                "COMMENT_METADATA_MISMATCH",
3413                main,
3414                format!("'{main}' has a relationship for missing comment part '{part}'"),
3415            );
3416        }
3417    }
3418}
3419
3420fn check_hex_id(
3421    label: &str,
3422    value: &str,
3423    word_para_bound: bool,
3424    part: &str,
3425    out: &mut Vec<Finding>,
3426) {
3427    // Word reads up to eight hex digits: seven open (k06), nine are refused
3428    // (k07, 2026-10-10).
3429    let parsed =
3430        if (1..=8).contains(&value.len()) && value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
3431            u32::from_str_radix(value, 16).ok()
3432        } else {
3433            None
3434        };
3435    let Some(parsed) = parsed else {
3436        comment_finding(
3437            out,
3438            "COMMENT_PARTS_INCONSISTENT",
3439            part,
3440            format!("{label} '{value}' is not a hexadecimal id of up to 8 digits"),
3441        );
3442        return;
3443    };
3444    if word_para_bound && parsed >= 0x8000_0000 {
3445        comment_finding(
3446            out,
3447            "COMMENT_METADATA_MISMATCH",
3448            part,
3449            format!("{label} '{value}' is outside Word's paraId range"),
3450        );
3451    }
3452}
3453
3454struct ExtendedGraph {
3455    keys: HashSet<String>,
3456    parents: HashMap<String, String>,
3457}
3458
3459fn check_comments_extended(
3460    pkg: &PartFs,
3461    last_para_ids: &HashSet<String>,
3462    out: &mut Vec<Finding>,
3463) -> Option<ExtendedGraph> {
3464    const PART: &str = "word/commentsExtended.xml";
3465    let (dom, root) = parse_part(pkg, PART)?;
3466    let mut keys = HashSet::new();
3467    let mut parents = HashMap::new();
3468    for entry in dom.elements(root, None) {
3469        let Some(para_id) = attribute_by_local(&dom, entry, "paraId") else {
3470            comment_finding(
3471                out,
3472                "COMMENT_PARTS_INCONSISTENT",
3473                PART,
3474                "commentsExtended entry has no paraId".to_string(),
3475            );
3476            continue;
3477        };
3478        let key = para_id.to_ascii_uppercase();
3479        check_hex_id("commentsExtended paraId", para_id, true, PART, out);
3480        if !keys.insert(key.clone()) {
3481            comment_finding(
3482                out,
3483                "COMMENT_METADATA_MISMATCH",
3484                PART,
3485                format!("duplicate commentsExtended paraId '{para_id}'"),
3486            );
3487        }
3488        if let Some(parent) = attribute_by_local(&dom, entry, "paraIdParent") {
3489            let parent = parent.to_ascii_uppercase();
3490            check_hex_id("commentsExtended paraIdParent", &parent, true, PART, out);
3491            if parent == key {
3492                comment_finding(
3493                    out,
3494                    "COMMENT_PARENT_CYCLE",
3495                    PART,
3496                    format!("commentsExtended paraId '{key}' is its own parent"),
3497                );
3498            }
3499            parents.insert(key, parent);
3500        }
3501    }
3502    check_exact_key_set("commentsExtended paraId", &keys, last_para_ids, PART, out);
3503    Some(ExtendedGraph { keys, parents })
3504}
3505
3506fn check_comments_ids(
3507    pkg: &PartFs,
3508    last_para_ids: &HashSet<String>,
3509    out: &mut Vec<Finding>,
3510) -> Option<HashSet<String>> {
3511    const PART: &str = "word/commentsIds.xml";
3512    let (dom, root) = parse_part(pkg, PART)?;
3513    let mut para_ids = HashSet::new();
3514    let mut durable_ids = HashSet::new();
3515    for entry in dom.elements(root, None) {
3516        let Some(para_id) = attribute_by_local(&dom, entry, "paraId") else {
3517            comment_finding(
3518                out,
3519                "COMMENT_PARTS_INCONSISTENT",
3520                PART,
3521                "commentsIds entry has no paraId".to_string(),
3522            );
3523            continue;
3524        };
3525        let para_key = para_id.to_ascii_uppercase();
3526        check_hex_id("commentsIds paraId", para_id, true, PART, out);
3527        if !para_ids.insert(para_key) {
3528            comment_finding(
3529                out,
3530                "COMMENT_METADATA_MISMATCH",
3531                PART,
3532                format!("duplicate commentsIds paraId '{para_id}'"),
3533            );
3534        }
3535        let Some(durable_id) = attribute_by_local(&dom, entry, "durableId") else {
3536            comment_finding(
3537                out,
3538                "COMMENT_METADATA_MISMATCH",
3539                PART,
3540                format!("commentsIds paraId '{para_id}' has no durableId"),
3541            );
3542            continue;
3543        };
3544        let durable_key = durable_id.to_ascii_uppercase();
3545        check_hex_id("commentsIds durableId", durable_id, false, PART, out);
3546        if !durable_ids.insert(durable_key) {
3547            comment_finding(
3548                out,
3549                "COMMENT_METADATA_MISMATCH",
3550                PART,
3551                format!("duplicate commentsIds durableId '{durable_id}'"),
3552            );
3553        }
3554    }
3555    check_exact_key_set("commentsIds paraId", &para_ids, last_para_ids, PART, out);
3556    Some(durable_ids)
3557}
3558
3559fn check_comments_extensible(
3560    pkg: &PartFs,
3561    expected_durable_ids: Option<&HashSet<String>>,
3562    out: &mut Vec<Finding>,
3563) {
3564    const PART: &str = "word/commentsExtensible.xml";
3565    let Some((dom, root)) = parse_part(pkg, PART) else {
3566        return;
3567    };
3568    let mut durable_ids = HashSet::new();
3569    for entry in dom.elements(root, None) {
3570        let Some(durable_id) = attribute_by_local(&dom, entry, "durableId") else {
3571            comment_finding(
3572                out,
3573                "COMMENT_METADATA_MISMATCH",
3574                PART,
3575                "commentsExtensible entry has no durableId".to_string(),
3576            );
3577            continue;
3578        };
3579        let key = durable_id.to_ascii_uppercase();
3580        check_hex_id("commentsExtensible durableId", durable_id, false, PART, out);
3581        if !durable_ids.insert(key) {
3582            comment_finding(
3583                out,
3584                "COMMENT_METADATA_MISMATCH",
3585                PART,
3586                format!("duplicate commentsExtensible durableId '{durable_id}'"),
3587            );
3588        }
3589    }
3590    match expected_durable_ids {
3591        Some(expected) => check_exact_key_set(
3592            "commentsExtensible durableId",
3593            &durable_ids,
3594            expected,
3595            PART,
3596            out,
3597        ),
3598        None => comment_finding(
3599            out,
3600            "COMMENT_METADATA_MISMATCH",
3601            PART,
3602            "commentsExtensible exists without commentsIds".to_string(),
3603        ),
3604    }
3605}
3606
3607fn attribute_by_local<'a>(dom: &'a Dom, element: NodeId, local: &str) -> Option<&'a str> {
3608    for index in 0..dom.attr_count(element) {
3609        let (name, value) = dom.attr_at(element, index);
3610        if name.local_name() == local {
3611            return Some(value);
3612        }
3613    }
3614    None
3615}
3616
3617fn check_exact_key_set(
3618    label: &str,
3619    actual: &HashSet<String>,
3620    expected: &HashSet<String>,
3621    part: &str,
3622    out: &mut Vec<Finding>,
3623) {
3624    for key in expected.difference(actual) {
3625        comment_finding(
3626            out,
3627            "COMMENT_METADATA_MISMATCH",
3628            part,
3629            format!("{label} is missing '{key}'"),
3630        );
3631    }
3632    for key in actual.difference(expected) {
3633        comment_finding(
3634            out,
3635            "COMMENT_METADATA_MISMATCH",
3636            part,
3637            format!("{label} '{key}' has no matching comment paragraph"),
3638        );
3639    }
3640}
3641
3642fn check_parent_cycles(parents: &HashMap<String, String>, out: &mut Vec<Finding>) {
3643    for start in parents.keys() {
3644        let mut seen = HashSet::new();
3645        let mut current = start;
3646        while let Some(parent) = parents.get(current) {
3647            if !seen.insert(current.clone()) {
3648                comment_finding(
3649                    out,
3650                    "COMMENT_PARENT_CYCLE",
3651                    "word/commentsExtended.xml",
3652                    format!("commentsExtended paraIdParent cycle contains '{current}'"),
3653                );
3654                break;
3655            }
3656            current = parent;
3657        }
3658    }
3659}
3660
3661/// An unqualified `Requires` is a prefix list only on `mc:Choice`; on any
3662/// other element (a custom XML part) it is application data.
3663fn is_namespace_qname_list(element: &XName, name: &XName) -> bool {
3664    (name.namespace_name().is_empty()
3665        && name.local_name() == "Requires"
3666        && element.namespace_name() == MC::URI
3667        && element.local_name() == "Choice")
3668        || (name.namespace_name() == MC::URI
3669            && matches!(
3670                name.local_name(),
3671                "Ignorable"
3672                    | "PreserveAttributes"
3673                    | "PreserveElements"
3674                    | "ProcessContent"
3675                    | "MustUnderstand"
3676            ))
3677}
3678
3679fn check_namespace_qname_context(pkg: &PartFs, part: &str, out: &mut Vec<Finding>) {
3680    let Some((dom, root)) = parse_part(pkg, part) else {
3681        return;
3682    };
3683    for element in dom.descendants_and_self(root, None) {
3684        let Some(element_name) = dom.name(element) else {
3685            continue;
3686        };
3687        for (name, value) in dom.attributes_iter(element) {
3688            if !is_namespace_qname_list(&element_name, name) {
3689                continue;
3690            }
3691            for token in value.split_whitespace() {
3692                let prefix = token.split_once(':').map_or(token, |(prefix, _)| prefix);
3693                if prefix != "xml" && namespace_in_scope(&dom, element, prefix).is_none() {
3694                    let mut finding = Finding::new(
3695                        "MC_UNBOUND_PREFIX",
3696                        part,
3697                        element_path(&dom, element),
3698                        format!(
3699                            "unresolved namespace prefix '{prefix}' in {}='{}' in '{part}'",
3700                            name.local_name(),
3701                            value
3702                        ),
3703                    );
3704                    finding.repairable = well_known_namespace(prefix).is_some();
3705                    out.push(finding);
3706                }
3707            }
3708        }
3709    }
3710}
3711
3712/// The namespace `prefix` names at `element`: the nearest `xmlns:prefix`
3713/// declaration on it or an ancestor.
3714pub(crate) fn namespace_in_scope<'a>(
3715    dom: &'a Dom,
3716    element: NodeId,
3717    prefix: &str,
3718) -> Option<&'a str> {
3719    let mut current = Some(element);
3720    while let Some(node) = current {
3721        for index in 0..dom.attr_count(node) {
3722            let (name, value) = dom.attr_at(node, index);
3723            if dom.is_namespace_declaration(name) && name.local_name() == prefix {
3724                return Some(value);
3725            }
3726        }
3727        current = dom.parent(node);
3728    }
3729    None
3730}
3731
3732// ── Repair ────────────────────────────────────────────────────────────────
3733
3734/// The package with every repairable finding fixed, in a fixed order:
3735/// unbound MC prefixes bound on the part root, `w:t`/`w:delText` swapped,
3736/// bookmarks dropped from single-value controls, dangling relationship
3737/// attributes dropped, duplicate drawing and revision ids renumbered,
3738/// paragraph ids brought into Word's range, cells given a last paragraph,
3739/// orphan comment anchors dropped. The result is validated again to fill
3740/// `remaining`. A package with no repairable finding comes back as its
3741/// own bytes; an ISO Strict package with one is repaired, and written
3742/// back, Transitional.
3743///
3744/// # Errors
3745///
3746/// As [`validate`], plus a package that cannot be written back.
3747pub fn repair(docx: &[u8]) -> Result<Repaired, ValidateError> {
3748    let findings = validate(docx)?;
3749    // Nothing to repair: hand the bytes back untouched rather than a
3750    // rewritten zip, so "nothing changed" is visible as equal bytes.
3751    if !findings.iter().any(|f| f.repairable) {
3752        return Ok(Repaired {
3753            docx: docx.to_vec(),
3754            repaired: Vec::new(),
3755            remaining: findings,
3756        });
3757    }
3758    let has = |code: &str| findings.iter().any(|f| f.code == code);
3759    let parts_with = |codes: &[&str]| -> Vec<String> {
3760        let mut parts: Vec<String> = findings
3761            .iter()
3762            .filter(|f| codes.contains(&f.code.as_str()))
3763            .map(|f| f.part.clone())
3764            .collect();
3765        parts.sort();
3766        parts.dedup();
3767        parts
3768    };
3769    // Ring-1 reads a Strict part under its Transitional names, and the
3770    // repairs below edit those names: a Strict package is repaired, and
3771    // written back, Transitional, as accept and reject write it.
3772    let transitional = crate::strict_translation::strict_to_transitional_docx(docx)
3773        .map_err(|e| ValidateError::Package(e.to_string()))?;
3774    let bytes = if has("DUPLICATE_DOCPR_ID") {
3775        crate::comparer::fixups::fix_up_drawing_ids_in_package(&transitional)?
3776    } else {
3777        transitional
3778    };
3779    let mut pkg = PartFs::open(&bytes)?;
3780    if has("DUPLICATE_DOCPR_ID") {
3781        crate::document_comparer::fix_up_drawing_ids_across_package(&mut pkg, false);
3782    }
3783    for part in parts_with(&["MC_UNBOUND_PREFIX"]) {
3784        edit_part(&mut pkg, &part, |dom, root| {
3785            crate::comparer::finalize::bind_compatibility_prefixes(dom, root);
3786        });
3787    }
3788    for part in parts_with(&[
3789        "TEXT_INSIDE_DELETION",
3790        "DELTEXT_OUTSIDE_DELETION",
3791        "MOVEFROM_WITH_DELTEXT",
3792        "INSTR_TEXT_INSIDE_DELETION",
3793    ]) {
3794        edit_part(&mut pkg, &part, fix_deleted_text);
3795    }
3796    for part in parts_with(&["BOOKMARK_IN_SINGLE_VALUE_CONTROL"]) {
3797        edit_part(&mut pkg, &part, drop_bookmarks_in_single_value_controls);
3798    }
3799    for part in parts_with(&["DANGLING_RELATIONSHIP"]) {
3800        let ids: HashSet<String> = pkg
3801            .read_rels_for(&part)
3802            .map(|r| r.items.iter().map(|i| i.id.clone()).collect())
3803            .unwrap_or_default();
3804        edit_part(&mut pkg, &part, |dom, root| {
3805            drop_dangling_relationship_attributes(dom, root, &ids);
3806        });
3807    }
3808    for part in parts_with(&["DUPLICATE_REVISION_ID"]) {
3809        edit_part(&mut pkg, &part, |dom, root| {
3810            renumber_duplicate_revision_ids(dom, root);
3811        });
3812    }
3813    if has("PARA_ID_OUT_OF_RANGE") {
3814        renumber_out_of_range_para_ids(&mut pkg);
3815    }
3816    for part in parts_with(&["CELL_WITHOUT_PARAGRAPH"]) {
3817        edit_part(&mut pkg, &part, end_cells_with_a_paragraph);
3818    }
3819    if (has("COMMENT_ANCHOR_ORPHAN") || has("COMMENT_RANGE_ORPHAN"))
3820        && let Some(main) = main_part(&pkg)
3821    {
3822        let defined: HashSet<String> = parse_part(&pkg, COMMENTS_PART)
3823            .map(|(dom, root)| {
3824                comment_id_counts(&dom, root, "comment")
3825                    .into_keys()
3826                    .collect()
3827            })
3828            .unwrap_or_default();
3829        edit_part(&mut pkg, &main, |dom, root| {
3830            drop_orphan_comment_anchors(dom, root, &defined);
3831        });
3832    }
3833    let docx = pkg.to_zip()?;
3834    let remaining = validate(&docx)?;
3835    let same =
3836        |a: &Finding, b: &Finding| a.code == b.code && a.part == b.part && a.message == b.message;
3837    let repaired = findings
3838        .into_iter()
3839        .filter(|f| f.repairable && !remaining.iter().any(|r| same(f, r)))
3840        .collect();
3841    Ok(Repaired {
3842        docx,
3843        repaired,
3844        remaining,
3845    })
3846}
3847
3848/// Parse `part`, let `f` change it, write it back.
3849fn edit_part(pkg: &mut PartFs, part: &str, f: impl FnOnce(&mut Dom, NodeId)) {
3850    let Some(xml) = pkg.part_string(part) else {
3851        return;
3852    };
3853    let mut dom = Dom::new();
3854    let doc = dom.parse_xdocument(&xml);
3855    let Some(root) = dom.root(doc) else {
3856        return;
3857    };
3858    f(&mut dom, root);
3859    pkg.set_part(part, dom.serialize_document(doc).into_bytes());
3860}
3861
3862/// `w:t` and `w:instrText` under a deletion become `w:delText` and
3863/// `w:delInstrText`. `w:delText` under a move source becomes live text
3864/// again only when no deletion in that story covers it, as does deleted
3865/// text no deletion covers.
3866fn fix_deleted_text(dom: &mut Dom, root: NodeId) {
3867    let mut renames: Vec<(NodeId, XName)> = Vec::new();
3868    for (live, deleted) in [("t", "delText"), ("instrText", "delInstrText")] {
3869        for t in dom.descendants(root, Some(&W::name(live))) {
3870            if under_deletion(dom, t) {
3871                renames.push((t, W::name(deleted)));
3872            }
3873        }
3874    }
3875    for mf in dom.descendants(root, Some(&W::move_from())) {
3876        for dt in dom.descendants(mf, Some(&W::del_text())) {
3877            if !ancestor_has(dom, dt, mf, "del") && !under_deletion(dom, dt) {
3878                renames.push((dt, W::t()));
3879            }
3880        }
3881    }
3882    for (node, name) in renames {
3883        dom.set_name(node, name);
3884    }
3885    let mut revive: Vec<(NodeId, XName)> = Vec::new();
3886    for (deleted, live) in [("delText", "t"), ("delInstrText", "instrText")] {
3887        for t in dom.descendants(root, Some(&W::name(deleted))) {
3888            if !covered_by_deletion(dom, t) {
3889                revive.push((t, W::name(live)));
3890            }
3891        }
3892    }
3893    for (node, name) in revive {
3894        dom.set_name(node, name);
3895    }
3896}
3897
3898/// Every bookmark whose start or end sits in a single-value content control
3899/// is dropped whole (both marks, wherever the other one is).
3900fn drop_bookmarks_in_single_value_controls(dom: &mut Dom, root: NodeId) {
3901    let ids: HashSet<String> = bookmarks_in_single_value_controls(dom, root)
3902        .into_iter()
3903        .filter_map(|(m, _, _)| dom.attribute(m, &W::id()).map(str::to_string))
3904        .collect();
3905    let doomed: Vec<NodeId> = ["bookmarkStart", "bookmarkEnd"]
3906        .into_iter()
3907        .flat_map(|kind| dom.descendants(root, Some(&W::name(kind))))
3908        .filter(|&m| {
3909            dom.attribute(m, &W::id())
3910                .is_some_and(|id| ids.contains(id))
3911        })
3912        .collect();
3913    for m in doomed {
3914        dom.remove(m);
3915    }
3916}
3917
3918/// Elements whose `r:id` the schema requires: without the relationship the
3919/// element itself has to go, not just the attribute.
3920const REQUIRES_RELATIONSHIP: [&str; 7] = [
3921    "headerReference",
3922    "footerReference",
3923    "altChunk",
3924    "attachedTemplate",
3925    "contentPart",
3926    "movie",
3927    "subDoc",
3928];
3929
3930/// Relationship attributes (`r:id`, `r:embed`, `r:link`, …) naming no
3931/// relationship of the part are dropped, which is what stops Word's
3932/// "unreadable content" repair. An element the schema gives no meaning
3933/// without its relationship (a header reference, an altChunk, …) is removed
3934/// whole.
3935fn drop_dangling_relationship_attributes(dom: &mut Dom, root: NodeId, ids: &HashSet<String>) {
3936    let mut doomed: Vec<(NodeId, XName)> = Vec::new();
3937    let mut removed: Vec<NodeId> = Vec::new();
3938    for el in dom.descendants_and_self(root, None) {
3939        for (name, value) in dom.attributes(el) {
3940            if name.namespace_name() == R::URI && !value.is_empty() && !ids.contains(&value) {
3941                let required = name.local_name() == "id"
3942                    && dom
3943                        .name(el)
3944                        .is_some_and(|n| REQUIRES_RELATIONSHIP.contains(&n.local_name()));
3945                if required {
3946                    removed.push(el);
3947                } else {
3948                    doomed.push((el, name));
3949                }
3950            }
3951        }
3952    }
3953    for (el, name) in doomed {
3954        dom.set_attribute_value(el, &name, None);
3955    }
3956    for el in removed {
3957        dom.remove(el);
3958    }
3959}
3960
3961/// A second use of a revision id on the same record type is renumbered
3962/// from the part's highest `w:id` upwards; a range start takes its end
3963/// along. An end is never renumbered on its own: which start it closes is
3964/// not known. Accepted cross-kind pairs retain their ids.
3965#[doc(hidden)]
3966pub fn renumber_duplicate_revision_ids(dom: &mut Dom, root: NodeId) -> Vec<(String, String)> {
3967    let id_name = W::id();
3968    let all: Vec<NodeId> = dom.descendants(root, None);
3969    let mut next: u64 = all
3970        .iter()
3971        .filter_map(|&n| dom.attribute(n, &id_name))
3972        .filter_map(|v| v.parse::<u64>().ok())
3973        .max()
3974        .unwrap_or(0)
3975        + 1;
3976    // The revision records with an id (range ends aside), and how often
3977    // each key occurs.
3978    let mut starts = Vec::new();
3979    let mut count: HashMap<String, usize> = HashMap::new();
3980    for (i, &n) in all.iter().enumerate() {
3981        let Some(name) = dom.name(n) else { continue };
3982        if !has_unique_revision_id(&name) || name.local_name().ends_with("RangeEnd") {
3983            continue;
3984        }
3985        let Some(id) = dom.attribute(n, &id_name).map(str::to_string) else {
3986            continue;
3987        };
3988        let key = revision_id_key(dom, n, name.local_name(), &id);
3989        *count.entry(key.clone()).or_default() += 1;
3990        starts.push((i, n, name, id, key));
3991    }
3992    let mut seen: HashSet<String> = HashSet::new();
3993    // Range ends a start before has taken.
3994    let mut taken: HashSet<NodeId> = HashSet::new();
3995    let mut renames: Vec<(NodeId, String)> = Vec::new();
3996    let mut revisions = Vec::new();
3997    for (i, n, name, id, key) in starts {
3998        if count[&key] < 2 {
3999            continue;
4000        }
4001        // A range start's end shares its id: the first that follows with
4002        // it, by the rule the duplicate check reads (`ABC` closes `abc`
4003        // where ids compare case-blind, #1666), and that no
4004        // start before has taken, so three starts of one id before their
4005        // three ends pair one to one (#1666).
4006        let end = range_end_of(name.local_name()).and_then(|end_local| {
4007            let blind = id_case_blind(end_local);
4008            all[i + 1..].iter().copied().find(|&e| {
4009                !taken.contains(&e)
4010                    && dom.name(e).is_some_and(|x| {
4011                        x.namespace_name() == W::URI && x.local_name() == end_local
4012                    })
4013                    && dom
4014                        .attribute(e, &id_name)
4015                        .is_some_and(|own| same_revision_id(blind, own, &id))
4016            })
4017        });
4018        if let Some(end) = end {
4019            taken.insert(end);
4020        }
4021        if seen.insert(key) {
4022            continue;
4023        }
4024        let fresh = next.to_string();
4025        next += 1;
4026        revisions.push((id, fresh.clone()));
4027        renames.push((n, fresh.clone()));
4028        if let Some(end) = end {
4029            renames.push((end, fresh));
4030        }
4031    }
4032    for (n, id) in renames {
4033        dom.set_attribute_value(n, &id_name, Some(&id));
4034    }
4035    revisions
4036}
4037
4038/// Every `w14:paraId` / `w14:textId` at or above `0x80000000` is masked
4039/// into Word's range, and every reference to it (`paraIdParent`, the
4040/// comment parts) follows.
4041fn renumber_out_of_range_para_ids(pkg: &mut PartFs) {
4042    let parts = wordml_parts(pkg);
4043    let mut used: HashSet<u32> = HashSet::new();
4044    for name in &parts {
4045        let Some(xml) = pkg.part_string(name) else {
4046            continue;
4047        };
4048        used.extend(para_id_values(&xml));
4049    }
4050    let mut map: HashMap<String, String> = HashMap::new();
4051    for name in &parts {
4052        let Some(xml) = pkg.part_string(name) else {
4053            continue;
4054        };
4055        for (_, old) in out_of_range_para_ids(&xml) {
4056            if map.contains_key(&old) {
4057                continue;
4058            }
4059            // The masked value first; if that is zero or taken, the next free
4060            // id upwards, wrapping inside Word's range.
4061            let mut n = u32::from_str_radix(&old, 16).unwrap_or(0) & 0x7FFF_FFFF;
4062            while n == 0 || used.contains(&n) {
4063                n = (n + 1) & 0x7FFF_FFFF;
4064            }
4065            used.insert(n);
4066            map.insert(old, format!("{n:08X}"));
4067        }
4068    }
4069    if map.is_empty() {
4070        return;
4071    }
4072    for name in &parts {
4073        let Some(mut xml) = pkg.part_string(name) else {
4074            continue;
4075        };
4076        let before = xml.clone();
4077        for (old, new) in &map {
4078            for attr in ["paraId", "textId", "paraIdParent"] {
4079                xml = xml.replace(&format!("{attr}=\"{old}\""), &format!("{attr}=\"{new}\""));
4080            }
4081        }
4082        if xml != before {
4083            pkg.set_part(name, xml.into_bytes());
4084        }
4085    }
4086}
4087
4088/// A table cell whose last child (its properties aside) is not a paragraph
4089/// gets an empty one.
4090fn end_cells_with_a_paragraph(dom: &mut Dom, root: NodeId) {
4091    let cells: Vec<NodeId> = dom
4092        .descendants(root, Some(&W::tc()))
4093        .into_iter()
4094        .filter(|&tc| !crate::debug::cell_ends_in_paragraph(dom, tc))
4095        .collect();
4096    for tc in cells {
4097        let p = dom.new_element(W::p());
4098        dom.add(tc, p);
4099    }
4100}
4101
4102/// Comment range marks and references naming no comment definition are
4103/// dropped; a run left holding only its properties goes with its reference.
4104fn drop_orphan_comment_anchors(dom: &mut Dom, root: NodeId, defined: &HashSet<String>) {
4105    let orphan = |dom: &Dom, n: NodeId| {
4106        dom.attribute(n, &W::id())
4107            .is_some_and(|id| !defined.contains(id))
4108    };
4109    let marks: Vec<NodeId> = ["commentRangeStart", "commentRangeEnd"]
4110        .into_iter()
4111        .flat_map(|kind| dom.descendants(root, Some(&W::name(kind))))
4112        .filter(|&m| orphan(dom, m))
4113        .collect();
4114    for m in marks {
4115        dom.remove(m);
4116    }
4117    let references: Vec<NodeId> = dom
4118        .descendants(root, Some(&W::comment_reference()))
4119        .into_iter()
4120        .filter(|&r| orphan(dom, r))
4121        .collect();
4122    for reference in references {
4123        let run = dom.parent(reference).filter(|&p| dom.name_is(p, &W::r()));
4124        dom.remove(reference);
4125        if let Some(run) = run
4126            && dom
4127                .elements(run, None)
4128                .iter()
4129                .all(|&c| dom.name_is(c, &W::r_pr()))
4130        {
4131            dom.remove(run);
4132        }
4133    }
4134}
4135
4136// ── Tracked-edit audit ────────────────────────────────────────────────────
4137
4138/// The body's paragraphs followed by every story's (`header1`, ...).
4139fn all_paragraphs(docx: &[u8]) -> Result<Vec<crate::inspect::Paragraph>, ValidateError> {
4140    let mut all = crate::inspect::paragraphs(docx)?;
4141    for story in crate::inspect::stories(docx)? {
4142        all.extend(story.paragraphs);
4143    }
4144    Ok(all)
4145}
4146
4147/// The part a paragraph or change id lives in: the body's (`p3`, `r12`)
4148/// is the main document, any other story's (`header1.p1`, `footnotes.r2`)
4149/// `word/{story}.xml`.
4150fn story_part(id: &str) -> String {
4151    let story = crate::ids::paragraph_place(id)
4152        .map(|(story, _)| story)
4153        .or_else(|| crate::ids::change_id(id).map(|c| c.story));
4154    match story.as_deref().unwrap_or("body") {
4155        "body" | "" => "word/document.xml".to_string(),
4156        story => format!("word/{story}.xml"),
4157    }
4158}
4159
4160/// [`validate.py --original --author`](audit_tracked) without an XSD:
4161/// every visible-text difference between `original` and `edited` must sit
4162/// in a revision by `author`. Rejecting that author's changes must give
4163/// back `original`'s text, body and stories alike; any residue is an
4164/// `UNTRACKED_EDIT` finding at its paragraph id — but not when rejecting
4165/// every change gives the paragraph back, for then its only difference is
4166/// tracked history the `FOREIGN_AUTHOR` findings already name (#1893).
4167/// That comparison is per story: the rejection of a tracked paragraph
4168/// mark merges or splits paragraphs, so a story whose shape changed is
4169/// compared by its text, and a story elsewhere in the document does not
4170/// silence the check here (#1893). Foreign revisions already in
4171/// `original` may remain: only added, altered or removed foreign history
4172/// is a `FOREIGN_AUTHOR` finding, one per logical change as `changes`
4173/// lists it (`r10+11`, #1893), never one per mark.
4174/// Paragraphs are aligned by full text (including deleted text), story
4175/// by story. An untracked paragraph merge or split around another author's
4176/// revisions reports those revisions as new and gone alongside `UNTRACKED_EDIT`.
4177/// Within each paragraph or non-paragraph owner, matching author,
4178/// kind, target, date and move-side groups are compared in document order,
4179/// ignoring revision ids. Split carriers combine only when they touch with
4180/// no visible content or still-present revision between them; a boundary
4181/// explained solely by a missing separator revision is not another change.
4182/// Missing original permission endpoints are reported as
4183/// `PERMISSION_RANGE_DROPPED`, including in headers, footers and notes.
4184/// Another author's comment that is gone, reworded, resolved or reopened,
4185/// and a new comment or reply not signed `author`, is a `FOREIGN_COMMENT`
4186/// finding (`check_foreign_comments`).
4187///
4188/// # Errors
4189///
4190/// [`ValidateError`] when either document cannot be read.
4191pub fn audit_tracked(
4192    original: &[u8],
4193    edited: &[u8],
4194    author: &str,
4195) -> Result<Vec<Finding>, ValidateError> {
4196    let mut out = Vec::new();
4197    check_dropped_permissions(&PartFs::open(original)?, &PartFs::open(edited)?, &mut out);
4198    let filter = ChangeFilter {
4199        authors: Some(vec![author.to_string()]),
4200        ..ChangeFilter::default()
4201    };
4202    let reverted = reject_changes(edited, &filter)?;
4203    check_foreign_revisions(
4204        original,
4205        &reverted,
4206        Some(author),
4207        &foreign_wholes(original, edited),
4208        &mut out,
4209    )?;
4210    check_foreign_comments(original, edited, author, &mut out)?;
4211    // Paragraph-by-paragraph text: the same projection `jubarte text` prints,
4212    // body first, then every header, footer and notes story.
4213    let before = all_paragraphs(original)?;
4214    let after = all_paragraphs(&reverted)?;
4215    if before.len() != after.len() {
4216        out.push(Finding::new(
4217            "UNTRACKED_EDIT",
4218            "word/document.xml",
4219            "",
4220            format!(
4221                "{} paragraphs before, {} after rejecting {author}'s changes",
4222                before.len(),
4223                after.len()
4224            ),
4225        ));
4226        return Ok(as_edits(out));
4227    }
4228    let differing: Vec<usize> = before
4229        .iter()
4230        .zip(&after)
4231        .enumerate()
4232        .filter(|(_, (b, a))| b.text != a.text)
4233        .map(|(i, _)| i)
4234        .collect();
4235    if !differing.is_empty() {
4236        // A paragraph whose only difference is tracked history — the
4237        // foreign changes `check_foreign_revisions` just reported —
4238        // rejects back to the original; an untracked edit does not.
4239        let every = ChangeFilter::default();
4240        let projected_original = all_paragraphs(&reject_changes(original, &every)?)?;
4241        let projected_edited = all_paragraphs(&reject_changes(edited, &every)?)?;
4242        // The paragraphs of each story, and where each of them sits in
4243        // it: the stories pair by name, so a story of one document is
4244        // compared with the same story of the other (#1893).
4245        let before_stories = by_story(&before);
4246        let after_stories = by_story(&after);
4247        let original_stories = by_story(&projected_original);
4248        let edited_stories = by_story(&projected_edited);
4249        let places = story_places(&after);
4250        for i in differing {
4251            let story = story_part(&after[i].id);
4252            let index = places
4253                .get(after[i].id.as_str())
4254                .map(|(_, index)| *index)
4255                .unwrap_or_default();
4256            let ubefore = story_of(&before_stories, &story);
4257            let uafter = story_of(&after_stories, &story);
4258            let po = story_of(&original_stories, &story);
4259            let pe = story_of(&edited_stories, &story);
4260            // The shape of the story decides how its paragraphs pair: with
4261            // the same shape, the index names the same paragraph on both
4262            // sides; with another, the rejection of a tracked paragraph
4263            // mark merged or split paragraphs, and the story's text is
4264            // the comparison — which no paragraph of it escapes: a
4265            // paragraph that was split or joined keeps its text in the
4266            // story's, and a story the two sides split differently reads
4267            // differently, so the finding stands (#1893).
4268            let explained = if po.len() == ubefore.len() && pe.len() == uafter.len() {
4269                po.get(index)
4270                    .zip(pe.get(index))
4271                    .is_some_and(|(b, a)| b.text == a.text)
4272            } else {
4273                story_text(po) == story_text(pe)
4274            };
4275            if !explained {
4276                let (b, a) = (&before[i], &after[i]);
4277                out.push(Finding::new(
4278                    "UNTRACKED_EDIT",
4279                    &story_part(&a.id),
4280                    a.id.clone(),
4281                    format!(
4282                        "{} differs after rejecting {author}'s changes: {:?} vs {:?}",
4283                        a.id, b.text, a.text
4284                    ),
4285                ));
4286            }
4287        }
4288    }
4289    Ok(as_edits(out))
4290}
4291
4292/// The paragraphs of `list` by the story they sit in ([`story_part`]),
4293/// in order.
4294fn by_story(list: &[crate::inspect::Paragraph]) -> Vec<(String, Vec<&crate::inspect::Paragraph>)> {
4295    let mut out: Vec<(String, Vec<&crate::inspect::Paragraph>)> = Vec::new();
4296    for p in list {
4297        let story = story_part(&p.id);
4298        match out.last_mut() {
4299            Some((name, paragraphs)) if *name == story => paragraphs.push(p),
4300            _ => out.push((story, vec![p])),
4301        }
4302    }
4303    out
4304}
4305
4306/// The paragraphs of `stories` that sit in `story`.
4307fn story_of<'a>(
4308    stories: &'a [(String, Vec<&'a crate::inspect::Paragraph>)],
4309    story: &str,
4310) -> &'a [&'a crate::inspect::Paragraph] {
4311    stories
4312        .iter()
4313        .find(|(name, _)| name == story)
4314        .map(|(_, paragraphs)| paragraphs.as_slice())
4315        .unwrap_or_default()
4316}
4317
4318/// The story each paragraph of `list` sits in, and its index in it.
4319fn story_places(list: &[crate::inspect::Paragraph]) -> HashMap<&str, (String, usize)> {
4320    let mut out = HashMap::with_capacity(list.len());
4321    let mut counts: HashMap<String, usize> = HashMap::new();
4322    for p in list {
4323        let story = story_part(&p.id);
4324        let index = counts.entry(story.clone()).or_default();
4325        out.insert(p.id.as_str(), (story, *index));
4326        *index += 1;
4327    }
4328    out
4329}
4330
4331/// The text of a story's paragraphs, one per line.
4332fn story_text(paragraphs: &[&crate::inspect::Paragraph]) -> String {
4333    paragraphs
4334        .iter()
4335        .map(|p| p.text.as_str())
4336        .collect::<Vec<_>>()
4337        .join("\n")
4338}
4339
4340/// The logical-change grouping of the two compared documents, as
4341/// `changes` lists it ([`crate::changes::member_wholes`]): the after
4342/// side's map always comes from `edited`, the file the user reads, whose
4343/// marks keep their ids in the rejected copy. A document whose changes
4344/// will not list keeps per-mark findings (empty maps).
4345fn foreign_wholes(original: &[u8], edited: &[u8]) -> Wholes {
4346    Wholes::new(
4347        crate::changes::member_wholes(original).unwrap_or_default(),
4348        crate::changes::member_wholes(edited).unwrap_or_default(),
4349    )
4350}
4351
4352/// Order-stable alignment. Sparse matches use Hunt--Szymanski with a linear
4353/// link budget. Dense matches use Myers with at most 64 edits, then a
4354/// deterministic forward-only fallback. Memory is O(N + 64²), even for
4355/// repeated text; unlike a multiset no path can match both sides of a swap.
4356fn ordered_pairs<T: Eq + std::hash::Hash>(a: &[T], b: &[T]) -> Vec<(usize, usize)> {
4357    let prefix = a.iter().zip(b).take_while(|(a, b)| a == b).count();
4358    let suffix = a[prefix..]
4359        .iter()
4360        .rev()
4361        .zip(b[prefix..].iter().rev())
4362        .take_while(|(a, b)| a == b)
4363        .count();
4364    let mut positions: HashMap<&T, Vec<usize>> = HashMap::new();
4365    for (j, value) in b.iter().enumerate().take(b.len() - suffix).skip(prefix) {
4366        positions.entry(value).or_default().push(j);
4367    }
4368    let budget = a.len().saturating_add(b.len()).saturating_mul(8);
4369    let matches = a[prefix..a.len() - suffix]
4370        .iter()
4371        .fold(0usize, |count, value| {
4372            count.saturating_add(positions.get(value).map_or(0, Vec::len))
4373        });
4374    if matches > budget {
4375        let middle_a = &a[prefix..a.len() - suffix];
4376        let middle_b = &b[prefix..b.len() - suffix];
4377        let middle = bounded_myers_pairs(middle_a, middle_b).map_or_else(
4378            || {
4379                // Earliest available counterpart, with no backtracking. A
4380                // bounded approximation can add findings, never reorder a
4381                // match or invent an equality that hides altered text.
4382                let mut next = prefix;
4383                let mut pairs = Vec::new();
4384                for (i, value) in a.iter().enumerate().take(a.len() - suffix).skip(prefix) {
4385                    if let Some(indices) = positions.get(value) {
4386                        let at = indices.partition_point(|&j| j < next);
4387                        if let Some(&j) = indices.get(at) {
4388                            pairs.push((i, j));
4389                            next = j + 1;
4390                        }
4391                    }
4392                }
4393                pairs
4394            },
4395            |pairs| {
4396                pairs
4397                    .into_iter()
4398                    .map(|(i, j)| (i + prefix, j + prefix))
4399                    .collect()
4400            },
4401        );
4402        let mut pairs: Vec<_> = (0..prefix).map(|i| (i, i)).collect();
4403        pairs.extend(middle);
4404        pairs.extend((0..suffix).map(|i| (a.len() - suffix + i, b.len() - suffix + i)));
4405        return pairs;
4406    }
4407    let mut links: Vec<(usize, usize, Option<usize>)> = Vec::new();
4408    let mut tails: Vec<usize> = Vec::new();
4409    for (i, value) in a.iter().enumerate().take(a.len() - suffix).skip(prefix) {
4410        for &j in positions.get(value).into_iter().flatten().rev() {
4411            let at = tails.partition_point(|&link| links[link].1 < j);
4412            let previous = at.checked_sub(1).map(|at| tails[at]);
4413            let link = links.len();
4414            links.push((i, j, previous));
4415            if at == tails.len() {
4416                tails.push(link);
4417            } else {
4418                tails[at] = link;
4419            }
4420        }
4421    }
4422    let mut middle = Vec::new();
4423    let mut link = tails.last().copied();
4424    while let Some(at) = link {
4425        let (i, j, previous) = links[at];
4426        middle.push((i, j));
4427        link = previous;
4428    }
4429    let mut pairs: Vec<_> = (0..prefix).map(|i| (i, i)).collect();
4430    pairs.extend(middle.into_iter().rev());
4431    pairs.extend((0..suffix).map(|i| (a.len() - suffix + i, b.len() - suffix + i)));
4432    pairs
4433}
4434
4435/// Myers' shortest edit path, bounded independently of input length. Keeping
4436/// only 65 narrow frontiers bounds both the search and its reconstruction.
4437fn bounded_myers_pairs<T: Eq>(a: &[T], b: &[T]) -> Option<Vec<(usize, usize)>> {
4438    const LIMIT: usize = 64;
4439    const OFFSET: usize = LIMIT + 1;
4440    let mut frontier = vec![0; 2 * LIMIT + 3];
4441    let mut trace = Vec::new();
4442    for depth in 0..=LIMIT {
4443        trace.push(frontier.clone());
4444        for diagonal in (OFFSET - depth..=OFFSET + depth).step_by(2) {
4445            let down = diagonal == OFFSET - depth
4446                || (diagonal != OFFSET + depth && frontier[diagonal - 1] < frontier[diagonal + 1]);
4447            let mut x = if down {
4448                frontier[diagonal + 1]
4449            } else {
4450                frontier[diagonal - 1] + 1
4451            };
4452            let mut y = x + OFFSET - diagonal;
4453            while x < a.len() && y < b.len() && a[x] == b[y] {
4454                x += 1;
4455                y += 1;
4456            }
4457            frontier[diagonal] = x;
4458            if x == a.len() && y == b.len() {
4459                let mut pairs = Vec::new();
4460                for d in (1..=depth).rev() {
4461                    let diagonal = x + OFFSET - y;
4462                    let previous = &trace[d];
4463                    let down = diagonal == OFFSET - d
4464                        || (diagonal != OFFSET + d
4465                            && previous[diagonal - 1] < previous[diagonal + 1]);
4466                    let prior_diagonal = if down { diagonal + 1 } else { diagonal - 1 };
4467                    let prior_x = previous[prior_diagonal];
4468                    let prior_y = prior_x + OFFSET - prior_diagonal;
4469                    while x > prior_x && y > prior_y {
4470                        x -= 1;
4471                        y -= 1;
4472                        pairs.push((x, y));
4473                    }
4474                    x = prior_x;
4475                    y = prior_y;
4476                }
4477                while x > 0 && y > 0 {
4478                    x -= 1;
4479                    y -= 1;
4480                    pairs.push((x, y));
4481                }
4482                pairs.reverse();
4483                return Some(pairs);
4484            }
4485        }
4486    }
4487    None
4488}
4489
4490/// Pair replacement gaps between the LCS anchors. Inserted/deleted tails
4491/// have no counterpart; a changed paragraph between anchors still has one.
4492fn aligned_pairs<T: Eq + std::hash::Hash>(a: &[T], b: &[T]) -> Vec<(usize, usize)> {
4493    let exact = ordered_pairs(a, b);
4494    let mut pairs = Vec::new();
4495    let (mut i, mut j) = (0, 0);
4496    for (x, y) in exact.into_iter().chain(std::iter::once((a.len(), b.len()))) {
4497        pairs.extend((i..x).zip(j..y));
4498        if x < a.len() {
4499            pairs.push((x, y));
4500        }
4501        i = x + 1;
4502        j = y + 1;
4503    }
4504    pairs
4505}
4506
4507#[derive(Clone, Debug, PartialEq, Eq, Hash)]
4508struct ForeignKey {
4509    part: String,
4510    paragraph: Option<(bool, usize)>,
4511    owner: String,
4512    author: Option<String>,
4513    kind: crate::changes::ChangeKind,
4514    target: &'static str,
4515    date: Option<String>,
4516    move_side: Option<crate::changes::MoveSide>,
4517    /// A run formatting change's recorded old properties: fragments of one
4518    /// record compare equal only when they recorded the same formatting.
4519    payload: Option<String>,
4520}
4521
4522struct ForeignGroup<'a> {
4523    key: ForeignKey,
4524    change: &'a Change,
4525    text: String,
4526    start: usize,
4527    end: usize,
4528    relaxed_start: usize,
4529    relaxed_end: usize,
4530    /// The characters a run formatting change covers in its paragraph's
4531    /// text. Rejecting the author's changes restores the paragraph's text,
4532    /// so these compare across the two documents (#1656).
4533    characters: Option<(usize, usize)>,
4534}
4535
4536impl ForeignGroup<'_> {
4537    /// What the comparison matches: the text, and for a run formatting
4538    /// change also where in its paragraph the text is.
4539    fn label(&self) -> String {
4540        match self.characters {
4541            Some((start, end)) => format!("{start}-{end}:{}", self.text),
4542            None => self.text.clone(),
4543        }
4544    }
4545}
4546
4547/// Story-local paragraph identities. Full text includes deleted text, so a
4548/// deletion-only paragraph participates in the alignment too.
4549fn foreign_paragraphs(
4550    before: &[crate::changes::AuditStory],
4551    after: &[crate::changes::AuditStory],
4552) -> HashMap<(String, String), usize> {
4553    let mut identities = HashMap::new();
4554    for original in before {
4555        let Some(edited) = after.iter().find(|s| s.part == original.part) else {
4556            continue;
4557        };
4558        let a: Vec<_> = original.paragraphs.iter().map(|(_, text)| text).collect();
4559        let b: Vec<_> = edited.paragraphs.iter().map(|(_, text)| text).collect();
4560        // An LCS alone can choose the moved paragraph as an anchor in a
4561        // swap. Crossing unique text counterparts establish relocation;
4562        // inserting a new paragraph above history creates no such crossing.
4563        let mut old_positions: HashMap<&String, Vec<usize>> = HashMap::new();
4564        let mut new_positions: HashMap<&String, Vec<usize>> = HashMap::new();
4565        for (i, text) in a.iter().enumerate() {
4566            old_positions.entry(text).or_default().push(i);
4567        }
4568        for (j, text) in b.iter().enumerate() {
4569            new_positions.entry(text).or_default().push(j);
4570        }
4571        let unique: Vec<_> = a
4572            .iter()
4573            .map(|text| {
4574                let old = old_positions.get(text)?;
4575                let new = new_positions.get(text)?;
4576                (old.len() == 1 && new.len() == 1).then_some(new[0])
4577            })
4578            .collect();
4579        let mut crossed = vec![false; a.len()];
4580        let mut maximum = None;
4581        for (i, position) in unique.iter().enumerate() {
4582            if let Some(j) = position {
4583                crossed[i] |= maximum.is_some_and(|max| max > *j);
4584                maximum = Some(maximum.map_or(*j, |max: usize| max.max(*j)));
4585            }
4586        }
4587        let mut minimum = None;
4588        for (i, position) in unique.iter().enumerate().rev() {
4589            if let Some(j) = position {
4590                crossed[i] |= minimum.is_some_and(|min| min < *j);
4591                minimum = Some(minimum.map_or(*j, |min: usize| min.min(*j)));
4592            }
4593        }
4594        for (i, j) in aligned_pairs(&a, &b) {
4595            if !crossed[i] {
4596                identities.insert((edited.part.clone(), edited.paragraphs[j].0.clone()), i);
4597            }
4598        }
4599    }
4600    identities
4601}
4602
4603/// Where each counted character of an edited paragraph sits in the
4604/// original paragraph aligned with it, for the aligned paragraphs whose
4605/// content differs: (original, edited) index pairs, both increasing.
4606type CharacterPairs = HashMap<(String, String), (Vec<(usize, usize)>, usize)>;
4607
4608fn foreign_characters(
4609    before: &[crate::changes::AuditStory],
4610    after: &[crate::changes::AuditStory],
4611    paragraphs: &HashMap<(String, String), usize>,
4612) -> CharacterPairs {
4613    let mut out = HashMap::new();
4614    for edited in after {
4615        let Some(original) = before.iter().find(|s| s.part == edited.part) else {
4616            continue;
4617        };
4618        for ((id, _), content) in edited.paragraphs.iter().zip(&edited.contents) {
4619            let key = (edited.part.clone(), id.clone());
4620            let Some(old) = paragraphs.get(&key).and_then(|&i| original.contents.get(i)) else {
4621                continue;
4622            };
4623            if old != content {
4624                let a: Vec<char> = old.chars().collect();
4625                let b: Vec<char> = content.chars().collect();
4626                out.insert(key, (ordered_pairs(&a, &b), a.len()));
4627            }
4628        }
4629    }
4630    out
4631}
4632
4633/// An edited paragraph's characters `start..end` in the original's
4634/// positions ([`foreign_characters`]): from the first kept character at or
4635/// after `start` to the last kept one before `end`.
4636fn original_characters(
4637    (pairs, length): &(Vec<(usize, usize)>, usize),
4638    (start, end): (usize, usize),
4639) -> (usize, usize) {
4640    let first = pairs.partition_point(|&(_, j)| j < start);
4641    let from = pairs.get(first).map_or(*length, |&(i, _)| i);
4642    let last = pairs.partition_point(|&(_, j)| j < end);
4643    let to = last.checked_sub(1).map_or(0, |k| pairs[k].0 + 1);
4644    (from, to.max(from))
4645}
4646
4647/// Keep each carrier for attribution. Windows may combine touching text,
4648/// but an altered window must still name the carrier that actually changed.
4649fn foreign_revisions<'a>(
4650    stories: &'a [crate::changes::AuditStory],
4651    paragraphs: &HashMap<(String, String), usize>,
4652    characters: &CharacterPairs,
4653    edited: bool,
4654) -> Vec<ForeignGroup<'a>> {
4655    let mut out: Vec<ForeignGroup<'a>> = Vec::new();
4656    for story in stories {
4657        let paragraph_indices: HashMap<_, _> = story
4658            .paragraphs
4659            .iter()
4660            .enumerate()
4661            .map(|(i, (id, _))| (id.as_str(), i))
4662            .collect();
4663        for located in &story.changes {
4664            let c = &located.change;
4665            let paragraph = c.paragraph.as_ref().map(|id| {
4666                if edited && let Some(&i) = paragraphs.get(&(story.part.clone(), id.clone())) {
4667                    (false, i)
4668                } else {
4669                    (
4670                        edited,
4671                        paragraph_indices
4672                            .get(id.as_str())
4673                            .copied()
4674                            .unwrap_or(usize::MAX),
4675                    )
4676                }
4677            });
4678            let key = ForeignKey {
4679                part: story.part.clone(),
4680                paragraph,
4681                owner: located.owner.clone(),
4682                author: c.author.clone(),
4683                kind: c.kind,
4684                target: c.target,
4685                date: c.date.clone(),
4686                move_side: c.move_side,
4687                payload: located.payload.clone(),
4688            };
4689            out.push(ForeignGroup {
4690                key,
4691                change: c,
4692                text: c.text.clone(),
4693                start: located.start,
4694                end: located.end,
4695                relaxed_start: located.start,
4696                relaxed_end: located.end,
4697                characters: located.characters.map(|span| {
4698                    match c
4699                        .paragraph
4700                        .as_ref()
4701                        .filter(|_| edited)
4702                        .and_then(|id| characters.get(&(story.part.clone(), id.clone())))
4703                    {
4704                        Some(pairs) => original_characters(pairs, span),
4705                        None => span,
4706                    }
4707                }),
4708            });
4709        }
4710    }
4711    out
4712}
4713
4714/// Remove only the document spans of revisions with no sequence counterpart.
4715/// A still-present separator, even with changed text, remains a boundary.
4716fn relax_foreign_boundaries(
4717    groups: &mut [ForeignGroup<'_>],
4718    present: &[bool],
4719    mut missing: HashMap<String, Vec<(usize, usize)>>,
4720) {
4721    for (group, &present) in groups.iter().zip(present) {
4722        if !present {
4723            missing
4724                .entry(group.key.part.clone())
4725                .or_default()
4726                .push((group.start, group.end));
4727        }
4728    }
4729    let mut ranges: HashMap<String, Vec<(usize, usize, usize)>> = HashMap::new();
4730    for (part, mut spans) in missing {
4731        spans.sort_unstable();
4732        let mut merged: Vec<(usize, usize)> = Vec::new();
4733        for (start, end) in spans {
4734            if let Some(last) = merged.last_mut()
4735                && start <= last.1
4736            {
4737                last.1 = last.1.max(end);
4738            } else {
4739                merged.push((start, end));
4740            }
4741        }
4742        let mut removed = 0;
4743        ranges.insert(
4744            part.to_string(),
4745            merged
4746                .into_iter()
4747                .map(|(start, end)| {
4748                    let prior = removed;
4749                    removed += end - start;
4750                    (start, end, prior)
4751                })
4752                .collect(),
4753        );
4754    }
4755    for group in groups {
4756        let Some(spans) = ranges.get(&group.key.part) else {
4757            continue;
4758        };
4759        let position = |pos: usize| {
4760            let index = spans.partition_point(|&(start, _, _)| start < pos);
4761            if index == 0 {
4762                return pos;
4763            }
4764            let (start, end, prior) = spans[index - 1];
4765            pos - prior - (pos.min(end) - start)
4766        };
4767        group.relaxed_start = position(group.start);
4768        group.relaxed_end = position(group.end);
4769    }
4770}
4771
4772/// A comparison window may lose boundaries only where a missing separator
4773/// explains them. Retain every carrier for attribution if the text differs.
4774/// The fragments of a run formatting change join only where their
4775/// characters touch, and the window keeps where its characters are.
4776fn foreign_window(groups: &[ForeignGroup<'_>], indices: &[usize]) -> Vec<(Vec<usize>, String)> {
4777    // Carriers, joined text and, for run formatting, joined characters.
4778    type Window = (Vec<usize>, String, Option<(usize, usize)>);
4779    let mut windows: Vec<Window> = Vec::new();
4780    let mut previous = None;
4781    for &index in indices {
4782        let group = &groups[index];
4783        let touches = |p: usize| match (groups[p].characters, group.characters) {
4784            (Some((_, end)), Some((start, _))) => end == start,
4785            (None, None) => groups[p].relaxed_end == group.relaxed_start,
4786            _ => false,
4787        };
4788        if previous.is_some_and(touches)
4789            && let Some((carriers, text, characters)) = windows.last_mut()
4790        {
4791            carriers.push(index);
4792            text.push_str(&group.text);
4793            if let (Some(window), Some((_, end))) = (characters, group.characters) {
4794                window.1 = end;
4795            }
4796        } else {
4797            windows.push((vec![index], group.text.clone(), group.characters));
4798        }
4799        previous = Some(index);
4800    }
4801    windows
4802        .into_iter()
4803        .map(|(carriers, text, characters)| match characters {
4804            Some((start, end)) => (carriers, format!("{start}-{end}:{text}")),
4805            None => (carriers, text),
4806        })
4807        .collect()
4808}
4809
4810/// The states a `FOREIGN_AUTHOR` finding names a change in: it appeared,
4811/// its text changed, or the original's is no longer there. The messages
4812/// end in them; [`foreign_state`] reads them back.
4813const FOREIGN_GONE: &str = "gone";
4814const FOREIGN_NEW: &str = "is new";
4815const FOREIGN_ALTERED: &str = "differs from the original";
4816
4817fn foreign_finding(group: &ForeignGroup<'_>, state: &str) -> Finding {
4818    let author = group.change.author.as_deref().unwrap_or("<no author>");
4819    foreign_message(&group.key.part, &group.change.id, author, state)
4820}
4821
4822/// The `FOREIGN_AUTHOR` finding of change `id` — one mark, or the
4823/// composite id `changes` prints for the marks of one logical change
4824/// (`r10+11`) — by `author`, in `state` (one of the `FOREIGN_*`
4825/// states).
4826fn foreign_message(part: &str, id: &str, author: &str, state: &str) -> Finding {
4827    let message = if state == FOREIGN_GONE {
4828        format!("{author}'s {id} in the original is gone")
4829    } else {
4830        format!("{id} by {author} {state}")
4831    };
4832    Finding::new("FOREIGN_AUTHOR", part, "", message)
4833}
4834
4835/// The state [`foreign_message`] wrote at the end of `finding`'s message.
4836fn foreign_state(finding: &Finding) -> &'static str {
4837    if finding.message.ends_with(FOREIGN_NEW) {
4838        FOREIGN_NEW
4839    } else if finding.message.ends_with(FOREIGN_ALTERED) {
4840        FOREIGN_ALTERED
4841    } else {
4842        FOREIGN_GONE
4843    }
4844}
4845
4846/// The change id and author a `FOREIGN_AUTHOR` finding of the `is new`
4847/// state names: `r10+11 by GiantCo is new`. Who signed new markup (#1893).
4848fn new_foreign(finding: &Finding) -> Option<(&str, &str)> {
4849    let rest = finding
4850        .message
4851        .strip_suffix(FOREIGN_NEW)?
4852        .strip_suffix(' ')?;
4853    let (id, by) = rest.split_once(' ')?;
4854    by.strip_prefix("by ").map(|author| (id, author))
4855}
4856
4857type ForeignSpans = HashMap<String, Vec<(usize, usize)>>;
4858type ForeignFindings = Vec<(bool, usize, Finding)>;
4859
4860/// The marks of each logical change, as `changes` groups them
4861/// ([`crate::changes::member_wholes`]): one map per compared document.
4862/// `after`'s is read from the edited document — the file the user reads —
4863/// even when the findings' after side is its rejected copy, whose marks
4864/// keep their ids.
4865#[derive(Default)]
4866struct Wholes {
4867    /// Each mark's id → its logical change's id (`r10` → `r10+11`).
4868    /// The first map is the edited side, the second the original's.
4869    whole: [HashMap<String, String>; 2],
4870    /// How many marks each logical change names, per side.
4871    marks: [HashMap<String, usize>; 2],
4872}
4873
4874impl Wholes {
4875    fn new(before: HashMap<String, String>, after: HashMap<String, String>) -> Self {
4876        let counts = |whole: &HashMap<String, String>| {
4877            let mut out: HashMap<String, usize> = HashMap::with_capacity(whole.len());
4878            for id in whole.values() {
4879                *out.entry(id.clone()).or_default() += 1;
4880            }
4881            out
4882        };
4883        Wholes {
4884            marks: [counts(&after), counts(&before)],
4885            whole: [after, before],
4886        }
4887    }
4888
4889    /// The change `mark` belongs to, or `mark` itself when `changes`
4890    /// lists it alone.
4891    fn whole<'a>(&'a self, original: bool, mark: &'a str) -> &'a str {
4892        self.whole[usize::from(original)]
4893            .get(mark)
4894            .map_or(mark, String::as_str)
4895    }
4896
4897    /// How many marks the change `whole` names on that side: a change
4898    /// the listing does not group has none.
4899    fn marks(&self, original: bool, whole: &str) -> usize {
4900        self.marks[usize::from(original)]
4901            .get(whole)
4902            .copied()
4903            .unwrap_or(0)
4904    }
4905}
4906
4907/// One finding per logical change (#1893): findings for the marks of one
4908/// change, on one side, in one state, that together cover the whole
4909/// change, print as one finding naming the change's id as `changes`
4910/// prints it (`r10+11 by GiantCo is new`). Findings for some of a change's
4911/// marks keep their mark's id, so a surviving mark is never named gone.
4912/// The findings are grouped by the change they belong to, not by their
4913/// place: another author's text between two marks of one change leaves
4914/// them one change (#1893).
4915fn whole_changes(
4916    findings: ForeignFindings,
4917    before: &[ForeignGroup<'_>],
4918    after: &[ForeignGroup<'_>],
4919    wholes: &Wholes,
4920) -> Vec<Finding> {
4921    let group_of = |original: bool, index: usize| -> &ForeignGroup<'_> {
4922        if original {
4923            &before[index]
4924        } else {
4925            &after[index]
4926        }
4927    };
4928    /// The change a finding belongs to, with the side and the state it
4929    /// names it in.
4930    type Change = (bool, &'static str, String);
4931    let key_of = |finding: &(bool, usize, Finding)| -> Change {
4932        let (original, index, f) = finding;
4933        (
4934            *original,
4935            foreign_state(f),
4936            wholes
4937                .whole(*original, &group_of(*original, *index).change.id)
4938                .to_string(),
4939        )
4940    };
4941    // The changes in the order they first appear, each with its findings.
4942    let mut order: Vec<Change> = Vec::new();
4943    let mut groups: HashMap<Change, Vec<(bool, usize, Finding)>> = HashMap::new();
4944    let count = findings.len();
4945    for finding in findings {
4946        let key = key_of(&finding);
4947        if !groups.contains_key(&key) {
4948            order.push(key.clone());
4949        }
4950        groups.entry(key).or_default().push(finding);
4951    }
4952    let mut out = Vec::with_capacity(count);
4953    for key in order {
4954        let (original, state, whole) = &key;
4955        let members = groups.remove(&key).unwrap_or_default();
4956        if members.len() == wholes.marks(*original, whole) {
4957            // The findings cover the whole change: one finding names it.
4958            let (_, index, _) = &members[0];
4959            let group = group_of(*original, *index);
4960            out.push(foreign_message(
4961                &group.key.part,
4962                whole,
4963                group.change.author.as_deref().unwrap_or("<no author>"),
4964                state,
4965            ));
4966        } else {
4967            out.extend(members.into_iter().map(|(_, _, finding)| finding));
4968        }
4969    }
4970    out
4971}
4972
4973/// Match omitted markers within aligned paragraphs, ignoring revision ids.
4974/// Retained slots remain boundaries. Only absent slots enter the span union.
4975fn missing_foreign_markers(
4976    before: &[crate::changes::AuditStory],
4977    after: &[crate::changes::AuditStory],
4978    paragraphs: &HashMap<(String, String), usize>,
4979) -> (ForeignSpans, ForeignSpans) {
4980    let keys = |stories: &[crate::changes::AuditStory], edited: bool| {
4981        stories
4982            .iter()
4983            .flat_map(|story| {
4984                story.markers.iter().map(move |marker| {
4985                    let paragraph = marker.paragraph.map(|i| {
4986                        if edited
4987                            && let Some(&index) =
4988                                paragraphs.get(&(story.part.clone(), story.paragraphs[i].0.clone()))
4989                        {
4990                            (false, index)
4991                        } else {
4992                            (edited, i)
4993                        }
4994                    });
4995                    (
4996                        story.part.clone(),
4997                        paragraph,
4998                        marker.owner.clone(),
4999                        marker.kind.clone(),
5000                    )
5001                })
5002            })
5003            .collect::<Vec<_>>()
5004    };
5005    let a = keys(before, false);
5006    let b = keys(after, true);
5007    let pairs = ordered_pairs(&a, &b);
5008    let present_a: HashSet<_> = pairs.iter().map(|&(i, _)| i).collect();
5009    let present_b: HashSet<_> = pairs.iter().map(|&(_, j)| j).collect();
5010    let missing = |stories: &[crate::changes::AuditStory], present: &HashSet<usize>| {
5011        let mut spans: ForeignSpans = HashMap::new();
5012        for (i, (story, marker)) in stories
5013            .iter()
5014            .flat_map(|story| story.markers.iter().map(move |marker| (story, marker)))
5015            .enumerate()
5016        {
5017            if !present.contains(&i) {
5018                spans
5019                    .entry(story.part.clone())
5020                    .or_default()
5021                    .push((marker.start, marker.start + 1));
5022            }
5023        }
5024        spans
5025    };
5026    (missing(before, &present_a), missing(after, &present_b))
5027}
5028
5029/// Exact carriers within an unequal combined window precede replacements.
5030/// No finding is allowed to borrow an unchanged neighbor's id.
5031fn report_foreign_carriers(
5032    before: &[ForeignGroup<'_>],
5033    after: &[ForeignGroup<'_>],
5034    old: &[usize],
5035    new: &[usize],
5036    findings: &mut ForeignFindings,
5037) {
5038    let a: Vec<_> = old.iter().map(|&i| before[i].label()).collect();
5039    let b: Vec<_> = new.iter().map(|&i| after[i].label()).collect();
5040    let (mut i, mut j) = (0, 0);
5041    for (x, y) in ordered_pairs(&a, &b)
5042        .into_iter()
5043        .chain(std::iter::once((a.len(), b.len())))
5044    {
5045        let paired = (x - i).min(y - j);
5046        for (offset, &index) in new[j..y].iter().enumerate() {
5047            let state = if offset < paired {
5048                FOREIGN_ALTERED
5049            } else {
5050                FOREIGN_NEW
5051            };
5052            findings.push((false, index, foreign_finding(&after[index], state)));
5053        }
5054        for &index in &old[i + paired..x] {
5055            findings.push((true, index, foreign_finding(&before[index], FOREIGN_GONE)));
5056        }
5057        i = x + 1;
5058        j = y + 1;
5059    }
5060}
5061
5062fn check_foreign_revisions(
5063    original: &[u8],
5064    after: &[u8],
5065    skip: Option<&str>,
5066    wholes: &Wholes,
5067    out: &mut Vec<Finding>,
5068) -> Result<(), ValidateError> {
5069    let before_stories = crate::changes::audit_stories(original)?;
5070    let after_stories = crate::changes::audit_stories(after)?;
5071    let paragraphs = foreign_paragraphs(&before_stories, &after_stories);
5072    let characters = foreign_characters(&before_stories, &after_stories, &paragraphs);
5073    let mut before = foreign_revisions(&before_stories, &paragraphs, &characters, false);
5074    let mut after_groups = foreign_revisions(&after_stories, &paragraphs, &characters, true);
5075    let mut by_key: HashMap<ForeignKey, (Vec<usize>, Vec<usize>)> = HashMap::new();
5076    for (i, group) in before.iter().enumerate() {
5077        by_key.entry(group.key.clone()).or_default().0.push(i);
5078    }
5079    for (i, group) in after_groups.iter().enumerate() {
5080        by_key.entry(group.key.clone()).or_default().1.push(i);
5081    }
5082    let mut before_present = vec![false; before.len()];
5083    let mut after_present = vec![false; after_groups.len()];
5084    for (old, new) in by_key.values() {
5085        let a: Vec<_> = old.iter().map(|&i| before[i].label()).collect();
5086        let b: Vec<_> = new.iter().map(|&i| after_groups[i].label()).collect();
5087        for (i, j) in aligned_pairs(&a, &b) {
5088            before_present[old[i]] = true;
5089            after_present[new[j]] = true;
5090        }
5091    }
5092    let (old_markers, new_markers) =
5093        missing_foreign_markers(&before_stories, &after_stories, &paragraphs);
5094    relax_foreign_boundaries(&mut before, &before_present, old_markers);
5095    relax_foreign_boundaries(&mut after_groups, &after_present, new_markers);
5096    let mut findings = Vec::new();
5097    for (key, (old, new)) in &by_key {
5098        // Only an author the run was given is skipped: a revision that
5099        // names none is another author's (#1893).
5100        if let Some(skip) = skip
5101            && key.author.as_deref() == Some(skip)
5102        {
5103            continue;
5104        }
5105        let a: Vec<_> = old.iter().map(|&i| before[i].label()).collect();
5106        let b: Vec<_> = new.iter().map(|&i| after_groups[i].label()).collect();
5107        let (mut i, mut j) = (0, 0);
5108        for (x, y) in ordered_pairs(&a, &b)
5109            .into_iter()
5110            .chain(std::iter::once((a.len(), b.len())))
5111        {
5112            let left = foreign_window(&before, &old[i..x]);
5113            let right = foreign_window(&after_groups, &new[j..y]);
5114            let left_text: Vec<_> = left.iter().map(|(_, text)| text).collect();
5115            let right_text: Vec<_> = right.iter().map(|(_, text)| text).collect();
5116            let (mut p, mut q) = (0, 0);
5117            for (u, v) in ordered_pairs(&left_text, &right_text)
5118                .into_iter()
5119                .chain(std::iter::once((left.len(), right.len())))
5120            {
5121                let old_carriers: Vec<_> = left[p..u]
5122                    .iter()
5123                    .flat_map(|(indices, _)| indices.iter().copied())
5124                    .collect();
5125                let new_carriers: Vec<_> = right[q..v]
5126                    .iter()
5127                    .flat_map(|(indices, _)| indices.iter().copied())
5128                    .collect();
5129                report_foreign_carriers(
5130                    &before,
5131                    &after_groups,
5132                    &old_carriers,
5133                    &new_carriers,
5134                    &mut findings,
5135                );
5136                p = u + 1;
5137                q = v + 1;
5138            }
5139            i = x + 1;
5140            j = y + 1;
5141        }
5142    }
5143    findings.sort_by_key(|(original, index, _)| (*original, *index));
5144    out.extend(whole_changes(findings, &before, &after_groups, wholes));
5145    Ok(())
5146}
5147
5148/// Permission exceptions are edit fidelity, not Word validity. Check both
5149/// endpoints by id in every XML part, so dropping only one is visible too.
5150fn check_dropped_permissions(original: &PartFs, edited: &PartFs, out: &mut Vec<Finding>) {
5151    for part in xml_parts(original) {
5152        if original
5153            .part_string(&part)
5154            .is_none_or(|xml| !xml.contains("permStart") && !xml.contains("permEnd"))
5155        {
5156            continue;
5157        }
5158        let Some((before, root)) = parse_part(original, &part) else {
5159            continue;
5160        };
5161        let after = parse_part(edited, &part);
5162        for kind in ["permStart", "permEnd"] {
5163            let name = W::name(kind);
5164            let mut remaining: HashMap<String, usize> = HashMap::new();
5165            if let Some((dom, root)) = &after {
5166                for n in dom.descendants(*root, Some(&name)) {
5167                    if let Some(id) = dom.attribute(n, &W::id()) {
5168                        *remaining.entry(id.to_string()).or_default() += 1;
5169                    }
5170                }
5171            }
5172            for n in before.descendants(root, Some(&name)) {
5173                let Some(id) = before.attribute(n, &W::id()) else {
5174                    continue;
5175                };
5176                if let Some(count) = remaining.get_mut(id)
5177                    && *count > 0
5178                {
5179                    *count -= 1;
5180                    continue;
5181                }
5182                out.push(Finding::new(
5183                    "PERMISSION_RANGE_DROPPED",
5184                    &part,
5185                    element_path(&before, n),
5186                    format!("original w:{kind} with w:id={id} is missing from the edited file"),
5187                ));
5188            }
5189        }
5190    }
5191}
5192
5193/// The comments of `docx`, as [`audit_tracked`] reads them.
5194fn comments_of(docx: &[u8]) -> Result<Vec<crate::comments::CommentRecord>, ValidateError> {
5195    use crate::comments::CommentError;
5196    crate::comments::list_comments(docx).map_err(|e| match e {
5197        CommentError::Admission(e) => ValidateError::Refused(e),
5198        CommentError::Package(m) => ValidateError::Package(m),
5199    })
5200}
5201
5202/// How `before`'s and `after`'s comments pair, first by id (with the same
5203/// author and date), then in order by author, date and text, then by
5204/// author and date: another tool may renumber them. The booleans mark
5205/// each side's paired comments; `pairs` holds the pairs, `before`'s order.
5206fn comment_pairs(
5207    before: &[crate::comments::CommentRecord],
5208    after: &[crate::comments::CommentRecord],
5209) -> (Vec<(usize, usize)>, Vec<bool>, Vec<bool>) {
5210    let mut pairs: Vec<(usize, usize)> = Vec::new();
5211    let mut paired_after = vec![false; after.len()];
5212    let mut paired_before = vec![false; before.len()];
5213    /// One pass: each unpaired comment of `before`, in order, takes the
5214    /// first unpaired comment of `after` with its key. Each key's
5215    /// candidates queue in document order and leave the queue once taken,
5216    /// so comments sharing an author and a date (or no date) cost no
5217    /// rescan: the pass is linear (#4374424613).
5218    fn pair_by<'a, K: Eq + std::hash::Hash>(
5219        before: &'a [crate::comments::CommentRecord],
5220        after: &'a [crate::comments::CommentRecord],
5221        paired_before: &mut [bool],
5222        paired_after: &mut [bool],
5223        pairs: &mut Vec<(usize, usize)>,
5224        key: impl Fn(&'a crate::comments::CommentRecord) -> K,
5225    ) {
5226        let mut queues: std::collections::HashMap<K, std::collections::VecDeque<usize>> =
5227            std::collections::HashMap::with_capacity(after.len());
5228        for (j, a) in after.iter().enumerate() {
5229            if !paired_after[j] {
5230                queues.entry(key(a)).or_default().push_back(j);
5231            }
5232        }
5233        for (i, b) in before.iter().enumerate() {
5234            if paired_before[i] {
5235                continue;
5236            }
5237            if let Some(j) = queues
5238                .get_mut(&key(b))
5239                .and_then(std::collections::VecDeque::pop_front)
5240            {
5241                paired_before[i] = true;
5242                paired_after[j] = true;
5243                pairs.push((i, j));
5244            }
5245        }
5246    }
5247    // Every pass needs the same author and date; the first also the same
5248    // id, the second the same text.
5249    let (pb, pa) = (&mut paired_before, &mut paired_after);
5250    pair_by(before, after, pb, pa, &mut pairs, |c| {
5251        (c.author.as_str(), c.date.as_deref(), c.id)
5252    });
5253    pair_by(before, after, pb, pa, &mut pairs, |c| {
5254        (c.author.as_str(), c.date.as_deref(), c.text.as_str())
5255    });
5256    pair_by(before, after, pb, pa, &mut pairs, |c| {
5257        (c.author.as_str(), c.date.as_deref())
5258    });
5259    (pairs, paired_before, paired_after)
5260}
5261
5262/// [`audit_tracked`]'s findings belong to the `edits` set and fail a run.
5263/// Comments `author` may not have changed (#1846). `original`'s comments
5264/// are paired with `edited`'s, first by id (with the same author and
5265/// date), then in order by author, date and text, then by author and date
5266/// ([`comment_pairs`]). Another author's comment (one that names no author
5267/// included) that has no pair is gone; a pair whose text differs was
5268/// reworded; a thread root whose resolved state differs was resolved or
5269/// reopened (a reply's state follows its root, so resolving one's own
5270/// thread changes no one else's). An `edited` comment with no pair that is
5271/// not signed `author` is new. Each finding's message starts with the
5272/// comment's id, `edited`'s where it has one.
5273fn check_foreign_comments(
5274    original: &[u8],
5275    edited: &[u8],
5276    author: &str,
5277    out: &mut Vec<Finding>,
5278) -> Result<(), ValidateError> {
5279    use crate::comments::CommentRecord;
5280    let before = comments_of(original)?;
5281    let after = comments_of(edited)?;
5282    let (mut pairs, paired_before, paired_after) = comment_pairs(&before, &after);
5283    let whose = |c: &CommentRecord| {
5284        if c.author.is_empty() {
5285            format!("c{}, which names no author,", c.id)
5286        } else {
5287            format!("c{} by {:?}", c.id, c.author)
5288        }
5289    };
5290    let instead = |c: &CommentRecord, doing: &str| {
5291        let them = if c.author.is_empty() {
5292            "it"
5293        } else {
5294            "their comment"
5295        };
5296        format!("reply to {them} instead of {doing}")
5297    };
5298    let mut findings: Vec<(usize, String)> = Vec::new();
5299    for (i, b) in before.iter().enumerate() {
5300        if !paired_before[i] && b.author != author {
5301            findings.push((
5302                i,
5303                format!("{} is gone: {}", whose(b), instead(b, "deleting it")),
5304            ));
5305        }
5306    }
5307    pairs.sort_unstable();
5308    for &(i, j) in &pairs {
5309        let (b, a) = (&before[i], &after[j]);
5310        if b.author == author {
5311            continue;
5312        }
5313        if b.text != a.text {
5314            findings.push((
5315                i,
5316                format!(
5317                    "{} was reworded: {}",
5318                    whose(a),
5319                    instead(a, "changing its words")
5320                ),
5321            ));
5322        }
5323        if b.parent.is_none() && b.done != a.done {
5324            let (done, doing) = if a.done {
5325                ("resolved", "resolving it")
5326            } else {
5327                ("reopened", "reopening it")
5328            };
5329            findings.push((i, format!("{} was {done}: {}", whose(a), instead(a, doing))));
5330        }
5331    }
5332    findings.sort_by_key(|(i, _)| *i);
5333    out.extend(
5334        findings
5335            .into_iter()
5336            .map(|(_, message)| Finding::new("FOREIGN_COMMENT", "word/comments.xml", "", message)),
5337    );
5338    for (j, a) in after.iter().enumerate() {
5339        if !paired_after[j] && a.author != author {
5340            let signed = if a.author.is_empty() {
5341                "names no author".to_string()
5342            } else {
5343                format!("signed {:?}", a.author)
5344            };
5345            out.push(Finding::new(
5346                "FOREIGN_COMMENT",
5347                "word/comments.xml",
5348                "",
5349                format!("c{} is new and {signed}, not {author:?}", a.id),
5350            ));
5351        }
5352    }
5353    Ok(())
5354}
5355
5356fn as_edits(mut findings: Vec<Finding>) -> Vec<Finding> {
5357    for f in &mut findings {
5358        f.set = "edits".to_string();
5359        f.severity = "error".to_string();
5360    }
5361    findings
5362}
5363
5364#[cfg(test)]
5365#[cfg_attr(all(coverage_nightly, test), coverage(off))]
5366mod validation_boundary_tests {
5367    use super::*;
5368
5369    fn pkg() -> PartFs {
5370        PartFs::open(include_bytes!(
5371            "../../../tests/fixtures/redline/original.docx"
5372        ))
5373        .unwrap()
5374    }
5375
5376    fn xml(dom: &mut Dom, body: &str) -> NodeId {
5377        let doc = dom.parse_xdocument(&format!(
5378            r#"<w:document xmlns:w="{}" xmlns:mc="{}"><w:body>{body}</w:body></w:document>"#,
5379            W::URI,
5380            MC::URI
5381        ));
5382        dom.root(doc).unwrap()
5383    }
5384
5385    #[test]
5386    fn metadata_ids_check_width_hex_digits_and_the_word_boundary_independently() {
5387        for (value, bound, expected) in [
5388            ("12345678", true, None),
5389            ("abcdef01", false, None),
5390            ("7FFFFFFF", true, None),
5391            // Word opens a comment paraId at 0x80000000 (probe h07) and
5392            // hangs on one that is not hexadecimal (h08, 2026-10-10).
5393            ("80000000", true, Some("outside Word")),
5394            ("80000000", false, None),
5395            // Seven digits open (k06); nine are refused (k07, 2026-10-10).
5396            ("1234567", true, None),
5397            ("1", false, None),
5398            ("", true, Some("not a hexadecimal id")),
5399            ("123456789", false, Some("not a hexadecimal id")),
5400            ("1234567z", true, Some("not a hexadecimal id")),
5401            ("é234567", false, Some("not a hexadecimal id")),
5402        ] {
5403            let mut findings = Vec::new();
5404            check_hex_id("test", value, bound, "part", &mut findings);
5405            assert_eq!(findings.len(), usize::from(expected.is_some()), "{value}");
5406            if let Some(message) = expected {
5407                let refused = message == "not a hexadecimal id";
5408                assert_eq!(
5409                    findings[0].code,
5410                    if refused {
5411                        "COMMENT_PARTS_INCONSISTENT"
5412                    } else {
5413                        "COMMENT_METADATA_MISMATCH"
5414                    }
5415                );
5416                assert!(findings[0].message.contains(message));
5417                assert_eq!(findings[0].word_fatal, refused, "{value}");
5418            }
5419        }
5420    }
5421
5422    #[test]
5423    fn paragraph_ids_ignore_invalid_or_unterminated_values_and_find_both_attributes() {
5424        let source = r#"w14:paraId="7fffffff" w14:textId="80000000" w14:paraId="ZZZZZZZZ" w14:textId="00000000" w14:paraId="FFFFFFFF" w14:textId="unfinished"#;
5425        assert_eq!(
5426            para_id_values(source),
5427            vec![0x7fffffff, u32::MAX, 0x80000000, 0]
5428        );
5429        assert_eq!(
5430            out_of_range_para_ids(source),
5431            vec![
5432                ("w14:paraId=\"", "FFFFFFFF".into()),
5433                ("w14:textId=\"", "80000000".into()),
5434                ("w14:textId=\"", "00000000".into())
5435            ]
5436        );
5437    }
5438
5439    #[test]
5440    fn deletion_scope_stops_at_textboxes_and_covers_nested_insertions() {
5441        let mut dom = Dom::new();
5442        let root = xml(
5443            &mut dom,
5444            "<w:p><w:del><w:r><w:t>deleted</w:t></w:r><w:ins><w:r><w:t>inserted</w:t></w:r></w:ins><w:r><w:txbxContent><w:p><w:r><w:delText>uncovered</w:delText></w:r></w:p></w:txbxContent></w:r></w:del></w:p><w:p><w:moveFrom><w:r><w:delText>moved</w:delText></w:r></w:moveFrom><w:r><w:delText>stranded</w:delText></w:r></w:p>",
5445        );
5446        let texts = dom.descendants(root, Some(&W::del_text()));
5447        assert!(!covered_by_deletion(&dom, texts[0]));
5448        assert!(covered_by_deletion(&dom, texts[1]));
5449        assert!(!covered_by_deletion(&dom, texts[2]));
5450        fix_deleted_text(&mut dom, root);
5451        let live = dom
5452            .descendants(root, Some(&W::t()))
5453            .into_iter()
5454            .map(|n| dom.value(n))
5455            .collect::<Vec<_>>();
5456        assert_eq!(live, ["uncovered", "moved", "stranded"]);
5457        let deleted = dom
5458            .descendants(root, Some(&W::del_text()))
5459            .into_iter()
5460            .map(|n| dom.value(n))
5461            .collect::<Vec<_>>();
5462        assert_eq!(deleted, ["deleted", "inserted"]);
5463    }
5464
5465    #[test]
5466    fn bookmarks_are_forbidden_in_each_single_value_control_but_allowed_in_rich_text() {
5467        for control in SINGLE_VALUE_CONTROLS.into_iter().chain(["richText"]) {
5468            let mut dom = Dom::new();
5469            let root = xml(
5470                &mut dom,
5471                &format!(
5472                    "<w:sdt><w:sdtPr><w:{control}/></w:sdtPr><w:sdtContent><w:p><w:bookmarkStart w:id=\"1\"/><w:r><w:t>value</w:t></w:r><w:bookmarkEnd w:id=\"1\"/></w:p></w:sdtContent></w:sdt><w:p><w:bookmarkStart w:id=\"2\"/></w:p>"
5473                ),
5474            );
5475            let forbidden = bookmarks_in_single_value_controls(&dom, root);
5476            assert_eq!(forbidden.len(), if control == "richText" { 0 } else { 2 });
5477            drop_bookmarks_in_single_value_controls(&mut dom, root);
5478            assert_eq!(
5479                dom.descendants(root, Some(&W::bookmark_start())).len(),
5480                if control == "richText" { 2 } else { 1 }
5481            );
5482            assert_eq!(dom.value(root), "value");
5483        }
5484    }
5485
5486    #[test]
5487    fn comment_auxiliary_parts_reject_missing_duplicate_and_unmatched_ids() {
5488        let mut pkg = pkg();
5489        let expected = HashSet::from(["11111111".to_string()]);
5490        pkg.set_part("word/commentsExtended.xml", br#"<root><row/><row paraId="11111111" paraIdParent="11111111"/><row paraId="11111111"/><row paraId="22222222"/></root>"#.to_vec());
5491        let mut out = Vec::new();
5492        let graph = check_comments_extended(&pkg, &expected, &mut out).unwrap();
5493        assert_eq!(
5494            graph.keys,
5495            HashSet::from(["11111111".into(), "22222222".into()])
5496        );
5497        assert_eq!(out.len(), 4);
5498        assert!(out.iter().any(|f| f.code == "COMMENT_PARENT_CYCLE"));
5499        assert!(out.iter().any(|f| f.message.contains("has no paraId")));
5500        assert!(out.iter().any(|f| f.message.contains("duplicate")));
5501        assert!(out.iter().any(|f| f.message.contains("no matching")));
5502        pkg.set_part("word/commentsIds.xml", br#"<root><row/><row paraId="11111111"/><row paraId="11111111" durableId="22222222"/><row paraId="33333333" durableId="22222222"/></root>"#.to_vec());
5503        out.clear();
5504        assert_eq!(
5505            check_comments_ids(&pkg, &expected, &mut out),
5506            Some(HashSet::from(["22222222".into()]))
5507        );
5508        assert_eq!(out.len(), 5);
5509        pkg.set_part(
5510            "word/commentsExtensible.xml",
5511            br#"<root><row/><row durableId="22222222"/><row durableId="22222222"/></root>"#
5512                .to_vec(),
5513        );
5514        out.clear();
5515        check_comments_extensible(&pkg, Some(&HashSet::from(["22222222".into()])), &mut out);
5516        assert_eq!(out.len(), 2);
5517        out.clear();
5518        check_comments_extensible(&pkg, None, &mut out);
5519        assert_eq!(out.len(), 3);
5520        assert!(
5521            out.iter()
5522                .any(|f| f.message.contains("without commentsIds"))
5523        );
5524    }
5525
5526    #[test]
5527    fn graph_cycles_are_reported_without_confusing_acyclic_chains() {
5528        let mut out = Vec::new();
5529        check_parent_cycles(
5530            &HashMap::from([("a".into(), "b".into()), ("b".into(), "c".into())]),
5531            &mut out,
5532        );
5533        assert!(out.is_empty());
5534        check_parent_cycles(
5535            &HashMap::from([
5536                ("a".into(), "b".into()),
5537                ("b".into(), "a".into()),
5538                ("tail".into(), "a".into()),
5539            ]),
5540            &mut out,
5541        );
5542        assert_eq!(out.len(), 3);
5543        assert!(out.iter().all(|f| f.code == "COMMENT_PARENT_CYCLE"));
5544    }
5545
5546    #[test]
5547    fn namespace_prefix_lists_distinguish_application_data_bound_and_unknown_prefixes() {
5548        let mut pkg = pkg();
5549        pkg.set_part("custom.xml", format!(r#"<root xmlns:mc="{}" xmlns:known="urn:known" Requires="application" mc:Ignorable="known xml w14 unknown"><mc:Choice Requires="known"/><child mc:PreserveElements="known:thing unknown:thing"/></root>"#, MC::URI).into_bytes());
5550        let mut out = Vec::new();
5551        check_namespace_qname_context(&pkg, "custom.xml", &mut out);
5552        assert_eq!(out.len(), 3);
5553        assert_eq!(out.iter().filter(|f| f.repairable).count(), 1);
5554        assert!(out.iter().all(|f| f.code == "MC_UNBOUND_PREFIX"));
5555        for attribute in [
5556            "Ignorable",
5557            "PreserveAttributes",
5558            "PreserveElements",
5559            "ProcessContent",
5560            "MustUnderstand",
5561        ] {
5562            assert!(is_namespace_qname_list(&W::p(), &MC::name(attribute)));
5563        }
5564        assert!(!is_namespace_qname_list(&W::p(), &MC::name("other")));
5565        assert!(!is_namespace_qname_list(
5566            &W::p(),
5567            &XName::get("Requires", "")
5568        ));
5569        assert!(is_namespace_qname_list(
5570            &MC::name("Choice"),
5571            &XName::get("Requires", "")
5572        ));
5573    }
5574
5575    #[test]
5576    fn absent_or_unreadable_parts_are_not_modified_by_edit_part() {
5577        let mut pkg = pkg();
5578        edit_part(&mut pkg, "absent.xml", |_, _| {
5579            panic!("missing part must not call editor")
5580        });
5581        assert!(pkg.part_bytes("absent.xml").is_none());
5582        pkg.set_part("empty.xml", Vec::new());
5583        edit_part(&mut pkg, "empty.xml", |_, _| {
5584            panic!("empty part must not call editor")
5585        });
5586        assert_eq!(pkg.part_bytes("empty.xml"), Some([].as_slice()));
5587    }
5588}
5589#[cfg(test)]
5590#[cfg_attr(all(coverage_nightly, test), coverage(off))]
5591mod validation_owner_boundary_tests {
5592    use super::*;
5593    fn package() -> PartFs {
5594        PartFs::open(include_bytes!(
5595            "../../../tests/fixtures/redline/original.docx"
5596        ))
5597        .unwrap()
5598    }
5599    #[test]
5600    fn relationship_target_diagnostics_distinguish_owned_payloads_from_unresolved_and_external_targets()
5601     {
5602        for (target, mode, present, missing) in [
5603            ("media/picture.bin", false, true, false),
5604            ("/word/media/picture.bin", false, true, false),
5605            ("word/media/picture.bin", false, true, false),
5606            ("media/missing.bin", false, false, true),
5607            ("https://example.invalid/picture.bin", false, false, false),
5608            ("http://example.invalid/picture.bin", false, false, false),
5609            ("mailto:owner@example.invalid", false, false, false),
5610            ("media/missing.bin", true, false, false),
5611        ] {
5612            let mut pkg = package();
5613            let id = if mode {
5614                pkg.add_document_relationship_external(
5615                    "word/document.xml",
5616                    "urn:test:payload",
5617                    target,
5618                )
5619            } else {
5620                pkg.add_document_relationship("word/document.xml", "urn:test:payload", target)
5621            };
5622            if present {
5623                pkg.set_part("word/media/picture.bin", vec![1, 2, 3, 4]);
5624            }
5625            pkg.set_part("word/document.xml", format!("<w:document xmlns:w='{}' xmlns:r='{}'><w:body><w:p><w:r><w:drawing r:embed=\"{id}\"/></w:r></w:p></w:body></w:document>", W::URI, R::URI).into_bytes());
5626            let before = pkg.to_zip().unwrap();
5627            let mut findings = Vec::new();
5628            check_relationship_integrity(&pkg, &mut findings);
5629            assert_eq!(
5630                findings
5631                    .iter()
5632                    .filter(|f| f.code == "MISSING_REL_TARGET")
5633                    .count(),
5634                usize::from(missing),
5635                "{target} external={mode}"
5636            );
5637            assert!(findings.iter().all(|f| f.code != "DANGLING_RELATIONSHIP"));
5638            if missing {
5639                assert!(
5640                    findings
5641                        .iter()
5642                        .any(|f| f.message.contains(&id) && f.message.contains(target))
5643                );
5644            }
5645            assert_eq!(pkg.to_zip().unwrap(), before);
5646        }
5647    }
5648
5649    #[test]
5650    fn file_unc_and_external_template_targets_are_not_internal_parts() {
5651        let template =
5652            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate";
5653        for target in [
5654            "file:///etc/passwd",
5655            "file://server/share/template.dotx",
5656            r"\\server\share\template.dotx",
5657            "//server/share/template.dotx",
5658        ] {
5659            let mut pkg = package();
5660            pkg.add_document_relationship("word/document.xml", template, target);
5661            let mut findings = Vec::new();
5662            check_relationship_integrity(&pkg, &mut findings);
5663            let missing: Vec<_> = findings
5664                .iter()
5665                .filter(|finding| finding.code == "MISSING_REL_TARGET")
5666                .map(|finding| finding.message.clone())
5667                .collect::<Vec<_>>();
5668            assert!(
5669                missing.is_empty(),
5670                "{target} was resolved as an internal part: {missing:?}"
5671            );
5672            let opened = PartFs::open(&pkg.to_zip().unwrap()).expect("reopen");
5673            let rels = opened
5674                .read_rels_for("word/document.xml")
5675                .expect("relationships");
5676            assert!(
5677                rels.items.iter().any(|item| item.target == target),
5678                "{target} was dropped from the package"
5679            );
5680        }
5681
5682        let mut kept = package();
5683        let external = "file:///C:/Templates/Normal.dotx";
5684        kept.add_document_relationship_external("word/document.xml", template, external);
5685        let mut findings = Vec::new();
5686        check_relationship_integrity(&kept, &mut findings);
5687        assert!(
5688            findings
5689                .iter()
5690                .all(|finding| finding.code != "MISSING_REL_TARGET")
5691        );
5692        let opened = PartFs::open(&kept.to_zip().unwrap()).expect("reopen");
5693        let rels = opened
5694            .read_rels_for("word/document.xml")
5695            .expect("relationships");
5696        assert!(
5697            rels.items.iter().any(|item| item.target == external),
5698            "an external template target was dropped"
5699        );
5700
5701        // Part names are case-insensitive, so `//Word/` is a package root too.
5702        for target in [
5703            "//word/no-such.xml",
5704            "//Word/no-such.xml",
5705            "//DOCPROPS/no-such.xml",
5706        ] {
5707            let mut doubled = package();
5708            doubled.add_document_relationship("word/document.xml", "urn:test/part", target);
5709            let mut findings = Vec::new();
5710            check_relationship_integrity(&doubled, &mut findings);
5711            assert!(
5712                findings
5713                    .iter()
5714                    .any(|finding| finding.code == "MISSING_REL_TARGET"),
5715                "{target}: a doubled package path still names a part"
5716            );
5717        }
5718    }
5719
5720    #[test]
5721    fn a_doubled_package_root_in_any_ascii_case_still_names_a_part() {
5722        for target in [
5723            "//Word/no-such.xml",
5724            "//WORD/no-such.xml",
5725            "//DocProps/no-such.xml",
5726            "//CustomXml/no-such.xml",
5727            "//_RELS/no-such.xml",
5728            "//Ppt/no-such.xml",
5729            "//XL/no-such.xml",
5730        ] {
5731            let mut pkg = package();
5732            pkg.add_document_relationship("word/document.xml", "urn:test/part", target);
5733            let mut findings = Vec::new();
5734            check_relationship_integrity(&pkg, &mut findings);
5735            assert!(
5736                findings
5737                    .iter()
5738                    .any(|finding| finding.code == "MISSING_REL_TARGET"),
5739                "{target} was treated as a share, not a part"
5740            );
5741        }
5742
5743        let mut present = package();
5744        present.add_document_relationship(
5745            "word/document.xml",
5746            "urn:test/part",
5747            "//Word/document.xml",
5748        );
5749        let mut findings = Vec::new();
5750        check_relationship_integrity(&present, &mut findings);
5751        assert!(
5752            findings.iter().all(|finding| {
5753                finding.code != "MISSING_REL_TARGET"
5754                    || !finding.message.contains("//Word/document.xml")
5755            }),
5756            "the document part was missed under another case: {findings:?}"
5757        );
5758
5759        let mut share = package();
5760        share.add_document_relationship(
5761            "word/document.xml",
5762            "urn:test/part",
5763            "//notepad/share/template.dotx",
5764        );
5765        let mut findings = Vec::new();
5766        check_relationship_integrity(&share, &mut findings);
5767        assert!(
5768            findings
5769                .iter()
5770                .all(|finding| finding.code != "MISSING_REL_TARGET"
5771                    || !finding.message.contains("notepad")),
5772            "a share whose name is not a package root was read as a part"
5773        );
5774    }
5775
5776    /// A referenced target behind a mixed-case doubled root, and a
5777    /// referenced target from an owner whose extension is `.XML`, are the
5778    /// Word-fatal, error-severity finding on their owner, not the unused
5779    /// relationship warning.
5780    #[test]
5781    fn a_referenced_missing_target_is_fatal_on_its_owner_in_any_case() {
5782        let body = |id: &str| {
5783            format!(
5784                "<w:document xmlns:w='{}' xmlns:r='{}'><w:body><w:p><w:r><w:drawing r:embed=\"{id}\"/></w:r></w:p></w:body></w:document>",
5785                W::URI,
5786                R::URI
5787            )
5788            .into_bytes()
5789        };
5790        for (owner, target) in [
5791            ("word/document.xml", "//Word/media/no-such.bin"),
5792            ("word/extra.XML", "media/no-such.bin"),
5793        ] {
5794            let mut pkg = package();
5795            let id = pkg.add_document_relationship(owner, "urn:test:payload", target);
5796            pkg.set_part(owner, body(&id));
5797            let mut findings = Vec::new();
5798            check_relationship_integrity(&pkg, &mut findings);
5799            let missing: Vec<_> = findings
5800                .iter()
5801                .filter(|f| f.code == "MISSING_REL_TARGET" && f.message.contains(target))
5802                .collect();
5803            assert_eq!(missing.len(), 1, "{owner} -> {target}: {findings:?}");
5804            let finding = missing[0];
5805            assert_eq!(finding.part, owner, "{target}");
5806            assert!(finding.word_fatal, "{owner} -> {target} is not Word-fatal");
5807            assert_eq!(finding.severity, "error", "{owner} -> {target}");
5808            assert!(
5809                finding
5810                    .message
5811                    .contains(&format!("relationship '{id}' on '{owner}'"))
5812            );
5813        }
5814    }
5815
5816    #[test]
5817    fn orphan_comment_cleanup_preserves_live_references_and_neighbor_run_properties() {
5818        for (content, remains) in [
5819            ("", false),
5820            ("<w:rPr><w:b/></w:rPr>", false),
5821            ("<w:rPr><w:i/></w:rPr><w:t>Keep</w:t>", true),
5822        ] {
5823            let mut dom = Dom::new();
5824            let doc = dom.parse_xdocument(&format!("<w:document xmlns:w='{}'><w:body><w:p><w:commentRangeStart w:id='3'/><w:r>{content}<w:commentReference w:id='3'/></w:r><w:commentRangeEnd w:id='3'/><w:r><w:rPr><w:color w:val='246810'/></w:rPr><w:commentReference w:id='4'/><w:t>Live</w:t></w:r></w:p></w:body></w:document>", W::URI));
5825            let root = dom.root(doc).unwrap();
5826            drop_orphan_comment_anchors(&mut dom, root, &HashSet::from(["4".to_string()]));
5827            assert!(
5828                dom.descendants(root, Some(&W::comment_range_start()))
5829                    .is_empty()
5830            );
5831            assert!(
5832                dom.descendants(root, Some(&W::comment_range_end()))
5833                    .is_empty()
5834            );
5835            let refs = dom.descendants(root, Some(&W::comment_reference()));
5836            assert_eq!(refs.len(), 1);
5837            assert_eq!(dom.attribute(refs[0], &W::id()), Some("4"));
5838            assert_eq!(
5839                dom.descendants(root, Some(&W::r())).len(),
5840                if remains { 2 } else { 1 }
5841            );
5842            let texts: Vec<_> = dom
5843                .descendants(root, Some(&W::t()))
5844                .into_iter()
5845                .map(|n| dom.value(n))
5846                .collect();
5847            assert_eq!(
5848                texts,
5849                if remains {
5850                    vec!["Keep", "Live"]
5851                } else {
5852                    vec!["Live"]
5853                }
5854            );
5855            let live_pr = dom
5856                .element(dom.parent(refs[0]).unwrap(), &W::r_pr())
5857                .unwrap();
5858            assert_eq!(
5859                dom.attribute(dom.element(live_pr, &W::name("color")).unwrap(), &W::val()),
5860                Some("246810")
5861            );
5862            let once = dom.serialize_element(root);
5863            drop_orphan_comment_anchors(&mut dom, root, &HashSet::from(["4".to_string()]));
5864            assert_eq!(dom.serialize_element(root), once);
5865        }
5866    }
5867}
5868
5869#[cfg(test)]
5870#[cfg_attr(all(coverage_nightly, test), coverage(off))]
5871mod public_memory_validator_owner_boundary_tests {
5872    use super::*;
5873    fn package(body: &str) -> PartFs {
5874        let mut pkg = PartFs::open(include_bytes!(
5875            "../../../tests/fixtures/redline/original.docx"
5876        ))
5877        .unwrap();
5878        pkg.set_part("word/document.xml",format!("<w:document xmlns:w=\"{}\" xmlns:w14=\"{}\" xmlns:mc=\"{}\" mc:Ignorable=\"w14\"><w:body>{body}<w:sectPr><w:pgSz w:w=\"12240\" w:h=\"15840\"/></w:sectPr></w:body></w:document>",W::URI,W14::URI,MC::URI).into_bytes());
5879        pkg
5880    }
5881    fn snapshot(pkg: &PartFs) -> Vec<(String, Vec<u8>)> {
5882        let mut parts = pkg.parts();
5883        parts.sort();
5884        parts
5885            .into_iter()
5886            .map(|name| {
5887                let bytes = pkg.part_bytes(&name).unwrap().to_vec();
5888                (name, bytes)
5889            })
5890            .collect()
5891    }
5892
5893    #[test]
5894    fn missing_opaque_part_type_has_exact_public_diagnostics_and_no_speculative_repair() {
5895        let mut pkg = package("<w:p><w:r><w:t>Owned source payload</w:t></w:r></w:p>");
5896        assert!(
5897            ring1(&pkg).is_empty(),
5898            "the source fixture has no unrelated Ring1 defects"
5899        );
5900        pkg.set_part(
5901            "customXml/source-owned.opaque",
5902            b"Independent opaque payload".to_vec(),
5903        );
5904        let source = snapshot(&pkg);
5905        let bytes = pkg.to_zip().unwrap();
5906        let expected = Finding {
5907            code: "MISSING_CONTENT_TYPE".into(),
5908            set: "word".into(),
5909            severity: "error".into(),
5910            part: "customXml/source-owned.opaque".into(),
5911            location: String::new(),
5912            r#ref: String::new(),
5913            message: "part 'customXml/source-owned.opaque' has no content type".into(),
5914            word_fatal: true,
5915            repairable: false,
5916        };
5917        assert_eq!(ring1(&pkg), vec![expected.clone()]);
5918        let report = validate(&bytes).unwrap();
5919        assert_eq!(report, vec![expected.clone()]);
5920        let result = repair(&bytes).unwrap();
5921        assert_eq!(
5922            result.docx, bytes,
5923            "an unknown opaque part requires a maintainer-selected type, not guessed rewriting"
5924        );
5925        assert!(result.repaired.is_empty());
5926        assert_eq!(result.remaining, vec![expected]);
5927        assert_eq!(snapshot(&PartFs::open(&result.docx).unwrap()), source);
5928        let again = repair(&result.docx).unwrap();
5929        assert_eq!(again, result);
5930    }
5931
5932    #[test]
5933    fn repairing_comment_paragraph_ids_retains_reply_graph_source_text_and_all_relationships() {
5934        // Ring1 deliberately diagnoses a serialized Word range violation.
5935        // The actual source package is otherwise complete: both comment
5936        // definitions have balanced body anchors and a real acyclic reply
5937        // graph. Identical paraId/textId aliases refer to the same source
5938        // owner; masked collisions must choose a free ID exactly once.
5939        for old in ["80000001", "00000000", "FFFFFFFF"] {
5940            let body = "<w:p w14:paraId=\"00000003\"><w:pPr><w:spacing w:after=\"80\"/></w:pPr><w:commentRangeStart w:id=\"1\"/><w:r><w:rPr><w:b/></w:rPr><w:t>Root source ação</w:t></w:r><w:commentRangeEnd w:id=\"1\"/><w:r><w:commentReference w:id=\"1\"/></w:r></w:p><w:p w14:paraId=\"00000004\" w14:textId=\"7FFFFFFF\"><w:commentRangeStart w:id=\"2\"/><w:r><w:rPr><w:i/></w:rPr><w:t>Reply source café</w:t></w:r><w:commentRangeEnd w:id=\"2\"/><w:r><w:commentReference w:id=\"2\"/></w:r></w:p>";
5941            let mut pkg = package(body);
5942            let comments = format!(
5943                "<w:comments xmlns:w=\"{}\" xmlns:w14=\"{}\" xmlns:mc=\"{}\" mc:Ignorable=\"w14\"><w:comment w:id=\"1\" w:author=\"Original reviewer\" w:initials=\"OR\" w:date=\"2025-02-03T04:05:06Z\"><w:p w14:paraId=\"00000001\"><w:pPr><w:spacing w:after=\"120\"/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t>Root comment ação</w:t></w:r></w:p></w:comment><w:comment w:id=\"2\" w:author=\"Reply reviewer\" w:initials=\"RR\" w:date=\"2025-03-04T05:06:07Z\"><w:p w14:paraId=\"{old}\" w14:textId=\"{old}\"><w:pPr><w:spacing w:after=\"240\"/></w:pPr><w:r><w:rPr><w:i/></w:rPr><w:t>Reply comment café</w:t></w:r></w:p></w:comment></w:comments>",
5944                W::URI,
5945                W14::URI,
5946                MC::URI
5947            );
5948            let extended = format!(
5949                "<w15:commentsEx xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\"><w15:commentEx w15:paraId=\"00000001\" w15:done=\"0\"/><w15:commentEx w15:paraId=\"{old}\" w15:paraIdParent=\"00000001\" w15:done=\"1\"/></w15:commentsEx>"
5950            );
5951            pkg.set_part("word/comments.xml", comments.clone().into_bytes());
5952            pkg.set_part("word/commentsExtended.xml", extended.clone().into_bytes());
5953            for (part, content_type, relationship) in COMMENT_FAMILY.into_iter().take(2) {
5954                pkg.add_content_type_override(&format!("/{part}"), content_type);
5955                pkg.add_document_relationship(
5956                    "word/document.xml",
5957                    relationship,
5958                    part.strip_prefix("word/").unwrap(),
5959                );
5960            }
5961            let source = snapshot(&pkg);
5962            let bytes = pkg.to_zip().unwrap();
5963            let original_records = crate::comments::list_comments(&bytes).unwrap();
5964            let before = validate(&bytes).unwrap();
5965            let range = before
5966                .iter()
5967                .filter(|finding| finding.code == "PARA_ID_OUT_OF_RANGE")
5968                .cloned()
5969                .collect::<Vec<_>>();
5970            let expected_range=["w14:paraId=\"","w14:textId=\""].map(|attribute|Finding {code:"PARA_ID_OUT_OF_RANGE".into(),set:"word".into(),severity:"warning".into(),part:"word/comments.xml".into(),location:String::new(),r#ref:String::new(),message:format!("{attribute} value '{old}' outside Word's range 1..0x7FFFFFFF (>= 0x80000000 or zero) in 'word/comments.xml' (id-paraid-overflow)"),word_fatal:false,repairable:true});
5971            assert_eq!(range, expected_range);
5972            let result = repair(&bytes).unwrap();
5973            assert!(
5974                result.remaining.is_empty(),
5975                "{old}: every reported range or graph inconsistency must be resolved, got {:?}",
5976                result.remaining
5977            );
5978            assert_eq!(result.repaired, expected_range);
5979            let output = PartFs::open(&result.docx).unwrap();
5980            let expected_comments = comments
5981                .replace(&format!("paraId=\"{old}\""), "paraId=\"00000002\"")
5982                .replace(&format!("textId=\"{old}\""), "textId=\"00000002\"");
5983            let expected_extended =
5984                extended.replace(&format!("paraId=\"{old}\""), "paraId=\"00000002\"");
5985            let expected = source
5986                .iter()
5987                .map(|(name, contents)| {
5988                    (
5989                        name.clone(),
5990                        match name.as_str() {
5991                            "word/comments.xml" => expected_comments.as_bytes().to_vec(),
5992                            "word/commentsExtended.xml" => expected_extended.as_bytes().to_vec(),
5993                            _ => contents.clone(),
5994                        },
5995                    )
5996                })
5997                .collect::<Vec<_>>();
5998            assert_eq!(
5999                snapshot(&output),
6000                expected,
6001                "{old}: repair must change only the owned identifier aliases, not source formats/text/history/relationships"
6002            );
6003            assert_eq!(
6004                crate::comments::list_comments(&result.docx).unwrap(),
6005                original_records,
6006                "{old}: complete comment records and reply topology survive"
6007            );
6008            assert_eq!(snapshot(&PartFs::open(&bytes).unwrap()), source);
6009            let again = repair(&result.docx).unwrap();
6010            assert_eq!(again.docx, result.docx);
6011            assert!(again.repaired.is_empty());
6012            assert!(again.remaining.is_empty());
6013        }
6014    }
6015}
6016
6017#[cfg(test)]
6018#[cfg_attr(all(coverage_nightly, test), coverage(off))]
6019mod literal_revision_repair_contract_tests {
6020    use super::*;
6021
6022    fn tree(source: &str) -> (Dom, NodeId) {
6023        let mut dom = Dom::new();
6024        let doc = dom.parse_xdocument(&format!(
6025            r#"<w:document xmlns:w="{}" xmlns:r="{}"><w:body>{source}</w:body></w:document>"#,
6026            W::URI,
6027            R::URI
6028        ));
6029        (dom, doc)
6030    }
6031
6032    #[test]
6033    fn duplicate_move_ids_keep_exact_range_pairings_and_every_unrelated_source_node() {
6034        let source = r#"<w:p><w:bookmarkStart w:id="40" w:name="owned"/><w:moveFromRangeStart w:id="7"/><w:r><w:t>first</w:t></w:r><w:moveFromRangeEnd w:id="7"/><w:moveFromRangeStart w:id="7"/><w:r><w:t>second</w:t></w:r><w:moveFromRangeEnd w:id="7"/><w:moveToRangeStart w:id="8"/><w:r><w:t>third</w:t></w:r><w:moveToRangeEnd w:id="8"/><w:moveToRangeStart w:id="8"/><w:r><w:t>fourth</w:t></w:r><w:moveToRangeEnd w:id="8"/><w:ins w:id="9" w:author="A" w:date="2026-10-09T00:00:00Z"><w:r><w:t>fifth</w:t></w:r></w:ins><w:ins w:id="9" w:author="B" w:date="2026-10-09T00:00:00Z"><w:r><w:t>sixth</w:t></w:r></w:ins><w:bookmarkEnd w:id="40"/></w:p>"#;
6035        let (mut dom, doc) = tree(source);
6036        let root = dom.root(doc).unwrap();
6037        let expected=source.replacen(r#"<w:moveFromRangeStart w:id="7"/><w:r><w:t>second</w:t></w:r><w:moveFromRangeEnd w:id="7"/>"#,r#"<w:moveFromRangeStart w:id="41"/><w:r><w:t>second</w:t></w:r><w:moveFromRangeEnd w:id="41"/>"#,1)
6038          .replacen(r#"<w:moveToRangeStart w:id="8"/><w:r><w:t>fourth</w:t></w:r><w:moveToRangeEnd w:id="8"/>"#,r#"<w:moveToRangeStart w:id="42"/><w:r><w:t>fourth</w:t></w:r><w:moveToRangeEnd w:id="42"/>"#,1)
6039          .replacen(r#"<w:ins w:id="9" w:author="B""#,r#"<w:ins w:id="43" w:author="B""#,1);
6040        let (expected_dom, expected_doc) = tree(&expected);
6041        renumber_duplicate_revision_ids(&mut dom, root);
6042        assert_eq!(
6043            dom.serialize_document(doc),
6044            expected_dom.serialize_document(expected_doc)
6045        );
6046        renumber_duplicate_revision_ids(&mut dom, root);
6047        assert_eq!(
6048            dom.serialize_document(doc),
6049            expected_dom.serialize_document(expected_doc)
6050        );
6051    }
6052
6053    #[test]
6054    fn repair_declines_missing_ids_and_unmatched_ranges_without_inventing_content() {
6055        let source = r#"<w:p><w:ins><w:r><w:t>missing id</w:t></w:r></w:ins><w:moveFromRangeStart w:id="3"/><w:moveFromRangeStart w:id="3"/><w:moveToRangeEnd w:id="3"/><w:r><w:t>unmatched range retained</w:t></w:r></w:p>"#;
6056        let expected = source.replacen(
6057            r#"<w:moveFromRangeStart w:id="3"/><w:moveToRangeEnd"#,
6058            r#"<w:moveFromRangeStart w:id="4"/><w:moveToRangeEnd"#,
6059            1,
6060        );
6061        let (mut dom, doc) = tree(source);
6062        let root = dom.root(doc).unwrap();
6063        let (expected_dom, expected_doc) = tree(&expected);
6064        renumber_duplicate_revision_ids(&mut dom, root);
6065        assert_eq!(
6066            dom.serialize_document(doc),
6067            expected_dom.serialize_document(expected_doc)
6068        );
6069    }
6070
6071    #[test]
6072    fn three_starts_of_one_id_before_their_ends_pair_one_to_one() {
6073        // Each start takes the first end of its id that no earlier start
6074        // has taken; the first start keeps its id (#1666).
6075        let range = |tag: &str, id: u32| format!(r#"<w:customXmlIns{tag} w:id="{id}"/>"#);
6076        let body = |ids: [u32; 3]| {
6077            let starts: String = ids.iter().map(|&id| range("RangeStart", id)).collect();
6078            let ends: String = ids.iter().map(|&id| range("RangeEnd", id)).collect();
6079            format!("<w:p>{starts}<w:r><w:t>held</w:t></w:r>{ends}</w:p>")
6080        };
6081        let (mut dom, doc) = tree(&body([9, 9, 9]));
6082        let root = dom.root(doc).unwrap();
6083        let (expected_dom, expected_doc) = tree(&body([9, 10, 11]));
6084        renumber_duplicate_revision_ids(&mut dom, root);
6085        assert_eq!(
6086            dom.serialize_document(doc),
6087            expected_dom.serialize_document(expected_doc)
6088        );
6089    }
6090}
6091
6092#[cfg(test)]
6093#[cfg_attr(all(coverage_nightly, test), coverage(off))]
6094mod paragraph_id_collision_owner_tests {
6095    use super::*;
6096
6097    fn snapshot(pkg: &PartFs) -> Vec<(String, Vec<u8>)> {
6098        let mut names = pkg.parts();
6099        names.sort();
6100        names
6101            .into_iter()
6102            .map(|name| {
6103                let bytes = pkg.part_bytes(&name).unwrap().to_vec();
6104                (name, bytes)
6105            })
6106            .collect()
6107    }
6108
6109    #[test]
6110    fn paragraph_id_collision_repair_preserves_all_owners_and_shared_references() {
6111        for old_id in ["00000000", "80000000", "80000001", "FFFFFFFF"] {
6112            let mut pkg = PartFs::open(include_bytes!(
6113                "../../../tests/fixtures/redline/original.docx"
6114            ))
6115            .unwrap();
6116            let document = format!(
6117                r#"<w:document xmlns:w="{}" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml"><w:body><w:p w14:paraId="00000001" w14:textId="00000002"><w:pPr><w:spacing w:after="80"/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t>existing ids</w:t></w:r></w:p><w:p w14:paraId="7FFFFFFF"><w:r><w:t>upper existing id</w:t></w:r></w:p><w:p w14:paraId="{old_id}" w14:textId="{old_id}"><w:pPr><w:keepNext/><w:pPrChange w:id="51" w:author="Source" w:date="2026-10-09T00:00:00Z"><w:pPr><w:spacing w:before="120"/></w:pPr></w:pPrChange></w:pPr><w:r><w:rPr><w:i/><w:color w:val="123456"/></w:rPr><w:t>ação τέλος</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/></w:sectPr></w:body></w:document>"#,
6118                W::URI
6119            );
6120            pkg.set_part("word/document.xml", document.as_bytes().to_vec());
6121            let refs = format!(
6122                r#"<w15:commentsEx xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml"><w15:commentEx w15:paraId="{old_id}" w15:paraIdParent="{old_id}" w15:done="0"/></w15:commentsEx>"#
6123            );
6124            pkg.set_part("word/commentsExtended.xml", refs.as_bytes().to_vec());
6125            pkg.add_content_type_override(
6126                "/word/commentsExtended.xml",
6127                "application/vnd.ms-word.commentsExtended+xml",
6128            );
6129            pkg.add_document_relationship(
6130                "word/document.xml",
6131                "http://schemas.microsoft.com/office/2011/relationships/commentsExtended",
6132                "commentsExtended.xml",
6133            );
6134            let before = snapshot(&pkg);
6135            let mut expected = before.clone();
6136            for (name, bytes) in &mut expected {
6137                if name == "word/document.xml" || name == "word/commentsExtended.xml" {
6138                    *bytes = std::str::from_utf8(bytes)
6139                        .unwrap()
6140                        .replace(&format!("=\"{old_id}\""), "=\"00000003\"")
6141                        .into_bytes();
6142                }
6143            }
6144            renumber_out_of_range_para_ids(&mut pkg);
6145            assert_eq!(
6146                snapshot(&pkg),
6147                expected,
6148                "{old_id}: only the out-of-range shared id changes"
6149            );
6150            renumber_out_of_range_para_ids(&mut pkg);
6151            assert_eq!(
6152                snapshot(&pkg),
6153                expected,
6154                "{old_id}: a repeat preserves every part byte"
6155            );
6156            assert_ne!(before, expected);
6157        }
6158    }
6159
6160    #[test]
6161    fn dangling_relationship_repair_keeps_empty_known_and_nonrelationship_owners() {
6162        let source = format!(
6163            r#"<w:document xmlns:w="{}" xmlns:r="{}" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><w:body><w:p><w:pPr><w:spacing w:after="80"/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:drawing><a:blip r:embed="missing" r:link="known"/></w:drawing><w:t>owned</w:t></w:r><w:hyperlink r:id="known"><w:r><w:t>keep</w:t></w:r></w:hyperlink><w:hyperlink r:id=""><w:r><w:t>empty reference</w:t></w:r></w:hyperlink><w:hyperlink r:id="missing"><w:r><w:t>attribute removed, text kept</w:t></w:r></w:hyperlink><w:ins w:id="52" w:author="Source" w:date="2026-10-09T00:00:00Z"><w:r><w:t>tracked source</w:t></w:r></w:ins></w:p><w:altChunk r:id="missing"/><w:sectPr><w:headerReference w:type="default" r:id="missing"/><w:footerReference w:type="default" r:id="known"/><w:pgSz w:w="12240" w:h="15840"/></w:sectPr></w:body></w:document>"#,
6164            W::URI,
6165            R::URI
6166        );
6167        let expected = source
6168            .replace(r#" r:embed="missing""#, "")
6169            .replace(r#"<w:hyperlink r:id="missing">"#, "<w:hyperlink>")
6170            .replace(r#"<w:altChunk r:id="missing"/>"#, "")
6171            .replace(
6172                r#"<w:headerReference w:type="default" r:id="missing"/>"#,
6173                "",
6174            );
6175        let mut dom = Dom::new();
6176        let doc = dom.parse_xdocument(&source);
6177        let root = dom.root(doc).unwrap();
6178        let mut expected_dom = Dom::new();
6179        let expected_doc = expected_dom.parse_xdocument(&expected);
6180        let ids = HashSet::from(["known".to_string()]);
6181        drop_dangling_relationship_attributes(&mut dom, root, &ids);
6182        assert_eq!(
6183            dom.serialize_document(doc),
6184            expected_dom.serialize_document(expected_doc)
6185        );
6186        drop_dangling_relationship_attributes(&mut dom, root, &ids);
6187        assert_eq!(
6188            dom.serialize_document(doc),
6189            expected_dom.serialize_document(expected_doc)
6190        );
6191    }
6192}
6193
6194#[cfg(test)]
6195#[cfg_attr(all(coverage_nightly, test), coverage(off))]
6196mod authored_comment_family_validation_contract_tests {
6197    use super::*;
6198
6199    fn package() -> PartFs {
6200        let mut pkg = PartFs::open(include_bytes!(
6201            "../../../tests/fixtures/redline/original.docx"
6202        ))
6203        .unwrap();
6204        pkg.set_part("word/document.xml",format!("<w:document xmlns:w='{}'><w:body><w:p><w:r><w:t>Owned body</w:t></w:r></w:p></w:body></w:document>",W::URI).into_bytes());
6205        pkg
6206    }
6207    fn frozen(pkg: &PartFs) -> Vec<(String, Vec<u8>)> {
6208        let mut parts = pkg.parts();
6209        parts.sort();
6210        parts
6211            .into_iter()
6212            .map(|part| {
6213                let bytes = pkg.part_bytes(&part).unwrap().to_vec();
6214                (part, bytes)
6215            })
6216            .collect()
6217    }
6218
6219    #[test]
6220    fn auxiliary_comment_parts_without_their_source_definition_are_reported_individually() {
6221        for (part, content_type, rel_type) in &COMMENT_FAMILY[1..] {
6222            let mut pkg = package();
6223            pkg.set_part(part, b"<root/>".to_vec());
6224            pkg.add_content_type_override(part, content_type);
6225            pkg.add_document_relationship("word/document.xml", rel_type, &format!("/{part}"));
6226            let before = frozen(&pkg);
6227            let mut findings = Vec::new();
6228            check_comment_graph(&pkg, &mut findings);
6229            assert_eq!(
6230                findings,
6231                vec![Finding::new(
6232                    "COMMENT_METADATA_MISMATCH",
6233                    part,
6234                    "",
6235                    format!("'{part}' exists without word/comments.xml")
6236                )]
6237            );
6238            assert!(ring1(&pkg).contains(&findings[0]));
6239            assert_eq!(frozen(&pkg), before);
6240        }
6241    }
6242
6243    #[test]
6244    fn each_comment_family_relationship_requires_its_exact_owned_part_and_content_type() {
6245        for (part, content_type, rel_type) in COMMENT_FAMILY {
6246            for case in 0..6 {
6247                let mut pkg = package();
6248                if case != 5 {
6249                    pkg.set_part(part, b"<root/>".to_vec());
6250                }
6251                pkg.add_content_type_override(
6252                    part,
6253                    if case == 0 {
6254                        "application/wrong"
6255                    } else {
6256                        content_type
6257                    },
6258                );
6259                let mut rid = None;
6260                let target = if case == 4 {
6261                    "wrong.xml".to_string()
6262                } else {
6263                    format!("/{part}")
6264                };
6265                if case != 1 {
6266                    rid = Some(if case == 3 {
6267                        pkg.add_document_relationship_external(
6268                            "word/document.xml",
6269                            rel_type,
6270                            &format!("/{part}"),
6271                        )
6272                    } else {
6273                        pkg.add_document_relationship("word/document.xml", rel_type, &target)
6274                    });
6275                }
6276                if case == 2 {
6277                    pkg.add_document_relationship(
6278                        "word/document.xml",
6279                        rel_type,
6280                        &format!("/{part}"),
6281                    );
6282                }
6283                let before = frozen(&pkg);
6284                let mut findings = Vec::new();
6285                check_comment_family_packaging(&pkg, "word/document.xml", &mut findings);
6286                let expected = match case {
6287                    0 => Finding::new(
6288                        "COMMENT_PARTS_INCONSISTENT",
6289                        part,
6290                        "",
6291                        format!("'{part}' has the wrong content type (expected '{content_type}')"),
6292                    ),
6293                    1 | 2 => Finding::new(
6294                        "COMMENT_PARTS_INCONSISTENT",
6295                        "word/document.xml",
6296                        "",
6297                        format!(
6298                            "'word/document.xml' needs exactly one relationship to '{part}', found {}",
6299                            if case == 1 { 0 } else { 2 }
6300                        ),
6301                    ),
6302                    3 | 4 => Finding::new(
6303                        "COMMENT_PARTS_INCONSISTENT",
6304                        "word/document.xml",
6305                        "",
6306                        format!(
6307                            "comment relationship '{}' on 'word/document.xml' resolves to '{}' instead of '{part}'",
6308                            rid.unwrap(),
6309                            if case == 3 {
6310                                format!("/{part}")
6311                            } else {
6312                                "wrong.xml".into()
6313                            }
6314                        ),
6315                    ),
6316                    _ => Finding::new(
6317                        "COMMENT_METADATA_MISMATCH",
6318                        "word/document.xml",
6319                        "",
6320                        format!(
6321                            "'word/document.xml' has a relationship for missing comment part '{part}'"
6322                        ),
6323                    ),
6324                };
6325                assert_eq!(findings, vec![expected], "{part}/case{case}");
6326                assert_eq!(frozen(&pkg), before);
6327            }
6328        }
6329    }
6330}
6331
6332#[cfg(test)]
6333#[cfg_attr(all(coverage_nightly, test), coverage(off))]
6334mod retained_namespace_finding_source_contract_tests {
6335    use super::*;
6336
6337    #[test]
6338    fn repair_reports_unbound_unknown_prefixes_without_discarding_owned_story_content() {
6339        for known in [false, true] {
6340            let ignorable = if known {
6341                "w14 UnknownFoo UnknownBar"
6342            } else {
6343                "UnknownFoo UnknownBar"
6344            };
6345            let mut pkg = PartFs::open(include_bytes!(
6346                "../../../tests/fixtures/redline/original.docx"
6347            ))
6348            .unwrap();
6349            let body = format!(
6350                "<w:document xmlns:w='{}' xmlns:mc='{}' mc:Ignorable='{ignorable}'><w:body><w:p><w:pPr><w:spacing w:after='120'/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t>Owned body</w:t></w:r></w:p></w:body></w:document>",
6351                W::URI,
6352                MC::URI
6353            );
6354            let header = format!(
6355                "<w:hdr xmlns:w='{}' xmlns:mc='{}' mc:Ignorable='UnknownFoo'><w:p><w:r><w:rPr><w:i/></w:rPr><w:t>Owned header</w:t></w:r></w:p></w:hdr>",
6356                W::URI,
6357                MC::URI
6358            );
6359            pkg.set_part("word/document.xml", body.into_bytes());
6360            pkg.set_part("word/header1.xml", header.into_bytes());
6361            pkg.add_content_type_override(
6362                "word/header1.xml",
6363                "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
6364            );
6365            pkg.add_document_relationship(
6366                "word/document.xml",
6367                "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header",
6368                "header1.xml",
6369            );
6370            let source = pkg.to_zip().unwrap();
6371            let before = validate(&source).unwrap();
6372            assert_eq!(before.len(), 3 + usize::from(known), "{before:?}");
6373            assert!(before.iter().all(|f| f.code == "MC_UNBOUND_PREFIX"));
6374            assert_eq!(
6375                before
6376                    .iter()
6377                    .filter(|f| f.part == "word/document.xml")
6378                    .count(),
6379                2 + usize::from(known)
6380            );
6381            assert_eq!(
6382                before
6383                    .iter()
6384                    .filter(|f| f.part == "word/header1.xml")
6385                    .count(),
6386                1
6387            );
6388            let out = repair(&source).unwrap();
6389            assert_eq!(
6390                out.repaired,
6391                before
6392                    .iter()
6393                    .filter(|finding| finding.repairable)
6394                    .cloned()
6395                    .collect::<Vec<_>>()
6396            );
6397            assert_eq!(out.repaired.len(), usize::from(known));
6398            assert_eq!(
6399                out.remaining,
6400                before
6401                    .iter()
6402                    .filter(|finding| !finding.repairable)
6403                    .cloned()
6404                    .collect::<Vec<_>>()
6405            );
6406            let after = PartFs::open(&out.docx).unwrap();
6407            for part in pkg.parts() {
6408                let old = pkg.part_bytes(&part).unwrap();
6409                let new = after.part_bytes(&part).unwrap();
6410                if matches!(part.as_str(), "word/document.xml" | "word/header1.xml") {
6411                    let mut dom = Dom::new();
6412                    let old_document = dom.parse_xdocument(std::str::from_utf8(old).unwrap());
6413                    let old_root = dom.root(old_document).unwrap();
6414                    if known && part == "word/document.xml" {
6415                        dom.set_attribute_value(
6416                            old_root,
6417                            &crate::xmllinq::XNamespace::xmlns().name("w14"),
6418                            Some(crate::namespaces::W14::URI),
6419                        );
6420                    }
6421                    let expected = dom.serialize_element(old_root);
6422                    let new_document = dom.parse_xdocument(std::str::from_utf8(new).unwrap());
6423                    let new_root = dom.root(new_document).unwrap();
6424                    assert_eq!(dom.serialize_element(new_root), expected, "{part}");
6425                } else {
6426                    assert_eq!(new, old, "{part}");
6427                }
6428            }
6429            assert_eq!(pkg.to_zip().unwrap(), source);
6430            let again = repair(&out.docx).unwrap();
6431            assert_eq!(again.remaining, out.remaining);
6432            assert!(again.repaired.is_empty());
6433        }
6434    }
6435}
6436
6437#[cfg(test)]
6438#[cfg_attr(all(coverage_nightly, test), coverage(off))]
6439mod duplicate_drawing_owned_repair_contract_tests {
6440    use super::*;
6441
6442    #[test]
6443    fn duplicate_drawing_repair_renumbers_only_ids_and_preserves_every_shape_owner() {
6444        let mut pkg = PartFs::open(include_bytes!(
6445            "../../../tests/fixtures/redline/original.docx"
6446        ))
6447        .unwrap();
6448        let drawing = |id, name, color| {
6449            format!(
6450                "<w:r><w:rPr><w:b/></w:rPr><w:drawing><wp:inline><wp:extent cx='914400' cy='457200'/><wp:docPr id='{id}' name='{name}' descr='Owned shape'/><a:graphic><a:graphicData uri='http://schemas.microsoft.com/office/word/2010/wordprocessingShape'><wps:wsp><wps:cNvSpPr/><wps:spPr><a:xfrm><a:off x='0' y='0'/><a:ext cx='914400' cy='457200'/></a:xfrm><a:prstGeom prst='rect'><a:avLst/></a:prstGeom><a:solidFill><a:srgbClr val='{color}'/></a:solidFill></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"
6451            )
6452        };
6453        let xml = |first, second| {
6454            format!(
6455                "<w:document xmlns:w='{}' xmlns:wp='http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing' xmlns:a='http://schemas.openxmlformats.org/drawingml/2006/main' xmlns:wps='http://schemas.microsoft.com/office/word/2010/wordprocessingShape'><w:body><w:p><w:pPr><w:spacing w:after='80'/></w:pPr><w:r><w:rPr><w:i/></w:rPr><w:t>Owned prefix</w:t></w:r>{}{}<w:r><w:t>Owned suffix</w:t></w:r></w:p><w:sectPr><w:pgSz w:w='12240' w:h='15840'/></w:sectPr></w:body></w:document>",
6456                W::URI,
6457                drawing(first, "First", "123456"),
6458                drawing(second, "Second", "987654")
6459            )
6460        };
6461        pkg.set_part("word/document.xml", xml(7, 7).into_bytes());
6462        let source = pkg.to_zip().unwrap();
6463        let findings = validate(&source).unwrap();
6464        assert_eq!(findings.len(), 1, "{findings:?}");
6465        assert_eq!(findings[0].code, "DUPLICATE_DOCPR_ID");
6466        assert!(findings[0].repairable);
6467        assert!(!findings[0].word_fatal);
6468        let repaired = repair(&source).unwrap();
6469        assert_eq!(repaired.repaired, findings);
6470        assert!(repaired.remaining.is_empty(), "{:?}", repaired.remaining);
6471        let output = PartFs::open(&repaired.docx).unwrap();
6472        let mut dom = Dom::new();
6473        let expected = dom.parse_xdocument(&xml(1, 2));
6474        let expected_root = dom.root(expected).unwrap();
6475        let expected = dom.serialize_element(expected_root);
6476        let actual = dom.parse_xdocument(&output.part_string("word/document.xml").unwrap());
6477        let actual_root = dom.root(actual).unwrap();
6478        assert_eq!(dom.serialize_element(actual_root), expected);
6479        for part in pkg
6480            .parts()
6481            .into_iter()
6482            .filter(|part| part != "word/document.xml")
6483        {
6484            assert_eq!(output.part_bytes(&part), pkg.part_bytes(&part), "{part}");
6485        }
6486        assert_eq!(pkg.to_zip().unwrap(), source);
6487        let again = repair(&repaired.docx).unwrap();
6488        assert!(again.repaired.is_empty());
6489        assert!(again.remaining.is_empty());
6490        assert_eq!(again.docx, repaired.docx);
6491    }
6492
6493    #[test]
6494    fn a_fallback_twin_of_a_picture_is_no_second_drawing() {
6495        // Word saves a text box twice (DrawingML choice, VML fallback) and a
6496        // picture inside it twice with one docPr id; w12's header and Word's
6497        // own redline of it carry such a twin and open clean (2026-10-27).
6498        let mut pkg = PartFs::open(include_bytes!(
6499            "../../../tests/fixtures/redline/original.docx"
6500        ))
6501        .unwrap();
6502        let picture = |id| {
6503            format!(
6504                "<w:p><w:r><w:drawing><wp:inline><wp:extent cx='914400' cy='457200'/><wp:docPr id='{id}' name='Picture {id}'/></wp:inline></w:drawing></w:r></w:p>"
6505            )
6506        };
6507        let header = |fallback_id| {
6508            format!(
6509                "<w:hdr xmlns:w='{}' xmlns:wp='http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing' xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006' xmlns:wps='http://schemas.microsoft.com/office/word/2010/wordprocessingShape' xmlns:v='urn:schemas-microsoft-com:vml' mc:Ignorable='wps'><w:p><w:r><mc:AlternateContent><mc:Choice Requires='wps'><w:drawing><wp:anchor><wp:docPr id='3' name='Text Box 3'/><wps:txbx><w:txbxContent>{}</w:txbxContent></wps:txbx></wp:anchor></w:drawing></mc:Choice><mc:Fallback><w:pict><v:shape><v:textbox><w:txbxContent>{}</w:txbxContent></v:textbox></v:shape></w:pict></mc:Fallback></mc:AlternateContent></w:r></w:p>{}</w:hdr>",
6510                W::URI,
6511                picture(4),
6512                picture(4),
6513                picture(fallback_id)
6514            )
6515        };
6516        let docpr = |pkg: &PartFs| -> Vec<String> {
6517            ring1(pkg)
6518                .into_iter()
6519                .filter(|f| f.code == "DUPLICATE_DOCPR_ID")
6520                .map(|f| f.location)
6521                .collect()
6522        };
6523        pkg.set_part("word/header1.xml", header(5).into_bytes());
6524        assert_eq!(
6525            docpr(&pkg),
6526            Vec::<String>::new(),
6527            "the fallback copy is a twin"
6528        );
6529        pkg.set_part("word/header1.xml", header(4).into_bytes());
6530        assert_eq!(
6531            docpr(&pkg),
6532            ["w:p[1]/w:r[0]/w:drawing[0]/wp:inline[0]/wp:docPr[0]"],
6533            "a picture outside the fallback repeating its id is a duplicate"
6534        );
6535    }
6536}
6537
6538#[cfg(test)]
6539mod foreign_alignment_budget_tests {
6540    use super::ordered_pairs;
6541    use std::{
6542        cell::Cell,
6543        hash::{Hash, Hasher},
6544        rc::Rc,
6545    };
6546
6547    struct Counted<'a> {
6548        text: &'a str,
6549        comparisons: Rc<Cell<usize>>,
6550    }
6551    impl PartialEq for Counted<'_> {
6552        fn eq(&self, other: &Self) -> bool {
6553            let count = self.comparisons.get() + 1;
6554            self.comparisons.set(count);
6555            assert!(
6556                count <= 1_000_000,
6557                "alignment exceeded 1,000,000 equality comparisons"
6558            );
6559            self.text == other.text
6560        }
6561    }
6562    impl Eq for Counted<'_> {}
6563    impl Hash for Counted<'_> {
6564        fn hash<H: Hasher>(&self, state: &mut H) {
6565            self.text.hash(state);
6566        }
6567    }
6568
6569    fn bounded_alignment(a: &[&'static str], b: &[&'static str], expected: usize) {
6570        let comparisons = Rc::new(Cell::new(0));
6571        let wrap = |values: &[&'static str]| {
6572            values
6573                .iter()
6574                .map(|&text| Counted {
6575                    text,
6576                    comparisons: comparisons.clone(),
6577                })
6578                .collect::<Vec<_>>()
6579        };
6580        // The test values are static; keep the counting type independent of
6581        // production code. The public audit tests separately bound allocation size.
6582        let left = wrap(a);
6583        let right = wrap(b);
6584        let pairs = ordered_pairs(&left, &right);
6585        assert_eq!(pairs.len(), expected);
6586        assert!(pairs.windows(2).all(|w| w[0].0 < w[1].0 && w[0].1 < w[1].1));
6587        assert!(pairs.iter().all(|&(i, j)| a[i] == b[j]));
6588    }
6589
6590    #[test]
6591    fn foreign_alignment_ten_thousand_empty_paragraphs_is_bounded() {
6592        let mut a = vec![""; 10_002];
6593        let mut b = a.clone();
6594        a[0] = "old first";
6595        a[10_001] = "old last";
6596        b[0] = "new first";
6597        b[10_001] = "new last";
6598        bounded_alignment(&a, &b, 10_000);
6599    }
6600
6601    #[test]
6602    fn foreign_alignment_ten_thousand_same_key_deletions_is_bounded() {
6603        let a = vec!["deleted"; 10_000];
6604        let mut b = a.clone();
6605        b[0] = "changed first";
6606        b[9_999] = "changed last";
6607        bounded_alignment(&a, &b, 9_998);
6608    }
6609
6610    #[test]
6611    fn foreign_alignment_ten_thousand_alternating_paragraphs_is_bounded() {
6612        let a: Vec<_> = (0..10_000)
6613            .map(|i| if i % 2 == 0 { "a" } else { "b" })
6614            .collect();
6615        let mut b = a.clone();
6616        b[5_000] = "changed";
6617        bounded_alignment(&a, &b, 9_999);
6618    }
6619    #[test]
6620    fn foreign_alignment_dense_fallback_is_order_stable() {
6621        let a = vec!["a"; 200];
6622        let mut b = vec!["b"; 200];
6623        b[32..168].fill("a");
6624        bounded_alignment(&a, &b, 136);
6625        assert_eq!(ordered_pairs(&a, &b), ordered_pairs(&a, &b));
6626        // 66 edits exceed the Myers budget. The deterministic fallback can
6627        // select fewer anchors, but must preserve order and exact equality.
6628        let alternating: Vec<_> = (0..200)
6629            .map(|i| if i % 2 == 0 { "a" } else { "b" })
6630            .collect();
6631        let mut changed = alternating.clone();
6632        for i in 0..32 {
6633            changed[i * 5] = "changed";
6634        }
6635        changed[199] = "changed";
6636        bounded_alignment(&alternating, &changed, 135);
6637    }
6638
6639    #[test]
6640    fn foreign_alignment_dense_myers_matches_short_edit_lcs() {
6641        for changed in [1, 8, 16, 31] {
6642            let a: Vec<_> = (0..200)
6643                .map(|i| if i % 2 == 0 { "a" } else { "b" })
6644                .collect();
6645            let mut b = a.clone();
6646            for i in 0..changed {
6647                b[i * 5] = "changed";
6648            }
6649            b[199] = "changed";
6650            bounded_alignment(&a, &b, 199 - changed);
6651        }
6652    }
6653}
6654
6655#[cfg(test)]
6656#[cfg_attr(all(coverage_nightly, test), coverage(off))]
6657mod baseline_tests {
6658    use super::*;
6659
6660    fn finding(code: &str, location: &str, message: &str) -> Finding {
6661        Finding::new(code, "word/document.xml", location, message)
6662    }
6663
6664    #[test]
6665    fn a_chain_resolves_to_the_element_it_names() {
6666        let mut dom = Dom::new();
6667        let doc = dom.parse_xdocument(&format!(
6668            r#"<w:document xmlns:w="{W_NS}"><w:body><w:p/><w:p><w:r/><w:r><w:t>x</w:t></w:r></w:p></w:body></w:document>"#,
6669            W_NS = W::URI
6670        ));
6671        let root = dom.root(doc).unwrap();
6672        let t = dom.descendants(root, Some(&W::t()))[0];
6673        let chain = element_path(&dom, t);
6674        assert_eq!(chain, "w:body[0]/w:p[1]/w:r[1]/w:t[0]");
6675        let mut part = Part::new(dom, root);
6676        assert_eq!(part.resolve(&chain), Some(t));
6677        assert_eq!(part.resolve("w:body[0]/w:p[2]"), None);
6678        assert_eq!(part.resolve("w:body[0]/w:p"), None);
6679    }
6680
6681    #[test]
6682    fn identity_drops_element_indices_and_paragraph_ids_from_the_message() {
6683        let a = finding(
6684            "BOOKMARK_CROSSES_REVISION",
6685            "",
6686            "_Hlk1: start w:body[0]/w:p[3]/w:bookmarkStart[0] and end p3, p4-p5.",
6687        );
6688        let b = finding(
6689            "BOOKMARK_CROSSES_REVISION",
6690            "",
6691            "_Hlk1: start w:body[0]/w:p[9]/w:bookmarkStart[0] and end p9, p10-p11.",
6692        );
6693        assert_eq!(a.identity(), b.identity());
6694        assert_eq!(
6695            a.identity().message,
6696            "_Hlk1: start w:body/w:p/w:bookmarkStart and end p#, p#-p#."
6697        );
6698        // The entity a message names stays: another bookmark is another
6699        // finding, and so is a bracket that is no index.
6700        let other = finding(
6701            "BOOKMARK_CROSSES_REVISION",
6702            "",
6703            "_Hlk2: start w:body[0]/w:p[3]/w:bookmarkStart[0] and end p3, p4-p5.",
6704        );
6705        assert_ne!(a.identity(), other.identity());
6706        assert_eq!(normalised("id [a] and [12x]"), "id [a] and [12x]");
6707        assert_eq!(
6708            normalised("header1.p2, t0.row1.cell2 and t0.row1.cell2.p1"),
6709            "p#, p# and p#"
6710        );
6711        // Stories, parts and words are kept.
6712        assert_eq!(
6713            normalised("header1 footnotes commentsExtensible word/document.xml"),
6714            "header1 footnotes commentsExtensible word/document.xml"
6715        );
6716        // Comments and revisions are entities, not positions.
6717        assert_eq!(normalised("c5 on r12 and c5.text"), "c5 on r12 and c5.text");
6718        assert_eq!(normalised("durableId '00251B63'"), "durableId '00251B63'");
6719    }
6720
6721    /// A rerun of fewer operations renumbers paragraphs and mints other
6722    /// ids: the unnumbered key ignores both, and keeps the names.
6723    #[test]
6724    fn unnumbered_keeps_names_and_drops_numbers() {
6725        let here = finding(
6726            "BOOKMARK_CROSSES_REVISION",
6727            "w:body[0]/w:p[3]",
6728            "Clause1: w:ins w:id 12 in w:p[3], 2 times",
6729        );
6730        let there = finding(
6731            "BOOKMARK_CROSSES_REVISION",
6732            "w:body[0]/w:p[9]",
6733            "Clause1: w:ins w:id 40 in w:p[9], 3 times",
6734        );
6735        assert_eq!(here.unnumbered(), there.unnumbered());
6736        assert_eq!(
6737            here.unnumbered(),
6738            "w:body/w:p\u{1f}Clause1: w:ins w:id # in w:p, # times"
6739        );
6740        let other = finding(
6741            "BOOKMARK_CROSSES_REVISION",
6742            "w:body[0]/w:p[3]",
6743            "Clause2: w:ins w:id 12 in w:p[3], 2 times",
6744        );
6745        assert_ne!(here.unnumbered(), other.unnumbered());
6746        assert_eq!(finding("X", "p3", "m").unnumbered(), "p#\u{1f}m");
6747        assert_eq!(
6748            without_numbers("durableId '00251B63', 1st, x7y, #1669, 2.5"),
6749            "durableId '00251B63', 1st, x7y, ##, #.#"
6750        );
6751    }
6752
6753    #[test]
6754    fn identity_keeps_where_the_finding_sits() {
6755        let here = finding("TEXT_INSIDE_DELETION", "w:body[0]/w:p[3]", "w:t in w:del");
6756        let there = finding("TEXT_INSIDE_DELETION", "w:body[0]/w:p[9]", "w:t in w:del");
6757        assert_ne!(here.identity(), there.identity());
6758        let mut audit = here.clone();
6759        audit.set = "a11y".to_string();
6760        assert_ne!(here.identity(), audit.identity());
6761    }
6762
6763    #[test]
6764    fn baseline_matches_one_for_one_by_identity() {
6765        let x = finding("DUPLICATE_DOCPR_ID", "", "docPr id 1 appears 2 times");
6766        let y = finding("DUPLICATE_DOCPR_ID", "", "docPr id 7 appears 2 times");
6767        // The same identity twice in the output, once in the input: one of
6768        // them is new.
6769        let split = baseline(vec![x.clone(), x.clone()], vec![x.clone()]);
6770        assert_eq!(split.baseline, vec![x.clone()]);
6771        assert_eq!(split.new, vec![x.clone()]);
6772        assert!(split.resolved.is_empty());
6773        // One replaced by another at the same count.
6774        let split = baseline(vec![y.clone()], vec![x.clone()]);
6775        assert_eq!(split.new, vec![y.clone()]);
6776        assert!(split.baseline.is_empty());
6777        assert_eq!(split.resolved, vec![x.clone()]);
6778        // Order is each input's own.
6779        let split = baseline(
6780            vec![y.clone(), x.clone()],
6781            vec![x.clone(), y.clone(), x.clone()],
6782        );
6783        assert_eq!(split.baseline, vec![y.clone(), x.clone()]);
6784        assert_eq!(split.resolved, vec![x]);
6785    }
6786
6787    #[test]
6788    fn baselined_text_and_json_name_each_list() {
6789        let x = finding("DUPLICATE_DOCPR_ID", "", "docPr id 1 appears 2 times");
6790        let empty = Baselined::default();
6791        assert_eq!(
6792            baselined_text(&empty, false),
6793            "new: none\nalready in the input: none\n\
6794             PASS: no new finding (authorship not checked: pass --author NAME)\n"
6795        );
6796        assert_eq!(
6797            baselined_json(&empty, false).unwrap(),
6798            "{\"resolved\":[]}\n\
6799             {\"authors\":[],\"verdict\":{\"pass\":true,\"findings\":0,\"changes\":0,\
6800             \"comments\":0,\"authored\":false}}\n"
6801        );
6802        let split = Baselined {
6803            new: vec![x.clone()],
6804            baseline: vec![x.clone()],
6805            resolved: vec![x.clone()],
6806            ..Baselined::default()
6807        };
6808        let line = finding_line(&x);
6809        assert_eq!(
6810            baselined_text(&split, false),
6811            format!(
6812                "resolved: 1 (in the input, not in this file)\n{line}\
6813                 new: 1\n{line}already in the input: 1 (not yours)\n\
6814                 FAIL: 1 finding (0 changes, 0 comments); not ready to deliver\n"
6815            )
6816        );
6817        let json = baselined_json(&split, false).unwrap();
6818        let rows: Vec<serde_json::Value> = json
6819            .lines()
6820            .map(|l| serde_json::from_str(l).unwrap())
6821            .collect();
6822        assert_eq!(rows[0]["status"], "new");
6823        assert_eq!(rows[1]["status"], "baseline");
6824        assert_eq!(rows[0]["code"], "DUPLICATE_DOCPR_ID");
6825        assert_eq!(rows[2]["resolved"][0]["code"], "DUPLICATE_DOCPR_ID");
6826        assert!(rows[2]["resolved"][0].get("status").is_none());
6827        assert_eq!(
6828            rows[3],
6829            serde_json::json!({
6830                "authors": [],
6831                "verdict": {
6832                    "pass": false,
6833                    "findings": 1,
6834                    "changes": 0,
6835                    "comments": 0,
6836                    "authored": false,
6837                },
6838            })
6839        );
6840    }
6841
6842    #[test]
6843    fn input_notice_counts_errors_and_warnings_but_not_info() {
6844        let warning = finding("DUPLICATE_DOCPR_ID", "", "w");
6845        let error = finding("TEXT_INSIDE_DELETION", "", "e");
6846        let mut info = warning.clone();
6847        info.severity = "info".to_string();
6848        assert_eq!(warning.severity, "warning");
6849        assert_eq!(error.severity, "error");
6850        assert_eq!(input_notice(&[], "a.docx"), None);
6851        assert_eq!(input_notice(std::slice::from_ref(&info), "a.docx"), None);
6852        assert_eq!(
6853            input_notice(std::slice::from_ref(&warning), "a.docx").unwrap(),
6854            "input has 1 validity warning; jubarte validate a.docx lists it"
6855        );
6856        assert_eq!(
6857            input_notice(&[warning.clone(), warning.clone(), info], "a.docx").unwrap(),
6858            "input has 2 validity warnings; jubarte validate a.docx lists them"
6859        );
6860        assert_eq!(
6861            input_notice(&[error.clone(), error.clone()], "a.docx").unwrap(),
6862            "input has 2 validity errors; jubarte validate a.docx lists them"
6863        );
6864        assert_eq!(
6865            input_notice(&[error, warning.clone(), warning.clone()], "my file.docx").unwrap(),
6866            "input has 1 validity error and 2 warnings; \
6867             jubarte validate 'my file.docx' lists them"
6868        );
6869    }
6870}
6871
6872#[cfg(test)]
6873mod page_field_tests {
6874    use super::*;
6875
6876    /// Whether the one paragraph of `runs` holds a PAGE or NUMPAGES field.
6877    fn holds(runs: &str) -> bool {
6878        let mut dom = Dom::new();
6879        let doc = dom.parse_xdocument(&format!(r#"<w:p xmlns:w="{}">{runs}</w:p>"#, W::URI));
6880        let p = dom.root(doc).unwrap();
6881        holds_page_field(&dom, p)
6882    }
6883
6884    fn field(pieces: &[&str]) -> String {
6885        let code: String = pieces
6886            .iter()
6887            .map(|piece| {
6888                format!(r#"<w:r><w:instrText xml:space="preserve">{piece}</w:instrText></w:r>"#)
6889            })
6890            .collect();
6891        format!(
6892            r#"<w:r><w:fldChar w:fldCharType="begin"/></w:r>{code}<w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>1</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r>"#
6893        )
6894    }
6895
6896    /// Word splits a field code across runs: `PA` + `GE` is a PAGE field.
6897    #[test]
6898    fn a_page_code_split_across_runs_is_a_page_field() {
6899        assert!(holds(&field(&[" PA", "GE "])));
6900        assert!(holds(&field(&[" NUM", "PAGES \\* Arabic "])));
6901        assert!(holds(&field(&[" PAGE "])));
6902    }
6903
6904    /// The code's first word decides, read whole: `PAGE` + `REF` is a
6905    /// PAGEREF, and a PAGE inside another field's result is still found.
6906    #[test]
6907    fn only_the_whole_first_word_counts() {
6908        assert!(!holds(&field(&[" PAGE", "REF _Ref1 \\h "])));
6909        assert!(!holds(&field(&[" REF ", "PAGE "])));
6910        let nested = format!(
6911            r#"<w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText> IF 1 = 1 </w:instrText></w:r>{}<w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r>"#,
6912            field(&[" PA", "GE "])
6913        );
6914        assert!(holds(&nested));
6915    }
6916
6917    /// A simple field, a deleted code, and code whose field began in an
6918    /// earlier paragraph.
6919    #[test]
6920    fn simple_deleted_and_continued_codes_count() {
6921        assert!(holds(
6922            r#"<w:fldSimple w:instr=" PAGE "><w:r><w:t>1</w:t></w:r></w:fldSimple>"#
6923        ));
6924        assert!(holds(
6925            r#"<w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:delInstrText>PA</w:delInstrText></w:r><w:r><w:delInstrText>GE</w:delInstrText></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r>"#
6926        ));
6927        assert!(holds(r#"<w:r><w:instrText> PAGE </w:instrText></w:r>"#));
6928        assert!(holds(
6929            r#"<w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText> PA</w:instrText></w:r><w:r><w:instrText>GE </w:instrText></w:r>"#
6930        ));
6931        assert!(!holds(r#"<w:r><w:t>PAGE</w:t></w:r>"#));
6932    }
6933}
6934
6935#[cfg(test)]
6936#[cfg_attr(all(coverage_nightly, test), coverage(off))]
6937mod unreadable_part_tests {
6938    use super::*;
6939
6940    fn pkg() -> PartFs {
6941        PartFs::open(include_bytes!(
6942            "../../../tests/fixtures/redline/original.docx"
6943        ))
6944        .unwrap()
6945    }
6946
6947    fn codes(findings: &[Finding]) -> Vec<(&str, &str)> {
6948        let mut out: Vec<(&str, &str)> = findings
6949            .iter()
6950            .map(|f| (f.code.as_str(), f.part.as_str()))
6951            .collect();
6952        out.sort_unstable();
6953        out.dedup();
6954        out
6955    }
6956
6957    /// Every check skips a part that holds no element: each reports
6958    /// nothing of its own, and the content-type pass names the parts that
6959    /// do not parse.
6960    #[test]
6961    fn checks_skip_parts_with_no_root_element() {
6962        let mut package = pkg();
6963        let r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
6964        for (kind, target) in [
6965            ("comments", "comments.xml"),
6966            ("header", "header1.xml"),
6967            ("footnotes", "footnotes.xml"),
6968        ] {
6969            package.add_document_relationship("word/document.xml", &format!("{r}/{kind}"), target);
6970        }
6971        for name in [
6972            "word/document.xml",
6973            "word/styles.xml",
6974            "word/numbering.xml",
6975            "word/settings.xml",
6976            "word/comments.xml",
6977            "word/header1.xml",
6978            "word/footnotes.xml",
6979        ] {
6980            package.set_part(name, b"no element here".to_vec());
6981        }
6982        package.set_part("word/fontTable.xml", b"<".to_vec());
6983        let findings = ring1(&package);
6984        let found = codes(&findings);
6985        assert!(
6986            found.contains(&("MALFORMED_XML", "word/fontTable.xml")),
6987            "{found:?}"
6988        );
6989        // The per-part checks skip a part with no root element instead of
6990        // inventing findings about its content. Whether a rootless part
6991        // should itself be reported is open: today it is not, so a fix that
6992        // reports it as MALFORMED_XML still passes here.
6993        for (code, part) in &found {
6994            assert!(
6995                matches!(*code, "MALFORMED_XML" | "MISSING_CONTENT_TYPE")
6996                    || (*code, *part) == ("COMMENT_PARTS_INCONSISTENT", "word/comments.xml"),
6997                "{code}: {found:?}"
6998            );
6999        }
7000    }
7001
7002    /// With no main document part the body checks have nothing to read.
7003    #[test]
7004    fn checks_without_a_main_part_report_only_the_package() {
7005        let mut package = pkg();
7006        package.remove_part("word/document.xml");
7007        package.remove_package_relationships_by_type(
7008            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
7009        );
7010        let findings = ring1(&package);
7011        for f in &findings {
7012            assert_ne!(f.part, "word/document.xml", "{f:?}");
7013        }
7014    }
7015}