jubarte-redlines 0.9.0

Lossless DOCX redline engine — compare two Word documents into a tracked-changes document that opens cleanly in Microsoft Word; list, accept, or reject revisions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: AGPL-3.0-only

//! Produce tracked-revision markup (M4.4). Core of
//! `ProduceDocumentWithTrackedRevisions` for the paragraph-text case.
//!
//! Consumes the LCS-tagged atom stream and rebuilds a `<w:document>` where
//! inserted content is wrapped in `<w:ins>` and deleted content in `<w:del>`
//! (with `<w:t>` → `<w:delText>`), each carrying `w:id`/`w:author`/`w:date`.
//!
//! NOTE: the full TS producer additionally handles inserted/deleted paragraph
//! marks (paragraph merge/split), tables, footnotes, moves, and format changes
//! (WmlComparer.ts:2222+, plus fixups). This core covers runs of text within
//! paragraphs — the common case — and is the base those refinements extend.

use std::sync::atomic::{AtomicU64, Ordering};

use crate::namespaces::{PT, W};
use crate::util::group_adjacent;
use crate::xmllinq::{Dom, NodeId, XNamespace};

use super::lcs::TaggedAtom;
use super::{CorrelationStatus, WmlComparerSettings};

static REV_ID: AtomicU64 = AtomicU64::new(1);

/// Deleted opaque subtrees (drawings, text boxes, `mc:AlternateContent`) are
/// cloned verbatim, so their nested text still reads `w:t`. `w:t` inside `w:del`
/// is non-conformant — Word writes `w:delText`. Rename every descendant `w:t`
/// in the cloned subtree to `w:delText` for pure deletions only.
///
/// **MovedSource:** Word Compare keeps `w:t` inside `w:moveFrom` (broken_ones_two
/// oracle). Renaming to `delText` invited nested `w:del` (wrap_bare) and Word's
/// "unreadable content" dialog. Inserted / moved-destination keep `w:t`.
/// `w:instrText` is left untouched — the `W::t()` filter excludes it.
fn delete_text_in_opaque(dom: &mut Dom, node: NodeId, status: CorrelationStatus) {
    if matches!(status, CorrelationStatus::Deleted) {
        // Hoist the name out of the loop — `W::name` allocates a fresh `XName`
        // on each call; `XName` is `Arc`-cheap to clone.
        let del_text = W::del_text();
        for t in dom.descendants(node, Some(&W::t())) {
            dom.set_name(t, del_text.clone());
        }
    }
}

fn next_rev_id() -> String {
    REV_ID.fetch_add(1, Ordering::Relaxed).to_string()
}

/// Build the redline `<w:document>` node from the tagged atom stream.
pub fn produce_document(
    dom: &mut Dom,
    tagged: &[TaggedAtom],
    settings: &WmlComparerSettings,
) -> NodeId {
    let doc = dom.new_document();
    let document = dom.new_element(W::document());
    dom.set_attribute_value(document, &XNamespace::xmlns().name("w"), Some(W::URI));
    dom.set_attribute_value(document, &XNamespace::xmlns().name("pt14"), Some(PT::URI));
    let body = dom.new_element(W::body());

    // Split the stream into paragraphs: a pPr atom ends a paragraph.
    let mut para: Vec<TaggedAtom> = Vec::new();
    for t in tagged {
        let is_ppr = dom.name_is(t.atom.content_element, &W::p_pr());
        if is_ppr {
            let p = build_paragraph(dom, &para, t, settings);
            dom.add(body, p);
            para.clear();
        } else {
            para.push(t.clone());
        }
    }
    // trailing content with no paragraph mark
    if !para.is_empty() {
        let synthetic = TaggedAtom {
            atom: para[0].atom.clone(),
            status: CorrelationStatus::Equal,
        };
        let p = build_paragraph(dom, &para, &synthetic, settings);
        dom.add(body, p);
    }

    dom.add(document, body);
    dom.add(doc, document);
    doc
}

/// Build one `<w:p>` from its run atoms + the paragraph-mark atom.
fn build_paragraph(
    dom: &mut Dom,
    run_atoms: &[TaggedAtom],
    ppr_atom: &TaggedAtom,
    settings: &WmlComparerSettings,
) -> NodeId {
    let p = dom.new_element(W::p());

    // Carry the paragraph's pPr (clone the content element if it's a real pPr).
    if dom.name_is(ppr_atom.atom.content_element, &W::p_pr())
        && dom.has_elements(ppr_atom.atom.content_element)
    {
        let ppr = dom.clone_subtree(ppr_atom.atom.content_element);
        dom.add(p, ppr);
    }

    // Group consecutive atoms by status, emit runs wrapped per status.
    let groups = group_adjacent(run_atoms.iter().cloned(), |t| t.status);
    for (status, group) in groups {
        // Concatenate the text of this status-run (text atoms only).
        let text: String = group
            .iter()
            .filter(|t| {
                let n = dom.name(t.atom.content_element);
                n == Some(W::t()) || n == Some(W::del_text())
            })
            .map(|t| dom.value_str(t.atom.content_element).into_owned())
            .collect();
        if text.is_empty() {
            continue;
        }
        match status {
            CorrelationStatus::Inserted => {
                let ins = wrap_run(dom, &text, false, settings, CorrelationStatus::Inserted);
                dom.add(p, ins);
            }
            CorrelationStatus::Deleted => {
                let del = wrap_run(dom, &text, true, settings, CorrelationStatus::Deleted);
                dom.add(p, del);
            }
            _ => {
                // Equal: a plain run.
                let r = build_text_run(dom, &text, false);
                dom.add(p, r);
            }
        }
    }
    p
}

/// Build `<w:r><w:t>text</w:t></w:r>` (or delText when `deleted`).
fn build_text_run(dom: &mut Dom, text: &str, deleted: bool) -> NodeId {
    let r = dom.new_element(W::r());
    let t = dom.new_element(if deleted { W::del_text() } else { W::t() });
    if text.starts_with(' ') || text.ends_with(' ') {
        dom.set_attribute_value(t, &XNamespace::xml().name("space"), Some("preserve"));
    }
    dom.add_text(t, text);
    dom.add(r, t);
    r
}

/// Wrap a run in `<w:ins>`/`<w:del>` with id/author/date.
fn wrap_run(
    dom: &mut Dom,
    text: &str,
    deleted: bool,
    settings: &WmlComparerSettings,
    status: CorrelationStatus,
) -> NodeId {
    let wrapper_name = if matches!(status, CorrelationStatus::Deleted) {
        W::del()
    } else {
        W::ins()
    };
    let wrapper = dom.new_element(wrapper_name);
    dom.set_attribute_value(wrapper, &W::id(), Some(&next_rev_id()));
    dom.set_attribute_value(wrapper, &W::author(), Some(&settings.author_for_revisions));
    dom.set_attribute_value(wrapper, &W::date(), Some(&settings.date_time_for_revisions));
    let r = build_text_run(dom, text, deleted);
    dom.add(wrapper, r);
    wrapper
}

// ─────────────────────────────────────────────────────────────────────────────
// M4.E — faithful reassembly: Flatten → AssembleAncestorUnids → CoalesceRecurse.
// (Added alongside the M4.4 shortcut producer above, which stays until M4.I.)
// ─────────────────────────────────────────────────────────────────────────────

use super::atoms::{ComparisonUnit, ComparisonUnitAtom, CorrelatedSequence};
use crate::unid::generate_unid;

fn flatten_atoms(units: &[ComparisonUnit]) -> Vec<ComparisonUnitAtom> {
    units
        .iter()
        .flat_map(|u| u.descendant_atoms().into_iter().cloned())
        .collect()
}

/// True when a before-side atom carries `pt:PreDelete="orig"` on itself or an
/// ancestor (word-mode flattened A-only pre-existing deletion). Equal emit
/// would drop the stamp (content comes from AFTER); force del+ins instead.
fn atom_has_predelete_orig(dom: &Dom, atom: &ComparisonUnitAtom) -> bool {
    let pre = PT::name("PreDelete");
    if dom.attribute(atom.content_element, &pre) == Some(crate::comparer::PREDELETE_STAMP_ORIG) {
        return true;
    }
    atom.ancestor_elements
        .iter()
        .any(|&a| dom.attribute(a, &pre) == Some(crate::comparer::PREDELETE_STAMP_ORIG))
}

/// M4.E.1 — `FlattenToComparisonUnitAtomList` (:4141): nested correlated tree →
/// flat status-tagged atom list. Equal carries content/ancestors from the AFTER
/// atom and a link to the BEFORE atom; zip truncates to the shorter side.
///
/// M-MOVE S1 exception: when the BEFORE atom is a PreDelete-orig span, emit
/// Deleted(before)+Inserted(after) instead of Equal so history survives even
/// if an upstream correlation path lost the salt (m36 / fresh-p4).
pub fn flatten_to_comparison_unit_atom_list(
    dom: &Dom,
    seqs: &[CorrelatedSequence],
) -> Vec<ComparisonUnitAtom> {
    let mut out = Vec::new();
    for cs in seqs {
        match cs.correlation_status {
            CorrelationStatus::Equal => {
                let before = flatten_atoms(cs.com_units_1.as_deref().unwrap_or(&[]));
                let after = flatten_atoms(cs.com_units_2.as_deref().unwrap_or(&[]));
                // M-MOVE S1: if any BEFORE atom is a PreDelete-orig span, emit
                // the whole before run as Deleted and the whole after run as
                // Inserted (paragraph/word granularity). Per-atom del+ins
                // confetti fails convert_stamped coalescing and m36.
                if before.iter().any(|b| atom_has_predelete_orig(dom, b)) {
                    for b in &before {
                        let mut del = b.clone();
                        del.correlation_status = CorrelationStatus::Deleted;
                        out.push(del);
                    }
                    for a in &after {
                        let mut ins = a.clone();
                        ins.correlation_status = CorrelationStatus::Inserted;
                        out.push(ins);
                    }
                    continue;
                }
                for (b, a) in before.iter().zip(after.iter()) {
                    let mut atom = a.clone();
                    atom.correlation_status = CorrelationStatus::Equal;
                    atom.content_element_before = Some(b.content_element);
                    atom.comparison_unit_atom_before = Some(std::sync::Arc::new(b.clone()));
                    out.push(atom);
                }
            }
            CorrelationStatus::Deleted => {
                for a in flatten_atoms(cs.com_units_1.as_deref().unwrap_or(&[])) {
                    let mut x = a;
                    x.correlation_status = CorrelationStatus::Deleted;
                    out.push(x);
                }
            }
            CorrelationStatus::Inserted => {
                for a in flatten_atoms(cs.com_units_2.as_deref().unwrap_or(&[])) {
                    let mut x = a;
                    x.correlation_status = CorrelationStatus::Inserted;
                    out.push(x);
                }
            }
            other => panic!("Internal error: unexpected status in flatten: {other:?}"),
        }
    }
    out
}

fn is_ppr_atom(dom: &Dom, atom: &ComparisonUnitAtom) -> bool {
    dom.name_is(atom.content_element, &W::p_pr())
}
fn atom_in_textbox(dom: &Dom, atom: &ComparisonUnitAtom) -> bool {
    let txbx = W::txbx_content();
    atom.ancestor_elements
        .iter()
        .any(|&a| dom.name(a).as_ref() == Some(&txbx))
}

/// M4.E.2 — `AssembleAncestorUnidsInOrderToRebuildXmlTreeProperly` (:3974).
/// Three phases (see WmlComparer.ts): A copy before→after pPr ancestor Unids;
/// PRODUCE-UNID-01: (ancestor-elements chain, its minted unid chain) memo.
type UnidChainMemo = Option<(std::sync::Arc<[NodeId]>, std::sync::Arc<[String]>)>;

/// B seed ancestor_unids from the paragraph mark (reverse walk, minting missing);
/// C fix text boxes in a second reverse pass.
pub fn assemble_ancestor_unids(dom: &mut Dom, atoms: &mut [ComparisonUnitAtom]) {
    let unid = PT::unid();
    let footnote = W::footnote();
    let endnote = W::endnote();

    // ── Phase A ───────────────────────────────────────────────────────────────
    for atom in atoms.iter() {
        let mut do_set = false;
        if is_ppr_atom(dom, atom) {
            if atom_in_textbox(dom, atom) {
                do_set = true;
            }
            if atom.correlation_status == CorrelationStatus::Equal {
                do_set = true;
            }
        }
        if do_set && let Some(before) = &atom.comparison_unit_atom_before {
            let after_anc = &atom.ancestor_elements;
            let before_anc = &before.ancestor_elements;
            if after_anc.len() == before_anc.len() {
                let pairs: Vec<(NodeId, Option<String>)> = after_anc
                    .iter()
                    .zip(before_anc.iter())
                    .filter_map(|(&aft, &bef)| {
                        match (dom.attribute(aft, &unid), dom.attribute(bef, &unid)) {
                            (Some(_), Some(bv)) => Some((aft, Some(bv.to_string()))),
                            _ => None,
                        }
                    })
                    .collect();
                for (aft, bv) in pairs {
                    dom.set_attribute_value(aft, &unid, bv.as_deref());
                }
            }
        }
    }

    // deepest-ancestor (footnote/endnote root) override for index 0.
    let deepest_unid: Option<String> = atoms.last().and_then(|last| {
        last.ancestor_elements.first().and_then(|&outer| {
            let nm = dom.name(outer);
            if nm.as_ref() == Some(&footnote) || nm.as_ref() == Some(&endnote) {
                dom.attribute(outer, &unid).map(|s| s.to_string())
            } else {
                None
            }
        })
    });

    // helper: unid of an ancestor element, minting if absent.
    let unid_or_mint = |dom: &mut Dom, ae: NodeId| -> String {
        match dom.attribute(ae, &unid) {
            Some(u) => u.to_string(),
            None => {
                let g = generate_unid();
                dom.set_attribute_value(ae, &unid, Some(&g));
                g
            }
        }
    };

    // ── Phase B (reverse) ──────────────────────────────────────────────────────
    let mut current: Option<std::sync::Arc<[String]>> = None;
    // PATH-01: track the shared Arc chain (not a cloned Vec).
    let mut current_elems: Option<std::sync::Arc<[NodeId]>> = None;
    // PRODUCE-UNID-01: atoms of one run share an ancestor_elements Arc — reuse
    // the chain built for the previous atom instead of rebuilding per atom.
    let mut memo: UnidChainMemo = None;
    for atom in atoms.iter_mut().rev() {
        if is_ppr_atom(dom, atom) && !atom_in_textbox(dom, atom) {
            let mut cur: Vec<String> = atom
                .ancestor_elements
                .iter()
                .map(|&ae| unid_or_mint(dom, ae))
                .collect();
            if let Some(d) = &deepest_unid
                && let Some(first) = cur.first_mut()
            {
                *first = d.clone();
            }
            let cur: std::sync::Arc<[String]> = cur.into();
            atom.ancestor_unids = Some(std::sync::Arc::clone(&cur));
            current = Some(cur);
            current_elems = Some(std::sync::Arc::clone(&atom.ancestor_elements));
            memo = None;
        } else {
            let prefix = current.clone().unwrap_or_default();
            // Borrow the following paragraph's Unid prefix to bridge MATCHED A/B
            // paragraphs (different NodeIds, parallel structure) so their content
            // shares one paragraph Unid. Stop borrowing where the ancestor ELEMENT
            // TYPES diverge: blindly borrowing the whole `prefix.len()` desyncs
            // ancestor_unids from ancestor_elements when this atom's ancestor shape
            // differs from the next paragraph's (e.g. text in an outer table cell
            // that precedes a nested table) — CoalesceRecurse then nests block
            // content in a run (`w:p` inside `w:r`, Word "unreadable",
            // sd-2672-nested-table_sd-2672-sdt-table). Name-based (not NodeId
            // identity) so cross-tree matched paragraphs still share a Unid (m21).
            if let Some((elems, unids)) = &memo
                && std::sync::Arc::ptr_eq(elems, &atom.ancestor_elements)
            {
                atom.ancestor_unids = Some(std::sync::Arc::clone(unids));
                continue;
            }
            let prev_elems = current_elems.clone().unwrap_or_default();
            let mut share = 0usize;
            while share < prefix.len()
                && share < atom.ancestor_elements.len()
                && share < prev_elems.len()
                && dom.name(atom.ancestor_elements[share]) == dom.name(prev_elems[share])
            {
                share += 1;
            }
            let mut full: Vec<String> = prefix[..share].to_vec();
            for &ae in atom.ancestor_elements.iter().skip(share) {
                full.push(unid_or_mint(dom, ae));
            }
            if let Some(d) = &deepest_unid
                && let Some(first) = full.first_mut()
            {
                *first = d.clone();
            }
            let full: std::sync::Arc<[String]> = full.into();
            memo = Some((
                std::sync::Arc::clone(&atom.ancestor_elements),
                std::sync::Arc::clone(&full),
            ));
            atom.ancestor_unids = Some(full);
        }
    }

    // ── Phase C (reverse, text-box fix) ─────────────────────────────────────────
    let mut current: Option<std::sync::Arc<[String]>> = None;
    let mut skip_until_ppr = false;
    let mut memo: UnidChainMemo = None;
    for atom in atoms.iter_mut().rev() {
        if let Some(cur) = &current
            && atom.ancestor_elements.len() < cur.len()
        {
            skip_until_ppr = true;
            current = None;
            memo = None;
            continue;
        }
        if is_ppr_atom(dom, atom) {
            if !atom_in_textbox(dom, atom) {
                skip_until_ppr = true;
                current = None;
                memo = None;
                continue;
            }
            // text-box pPr: rebuild prefix (must already have Unids — Phase B minted them)
            let cur: Vec<String> = atom
                .ancestor_elements
                .iter()
                .map(|&ae| {
                    dom.attribute(ae, &unid)
                        .map(|s| s.to_string())
                        .expect("text-box pPr ancestor must have a Unid (Phase B)")
                })
                .collect();
            let cur: std::sync::Arc<[String]> = cur.into();
            atom.ancestor_unids = Some(std::sync::Arc::clone(&cur));
            current = Some(cur);
            skip_until_ppr = false;
            memo = None;
            continue;
        }
        if skip_until_ppr {
            continue;
        }
        if let Some(cur) = &current {
            if let Some((elems, unids)) = &memo
                && std::sync::Arc::ptr_eq(elems, &atom.ancestor_elements)
            {
                atom.ancestor_unids = Some(std::sync::Arc::clone(unids));
                continue;
            }
            let extra: Vec<NodeId> = atom
                .ancestor_elements
                .iter()
                .skip(cur.len())
                .copied()
                .collect();
            let mut full: Vec<String> = cur.as_ref().to_vec();
            for ae in extra {
                full.push(unid_or_mint(dom, ae));
            }
            let full: std::sync::Arc<[String]> = full.into();
            memo = Some((
                std::sync::Arc::clone(&atom.ancestor_elements),
                std::sync::Arc::clone(&full),
            ));
            atom.ancestor_unids = Some(full);
        }
    }
}

// ── M4.E.3-E.7 — CoalesceRecurse + ReconstructElement ────────────────────────

/// `GetXmlSpaceAttribute` — `Some("preserve")` when leading/trailing whitespace.
fn xml_space_attr(text: &str) -> Option<&'static str> {
    match (text.chars().next(), text.chars().last()) {
        (Some(f), _) if f.is_whitespace() => Some("preserve"),
        (_, Some(l)) if l.is_whitespace() => Some("preserve"),
        _ => None,
    }
}

fn status_str(s: CorrelationStatus) -> &'static str {
    match s {
        CorrelationStatus::Deleted => "Deleted",
        CorrelationStatus::Inserted => "Inserted",
        CorrelationStatus::MovedSource => "MovedSource",
        CorrelationStatus::MovedDestination => "MovedDestination",
        CorrelationStatus::FormatChanged => "FormatChanged",
        CorrelationStatus::Equal => "Equal",
        _ => "Nil",
    }
}

/// Stable first-key-seen bucket grouping (port of `groupByKey`).
fn group_by_key_stable<'a, K: Eq + std::hash::Hash + Clone>(
    items: &[&'a ComparisonUnitAtom],
    key: impl Fn(&ComparisonUnitAtom) -> K,
) -> Vec<(K, Vec<&'a ComparisonUnitAtom>)> {
    // Groups hold references, not owned atoms: coalesce_recurse re-groups every
    // atom at every nesting level, and ComparisonUnitAtom is fat (sha1_hash +
    // ancestor_unids: Vec<String> + a recursive Box<before-atom>), so cloning
    // per level was the dominant produce-phase allocation (samply). Grouping
    // semantics are unchanged — only ownership.
    let mut order: Vec<K> = Vec::new();
    let mut map: std::collections::HashMap<K, Vec<&'a ComparisonUnitAtom>> =
        std::collections::HashMap::new();
    for it in items {
        let k = key(it);
        if !map.contains_key(&k) {
            order.push(k.clone());
        }
        map.entry(k).or_default().push(*it);
    }
    order
        .into_iter()
        .map(|k| {
            let v = map.remove(&k).unwrap();
            (k, v)
        })
        .collect()
}

/// Add the `pt:Status` (+ move/format) attributes to a constructed node.
fn tag_status(dom: &mut Dom, node: NodeId, status: CorrelationStatus, atom: &ComparisonUnitAtom) {
    match status {
        CorrelationStatus::Deleted => {
            dom.set_attribute_value(node, &PT::status(), Some("Deleted"));
        }
        CorrelationStatus::Inserted => {
            dom.set_attribute_value(node, &PT::status(), Some("Inserted"));
        }
        CorrelationStatus::MovedSource | CorrelationStatus::MovedDestination => {
            dom.set_attribute_value(node, &PT::status(), Some(status_str(status)));
            if let Some(id) = atom.move_group_id {
                dom.set_attribute_value(node, &PT::name("MoveGroupId"), Some(&id.to_string()));
                dom.set_attribute_value(
                    node,
                    &PT::name("MoveName"),
                    Some(atom.move_name.as_deref().unwrap_or("")),
                );
            }
        }
        CorrelationStatus::FormatChanged => {
            dom.set_attribute_value(node, &PT::status(), Some("FormatChanged"));
            if let Some(fc) = &atom.format_change {
                if let Some(old) = fc.old_run_properties {
                    let s = dom.serialize_element(old);
                    dom.set_attribute_value(node, &PT::name("OldRPr"), Some(&s));
                }
                // M81: body pilcrow format change carries projected old pPr.
                if let Some(old) = fc.old_para_properties {
                    let s = dom.serialize_element(old);
                    dom.set_attribute_value(node, &PT::name("OldPPr"), Some(&s));
                }
            }
        }
        _ => {}
    }
}

fn is_txbx_from_level(dom: &Dom, atom: &ComparisonUnitAtom, level: usize) -> bool {
    let txbx = W::txbx_content();
    atom.ancestor_elements
        .iter()
        .skip(level)
        .any(|&a| dom.name(a).as_ref() == Some(&txbx))
}

/// M463 — final-serialization pass: every `w:ins`/`w:del` whose element
/// content is exactly OMML math (`m:oMath`/`m:oMathPara`) is unwrapped, and
/// the revision state is rewritten INSIDE the math the way Word Compare
/// writes it. Runs AFTER all mesh/finalize passes, which reason about the
/// outer-wrapped shape.
///
/// LibreOffice renders Word's internal-marked math as placeholder boxes; the
/// outer wrap rendered the live formula instead — every formula's ink
/// diverged from the oracle (math family n=28, mean ≈58; math_func ×
/// math_groupchr 54.6).
pub fn convert_outer_math_wraps_to_internal(
    dom: &mut Dom,
    root: NodeId,
    settings: &WmlComparerSettings,
) {
    let math_names = [
        crate::namespaces::M::name("oMath"),
        crate::namespaces::M::name("oMathPara"),
    ];
    // Next free revision id — internal marks need fresh ones.
    let mut max_id: u32 = 0;
    for e in dom.descendants(root, None) {
        if let Some(v) = dom.attribute(e, &W::id())
            && let Ok(n) = v.parse::<u32>()
        {
            max_id = max_id.max(n);
        }
    }
    let mut id_gen = max_id + 1;
    for rev_name in [W::ins(), W::del()] {
        let wrappers: Vec<NodeId> = dom
            .descendants(root, Some(&rev_name))
            .into_iter()
            .filter(|&w| {
                let kids = dom.elements(w, None);
                !kids.is_empty()
                    && kids
                        .iter()
                        .all(|&k| dom.name(k).is_some_and(|n| math_names.contains(&n)))
            })
            .collect();
        for w in wrappers {
            let maths: Vec<NodeId> = dom.elements(w, None);
            for m in &maths {
                mark_math_revisions_internally(dom, *m, &rev_name, settings, &mut id_gen);
            }
            for m in maths {
                dom.remove(m);
                dom.add_before_self(w, m);
            }
            dom.remove(w);
        }
    }
}

/// Rewrite a `m:oMath(Para)` subtree so its revision state lives INSIDE the
/// math, the way Word Compare writes it:
/// - every `m:r` moves its children (m:rPr?, w:rPr?, m:t…) into a
///   `w:ins`/`w:del` child; a `w:rPr` with Cambria Math rFonts is
///   materialized when the run stores none (Word always writes it);
/// - every `m:ctrlPr` moves its `w:rPr` (materialized likewise) into the
///   same mark.
///
/// `m:t` stays `m:t` under `w:del` — math content never becomes delText.
fn mark_math_revisions_internally(
    dom: &mut Dom,
    math_root: NodeId,
    rev_name: &crate::xmllinq::XName,
    settings: &WmlComparerSettings,
    id_gen: &mut u32,
) {
    let m_r = crate::namespaces::M::name("r");
    let m_ctrl_pr = crate::namespaces::M::name("ctrlPr");
    let w_rpr = W::r_pr();
    let cambria = |dom: &mut Dom| -> NodeId {
        let rpr = dom.new_element(W::r_pr());
        let fonts = dom.new_element(W::name("rFonts"));
        dom.set_attribute_value(fonts, &W::name("ascii"), Some("Cambria Math"));
        dom.set_attribute_value(fonts, &W::name("hAnsi"), Some("Cambria Math"));
        dom.add(rpr, fonts);
        rpr
    };
    let mut new_mark = |dom: &mut Dom| -> NodeId {
        let w = dom.new_element(rev_name.clone());
        dom.set_attribute_value(w, &W::id(), Some(&id_gen.to_string()));
        *id_gen += 1;
        dom.set_attribute_value(w, &W::author(), Some(&settings.author_for_revisions));
        dom.set_attribute_value(w, &W::date(), Some(&settings.date_time_for_revisions));
        w
    };
    let targets: Vec<(NodeId, bool)> = dom
        .descendants(math_root, Some(&m_r))
        .into_iter()
        .map(|n| (n, false))
        .chain(
            dom.descendants(math_root, Some(&m_ctrl_pr))
                .into_iter()
                .map(|n| (n, true)),
        )
        .collect();
    for (node, is_ctrl_pr) in targets {
        // Skip runs that already carry a revision mark (defensive).
        if dom
            .elements(node, None)
            .iter()
            .any(|&c| dom.name(c).is_some_and(|n| n == W::ins() || n == W::del()))
        {
            continue;
        }
        let children: Vec<NodeId> = dom.elements(node, None);
        let mark = new_mark(dom);
        let mut saw_wrpr = false;
        for c in children {
            let is_m_rpr = dom.name(c) == Some(crate::namespaces::M::name("rPr"));
            saw_wrpr |= dom.name(c).as_ref() == Some(&w_rpr);
            dom.remove(c);
            dom.add(mark, c);
            // Materialize the math w:rPr right after m:rPr, before m:t.
            let _ = is_m_rpr;
        }
        if !saw_wrpr {
            let rpr = cambria(dom);
            // After m:rPr when present, else first.
            let anchor = dom
                .elements(mark, None)
                .into_iter()
                .find(|&c| dom.name(c) == Some(crate::namespaces::M::name("rPr")));
            match anchor {
                Some(a) => dom.add_after_self(a, rpr),
                None => match dom.elements(mark, None).first().copied() {
                    Some(first) => dom.add_before_self(first, rpr),
                    None => dom.add(mark, rpr),
                },
            }
        }
        let _ = is_ctrl_pr;
        dom.add(node, mark);
    }
}

/// M4.E.3-E.7 — `CoalesceRecurse` (:6024). Returns the constructed nodes for this
/// level. `id_gen` is the `s_MaxId` analog (oMath revision ids).
pub fn coalesce_recurse(
    dom: &mut Dom,
    atoms: &[&ComparisonUnitAtom],
    level: usize,
    settings: &WmlComparerSettings,
    id_gen: &mut u32,
) -> Vec<NodeId> {
    // Step 1 — group by (ancestor Unid, element type) at this level (stable), drop
    // empty keys. A Unid must map to ONE element type; when the correlation assigns
    // the SAME Unid to different types (A's <w:tbl> nested in a cell ↔ B's <w:sdt>),
    // grouping by Unid alone merges them and spills a stray child (e.g. a <w:tc>
    // directly under <w:sdtContent>). Keying on element-name too keeps the divergent
    // structures separate. (sd-2672-nested-table_sd-2672-sdt-table.)
    let dref: &Dom = dom;
    // Tuple key, not format!("{u}|{nm}") — the concat + re-split was a
    // measurable slice of produce-phase hashing/allocation.
    let grouped = group_by_key_stable(atoms, |ca| {
        if level >= ca.ancestor_elements.len() {
            return (String::new(), String::new());
        }
        let u = ca
            .ancestor_unids
            .as_ref()
            .and_then(|u| u.get(level).cloned())
            .unwrap_or_default();
        if u.is_empty() {
            return (String::new(), String::new());
        }
        let nm = dref
            .name(ca.ancestor_elements[level])
            .map(|n| n.local_name().to_string())
            .unwrap_or_default();
        (u, nm)
    });
    let grouped: Vec<_> = grouped
        .into_iter()
        .filter(|(k, _)| !k.0.is_empty())
        .collect();
    if grouped.is_empty() {
        return Vec::new();
    }

    let mut out = Vec::new();
    for (gkey, g) in grouped {
        let ancestor = g[0].ancestor_elements[level];
        let aname = dom.name(ancestor).unwrap();

        // Step 3 — group children by (next-level unid | status), txbx → Equal.
        let groupedchildren = group_adjacent(g.iter().cloned(), |gc| {
            let key = if level < gc.ancestor_elements.len() - 1 {
                gc.ancestor_unids
                    .as_ref()
                    .and_then(|u| u.get(level + 1).cloned())
                    .unwrap_or_default()
            } else {
                String::new()
            };
            let st = if is_txbx_from_level(dom, gc, level) {
                "Equal"
            } else {
                status_str(gc.correlation_status)
            };
            (key, st)
        });

        // w:p
        if aname == W::p() {
            let p = dom.new_element(W::p());
            for (an, av) in dom.attributes(ancestor) {
                if an.namespace_name() != PT::URI {
                    dom.set_attribute_value(p, &an, Some(&av));
                }
            }
            // Tuple key: .0 is the Unid (scratch).
            dom.set_attribute_value(p, &PT::unid(), Some(&gkey.0));
            for (key, gc) in &groupedchildren {
                if key.0.is_empty() {
                    for gcc in gc {
                        let dup = dom.clone_subtree(gcc.content_element);
                        tag_status(dom, dup, gcc.correlation_status, gcc);
                        dom.add(p, dup);
                    }
                } else {
                    for child in coalesce_recurse(dom, gc, level + 1, settings, id_gen) {
                        dom.add(p, child);
                    }
                }
            }
            out.push(p);
            continue;
        }

        // w:r
        if aname == W::r() {
            let r = dom.new_element(W::r());
            for (an, av) in dom.attributes(ancestor) {
                // the pt:PreDelete / pt:PreIns stamp trios are the ONLY
                // scratch attr families produce must carry:
                // finalize::convert_stamped_predeletes / _preins turn the
                // stamped runs back into pending w:del / w:ins. Explicit
                // allowlist — no other pt:* attr may leak into the redline.
                if an.namespace_name() != PT::URI
                    || matches!(
                        an.local_name(),
                        "PreDelete"
                            | "PreDelAuthor"
                            | "PreDelDate"
                            | "PreIns"
                            | "PreInsAuthor"
                            | "PreInsDate"
                    )
                {
                    dom.set_attribute_value(r, &an, Some(&av));
                }
            }
            if let Some(rpr) = dom.element(ancestor, &W::r_pr()) {
                let rpr_clone = dom.clone_subtree(rpr);
                dom.add(r, rpr_clone);
            }
            for (key, gc) in &groupedchildren {
                if key.0.is_empty() {
                    for gcc in gc {
                        let dup = dom.clone_subtree(gcc.content_element);
                        tag_status(dom, dup, gcc.correlation_status, gcc);
                        dom.add(r, dup);
                    }
                } else {
                    for child in coalesce_recurse(dom, gc, level + 1, settings, id_gen) {
                        dom.add(r, child);
                    }
                }
            }
            out.push(r);
            continue;
        }

        // w:t — emit text elements (w:t / w:delText) with status; no wrapper.
        // Pure del → delText. MovedSource → w:t (Word Compare; see delete_text_in_opaque).
        if aname == W::t() {
            for (_key, gc) in &groupedchildren {
                let text: String = gc
                    .iter()
                    .map(|a| dom.value_str(a.content_element).into_owned())
                    .collect();
                let first = &gc[0];
                let elem_name = match first.correlation_status {
                    CorrelationStatus::Deleted => W::del_text(),
                    _ => W::t(),
                };
                let te = dom.new_element(elem_name);
                tag_status(dom, te, first.correlation_status, first);
                if let Some(sp) = xml_space_attr(&text) {
                    dom.set_attribute_value(te, &XNamespace::xml().name("space"), Some(sp));
                }
                dom.add_text(te, &text);
                out.push(te);
            }
            continue;
        }

        // w:drawing — clone + status (part relocation deferred to M4.H).
        if aname == W::drawing() {
            for (_key, gc) in &groupedchildren {
                for gcc in gc {
                    let d = dom.clone_subtree(gcc.content_element);
                    tag_status(dom, d, gcc.correlation_status, gcc);
                    delete_text_in_opaque(dom, d, gcc.correlation_status);
                    out.push(d);
                }
            }
            continue;
        }

        // w:pict (VML image) — clone full subtree + status. Must not fall
        // through to reconstruct_element / empty Allowable shell: attribute-
        // only v:imagedata children emit no atoms when recursed (M74).
        if aname == W::pict() {
            for (_key, gc) in &groupedchildren {
                for gcc in gc {
                    let d = dom.clone_subtree(gcc.content_element);
                    tag_status(dom, d, gcc.correlation_status, gcc);
                    delete_text_in_opaque(dom, d, gcc.correlation_status);
                    out.push(d);
                }
            }
            continue;
        }

        // mc:AlternateContent — verbatim clone + status.
        if aname == crate::namespaces::MC::name("AlternateContent") {
            for (_key, gc) in &groupedchildren {
                for gcc in gc {
                    let d = dom.clone_subtree(gcc.content_element);
                    tag_status(dom, d, gcc.correlation_status, gcc);
                    delete_text_in_opaque(dom, d, gcc.correlation_status);
                    out.push(d);
                }
            }
            continue;
        }

        // m:oMath / m:oMathPara — wrap in real w:del/w:ins/w:moveFrom/w:moveTo.
        // The outer wrap is the shape every mesh/finalize pass reasons about;
        // the final Word serialization (revision marks INSIDE the math, M463)
        // is produced by `convert_outer_math_wraps_to_internal` at the very
        // end of the pipeline.
        if aname == crate::namespaces::M::name("oMath")
            || aname == crate::namespaces::M::name("oMathPara")
        {
            for (_key, gc) in &groupedchildren {
                for gcc in gc {
                    let rev = match gcc.correlation_status {
                        CorrelationStatus::Deleted => Some(W::del()),
                        CorrelationStatus::MovedSource => Some(W::move_from()),
                        CorrelationStatus::Inserted => Some(W::ins()),
                        CorrelationStatus::MovedDestination => Some(W::move_to()),
                        _ => None,
                    };
                    let content = dom.clone_subtree(gcc.content_element);
                    match rev {
                        Some(rname) => {
                            let w = dom.new_element(rname);
                            dom.set_attribute_value(
                                w,
                                &W::author(),
                                Some(&settings.author_for_revisions),
                            );
                            dom.set_attribute_value(w, &W::id(), Some(&id_gen.to_string()));
                            *id_gen += 1;
                            dom.set_attribute_value(
                                w,
                                &W::date(),
                                Some(&settings.date_time_for_revisions),
                            );
                            dom.add(w, content);
                            out.push(w);
                        }
                        None => out.push(content),
                    }
                }
            }
            continue;
        }

        // AllowableRunChildren — fresh element (attrs minus pt:) + status.
        if super::tables::ALLOWABLE_RUN_CHILDREN.contains(&aname) {
            for (_key, gc) in &groupedchildren {
                let first = &gc[0];
                match first.correlation_status {
                    CorrelationStatus::Deleted
                    | CorrelationStatus::Inserted
                    | CorrelationStatus::MovedSource
                    | CorrelationStatus::MovedDestination => {
                        for gcc in gc {
                            let dup = dom.new_element(aname.clone());
                            for (an, av) in dom.attributes(ancestor) {
                                if an.namespace_name() != PT::URI {
                                    dom.set_attribute_value(dup, &an, Some(&av));
                                }
                            }
                            tag_status(dom, dup, gcc.correlation_status, gcc);
                            out.push(dup);
                        }
                    }
                    _ => {
                        for gcc in gc {
                            out.push(dom.clone_subtree(gcc.content_element));
                        }
                    }
                }
            }
            continue;
        }

        // Container elements → ReconstructElement (props hoisted first).
        let props: &[&str] = if aname == W::tbl() {
            &["tblPr", "tblGrid"]
        } else if aname == W::tr() {
            &["trPr"]
        } else if aname == W::tc() {
            &["tcPr"]
        } else if aname == W::sdt() {
            &["sdtPr", "sdtEndPr"]
        } else if aname == W::name("ruby") {
            &["rubyPr"]
        } else {
            &[]
        };
        let pict_props = aname == W::pict();
        let recon = reconstruct_element(
            dom, &g, ancestor, props, pict_props, level, settings, id_gen,
        );
        out.push(recon);
    }
    out
}

/// M4.E.6 — `ReconstructElement` (:6984): rebuild a container element, hoisting
/// the named property children first, then the recursively-coalesced children.
#[allow(clippy::too_many_arguments)]
fn reconstruct_element(
    dom: &mut Dom,
    g: &[&ComparisonUnitAtom],
    ancestor: NodeId,
    props: &[&str],
    pict_props: bool,
    level: usize,
    settings: &WmlComparerSettings,
    id_gen: &mut u32,
) -> NodeId {
    let aname = dom.name(ancestor).unwrap();
    let new_children = coalesce_recurse(dom, g, level + 1, settings, id_gen);
    let ne = dom.new_element(aname.clone());
    for (an, av) in dom.attributes(ancestor) {
        dom.set_attribute_value(ne, &an, Some(&av));
    }
    // hoist property children (in declared order)
    if pict_props {
        for p in dom.elements(ancestor, Some(&crate::namespaces::VML::name("shapetype"))) {
            let c = dom.clone_subtree(p);
            dom.add(ne, c);
        }
    }
    for pname in props {
        for p in dom.elements(ancestor, Some(&W::name(pname))) {
            let c = dom.clone_subtree(p);
            dom.add(ne, c);
        }
    }
    // Word-alignment (M-TBL, parity/_scratch/table_class_forensics.md): a
    // MERGED table takes the NEW table's effective tblPr/tblGrid (hoisted
    // above from `ancestor`, the modified side), and Word records the OLD
    // table's properties in w:tblPrChange (last child of tblPr) and
    // w:tblGridChange (last child of tblGrid) — GT table-bookmark-end_
    // table-vmerge-colspan: effective tblW 6000/grid 3502·3509·3285, old
    // tblW 9360/union grid preserved in the change records. Ours dropped
    // the history entirely, so the old width kept rendering (2 vs 3 pages).
    if settings.merge_replaced_paragraphs && aname == W::tbl() {
        // Bind the table element name once; the find_map below runs per atom.
        let is_tbl = |anc: NodeId| dom.name(anc).is_some_and(|nm| *nm.local_name() == *"tbl");
        // the OLD table node: Deleted atoms carry doc A's ancestors directly;
        // Equal atoms carry them on `comparison_unit_atom_before`.
        let old_tbl = g.iter().find_map(|a| {
            let direct = a
                .ancestor_elements
                .get(level)
                .copied()
                .filter(|&anc| anc != ancestor && is_tbl(anc));
            direct.or_else(|| {
                let before = a.comparison_unit_atom_before.as_ref()?;
                before
                    .ancestor_elements
                    .get(level)
                    .copied()
                    .filter(|&anc| anc != ancestor && is_tbl(anc))
            })
        });
        // M-TBL rule 2b — orientation: `ancestor` (the hoist source) may
        // resolve to the OLD (doc A) table when the merged group leads with
        // A-side atoms. Word keeps the NEW table's props effective in either
        // orientation (GT table-bookmark-end_table-vmerge-colspan: effective
        // 0/auto from B, A's 6000 in tblPrChange; ours kept A's 6000 with the
        // NEW props in the change record). Detect: a Deleted atom (or a
        // `comparison_unit_atom_before`) owns `ancestor` → the "other" table
        // found above is really the NEW one; re-hoist from it and record
        // `ancestor` as the old side.
        let ancestor_is_old = g.iter().any(|a| {
            (a.correlation_status == CorrelationStatus::Deleted
                && a.ancestor_elements.get(level) == Some(&ancestor))
                || a.comparison_unit_atom_before
                    .as_ref()
                    .is_some_and(|b| b.ancestor_elements.get(level) == Some(&ancestor))
        });
        let old_tbl = match (old_tbl, ancestor_is_old) {
            (Some(new_tbl), true) => {
                for pname in ["tblPr", "tblGrid"] {
                    for hoisted in dom.elements(ne, Some(&W::name(pname))) {
                        dom.remove(hoisted);
                    }
                    for p in dom.elements(new_tbl, Some(&W::name(pname))) {
                        let c = dom.clone_subtree(p);
                        dom.add(ne, c);
                    }
                }
                Some(ancestor)
            }
            (found, _) => found,
        };
        if let Some(old_tbl) = old_tbl {
            let strip_change = |dom: &mut Dom, el: NodeId, change: &str| {
                for c in dom.elements(el, Some(&W::name(change))) {
                    dom.remove(c);
                }
            };
            // tblPr → tblPrChange
            if let (Some(new_pr), Some(old_pr)) = (
                dom.element(ne, &W::tbl_pr()),
                dom.element(old_tbl, &W::tbl_pr()),
            ) {
                let old_clone = dom.clone_subtree(old_pr);
                strip_change(dom, old_clone, "tblPrChange");
                if dom.serialize_element(old_clone) != dom.serialize_element(new_pr) {
                    let change = dom.new_element(W::name("tblPrChange"));
                    dom.set_attribute_value(change, &W::id(), Some(&id_gen.to_string()));
                    *id_gen += 1;
                    dom.set_attribute_value(
                        change,
                        &W::author(),
                        Some(&settings.author_for_revisions),
                    );
                    dom.set_attribute_value(
                        change,
                        &W::date(),
                        Some(&settings.date_time_for_revisions),
                    );
                    dom.add(change, old_clone);
                    dom.add(new_pr, change);
                } else {
                    dom.remove(old_clone);
                }
            }
            // tblGrid → tblGridChange
            if let (Some(new_grid), Some(old_grid)) = (
                dom.element(ne, &W::name("tblGrid")),
                dom.element(old_tbl, &W::name("tblGrid")),
            ) {
                let old_clone = dom.clone_subtree(old_grid);
                strip_change(dom, old_clone, "tblGridChange");
                if dom.serialize_element(old_clone) != dom.serialize_element(new_grid) {
                    let change = dom.new_element(W::name("tblGridChange"));
                    // w:id ONLY. CT_TblGridChange is the one revision-history
                    // element that does not extend CT_TrackChange, so it
                    // declares neither w:author nor w:date — unlike the
                    // tblPrChange directly above, which does. Copying that
                    // block wholesale made the validator report
                    // Sch_UndeclaredAttribute on both.
                    dom.set_attribute_value(change, &W::id(), Some(&id_gen.to_string()));
                    *id_gen += 1;
                    dom.add(change, old_clone);
                    dom.add(new_grid, change);
                } else {
                    dom.remove(old_clone);
                }
            }
        }
    }
    for c in new_children {
        dom.add(ne, c);
    }
    // Word-alignment (M-TBL rule 4, parity/_scratch/table_class_forensics.md):
    // a DEGENERATE grid — fewer w:gridCol entries than the real column count
    // implied by the rows' gridSpan/tc structure — is rebuilt Word's way:
    // per-column gridCols (equal split of the page content width) plus
    // `tblW 0 auto`. GT table-vmerge-colspan_text-box: 1×4985 → 4675+4675;
    // GT nested-table-rowspan_numbered-list: 1×9970 → 4887+4905.
    if settings.merge_replaced_paragraphs && aname == W::tbl() {
        rebuild_degenerate_grid(dom, ne, ancestor);
    }
    ne
}

/// CT_TblPrBase child order (wml.xsd). A synthesized child must be inserted
/// immediately after the last existing predecessor so `tblPr` stays
/// schema-valid — Word repairs an out-of-order `CT_TblPrBase`.
const TBLPR_CHILD_ORDER: &[&str] = &[
    "tblStyle",
    "tblpPr",
    "tblOverlap",
    "bidiVisual",
    "tblStyleRowBandSize",
    "tblStyleColBandSize",
    "tblW",
    "jc",
    "tblCellSpacing",
    "tblInd",
    "tblBorders",
    "shd",
    "tblLayout",
    "tblCellMar",
    "tblLook",
    "tblCaption",
    "tblDescription",
];

/// Insert `child` (a new tblPr child named `local`) under `tbl_pr` in
/// CT_TblPrBase order: after the last present predecessor, else first.
fn add_tblpr_child_in_order(dom: &mut Dom, tbl_pr: NodeId, child: NodeId, local: &str) {
    let new_rank = TBLPR_CHILD_ORDER
        .iter()
        .position(|&n| n == local)
        .unwrap_or(usize::MAX);
    let anchor = dom.elements(tbl_pr, None).into_iter().rev().find(|&e| {
        dom.name(e).is_some_and(|nm| {
            TBLPR_CHILD_ORDER
                .iter()
                .position(|&n| n == nm.local_name())
                .is_some_and(|rank| rank < new_rank)
        })
    });
    match anchor {
        Some(a) => dom.add_after_self(a, child),
        None => dom.add_first(tbl_pr, child),
    }
}

/// M-TBL rule 4 — see call site. `src_tbl` is the source-document table node
/// used to locate the section geometry (page width minus margins).
fn rebuild_degenerate_grid(dom: &mut Dom, tbl: NodeId, src_tbl: NodeId) {
    let Some(grid) = dom.element(tbl, &W::name("tblGrid")) else {
        return;
    };
    let grid_cols = dom.elements(grid, Some(&W::name("gridCol")));
    // real column count: max over rows of Σ gridSpan (default 1) per cell
    let real_cols = dom
        .elements(tbl, Some(&W::tr()))
        .into_iter()
        .map(|tr| {
            dom.elements(tr, Some(&W::tc()))
                .into_iter()
                .map(|tc| {
                    dom.element(tc, &W::tc_pr())
                        .and_then(|pr| dom.element(pr, &W::grid_span()))
                        .and_then(|gs| dom.attribute(gs, &W::val()))
                        .and_then(|v| v.parse::<usize>().ok())
                        .unwrap_or(1)
                })
                .sum::<usize>()
        })
        .max()
        .unwrap_or(0);
    if real_cols < 2 || grid_cols.len() >= real_cols {
        return;
    }
    // effective width = page content width from the source doc's sectPr,
    // falling back to the declared grid total
    let content_width = dom
        .ancestors(src_tbl, None)
        .last()
        .map(|&root| dom.descendants(root, Some(&W::sect_pr())))
        .and_then(|s| s.first().copied())
        .and_then(|sect| {
            let w: i64 = dom
                .element(sect, &W::name("pgSz"))
                .and_then(|e| dom.attribute(e, &W::name("w")))
                .and_then(|v| v.parse().ok())?;
            let mar = dom.element(sect, &W::name("pgMar"))?;
            let l: i64 = dom
                .attribute(mar, &W::name("left"))
                .and_then(|v| v.parse().ok())?;
            let r: i64 = dom
                .attribute(mar, &W::name("right"))
                .and_then(|v| v.parse().ok())?;
            Some(w - l - r)
        })
        .filter(|&w| w > 0)
        .unwrap_or_else(|| {
            grid_cols
                .iter()
                .filter_map(|&c| dom.attribute(c, &W::name("w")))
                .filter_map(|v| v.parse::<i64>().ok())
                .sum()
        });
    if content_width <= 0 {
        return;
    }
    for c in &grid_cols {
        dom.remove(*c);
    }
    let each = content_width / real_cols as i64;
    let mut new_cols = Vec::with_capacity(real_cols);
    for i in 0..real_cols {
        let w = if i + 1 == real_cols {
            content_width - each * (real_cols as i64 - 1)
        } else {
            each
        };
        let col = dom.new_element(W::name("gridCol"));
        dom.set_attribute_value(col, &W::name("w"), Some(&w.to_string()));
        new_cols.push(col);
    }
    // gridCols must precede any tblGridChange history in the grid
    for col in new_cols.into_iter().rev() {
        dom.add_first(grid, col);
    }
    // tblW → 0 auto (CT_TblPrBase schema order: tblW follows tblStyle,
    // tblpPr, tblOverlap, bidiVisual, tblStyleRowBandSize,
    // tblStyleColBandSize). Insert after the last present predecessor so a
    // floating (tblpPr) or banded table stays schema-valid; mutate in place
    // when tblW already exists.
    if let Some(tbl_pr) = dom.element(tbl, &W::tbl_pr()) {
        let tblw = match dom.element(tbl_pr, &W::name("tblW")) {
            Some(e) => e,
            None => {
                let e = dom.new_element(W::name("tblW"));
                add_tblpr_child_in_order(dom, tbl_pr, e, "tblW");
                e
            }
        };
        dom.set_attribute_value(tblw, &W::name("w"), Some("0"));
        dom.set_attribute_value(tblw, &W::name("type"), Some("auto"));
    }
}

/// M4.E.8 — `ProduceNewWmlMarkupFromCorrelatedSequence` (:5926): reset the id
/// counter and coalesce at level 0.
pub fn produce_new_wml_markup_from_correlated_sequence(
    dom: &mut Dom,
    atoms: &[ComparisonUnitAtom],
    settings: &WmlComparerSettings,
    id_gen: &mut u32,
) -> Vec<NodeId> {
    // Borrow each atom once; coalesce_recurse threads &-slices (no atom clones).
    let refs: Vec<&ComparisonUnitAtom> = atoms.iter().collect();
    coalesce_recurse(dom, &refs, 0, settings, id_gen)
}

#[cfg(test)]
mod opaque_text_tests {
    //! Direct coverage for `delete_text_in_opaque` (private). Pins the
    //! status→text-kind contract — in particular that `MovedSource` renames `w:t`
    //! to `w:delText` (ISO/IEC 29500-1 §17.3.3.7: `delText` replaces `t` within a
    //! `del` *or `moveFrom`*), which is otherwise unexercised because move
    //! detection is off by default.
    use super::*;

    /// `<w:drawing><w:r><w:t>txt</w:t></w:r></w:drawing>` — an opaque subtree.
    fn opaque_with_text(d: &mut Dom, txt: &str) -> NodeId {
        let drawing = d.new_element(W::drawing());
        let r = d.new_element(W::r());
        let t = d.new_element(W::t());
        d.add_text(t, txt);
        d.add(r, t);
        d.add(drawing, r);
        drawing
    }

    /// Local name of the first `w:t`/`w:delText` leaf under `node`.
    fn text_kind(d: &Dom, node: NodeId) -> String {
        let leaf = d
            .descendants(node, None)
            .into_iter()
            .find(|&c| {
                matches!(
                    d.name(c).as_ref().map(|n| n.local_name()),
                    Some("t") | Some("delText")
                )
            })
            .expect("a text leaf");
        d.name(leaf).unwrap().local_name().to_string()
    }

    #[test]
    fn deleted_opaque_text_becomes_deltext() {
        let mut d = Dom::new();
        let n = opaque_with_text(&mut d, "x");
        delete_text_in_opaque(&mut d, n, CorrelationStatus::Deleted);
        assert_eq!(text_kind(&d, n), "delText");
    }

    #[test]
    fn moved_source_opaque_text_stays_t_like_word() {
        let mut d = Dom::new();
        let n = opaque_with_text(&mut d, "x");
        delete_text_in_opaque(&mut d, n, CorrelationStatus::MovedSource);
        assert_eq!(
            text_kind(&d, n),
            "t",
            "Word Compare keeps w:t inside moveFrom (not delText)"
        );
    }

    #[test]
    fn non_deleted_opaque_text_stays_t() {
        for status in [
            CorrelationStatus::Inserted,
            CorrelationStatus::MovedDestination,
            CorrelationStatus::Equal,
        ] {
            let mut d = Dom::new();
            let n = opaque_with_text(&mut d, "x");
            delete_text_in_opaque(&mut d, n, status);
            assert_eq!(
                text_kind(&d, n),
                "t",
                "non-deleted opaque text stays w:t for {status:?}"
            );
        }
    }

    #[test]
    fn instr_text_is_untouched() {
        // `w:instrText` is not `w:t`, so the `W::t()` filter must leave it alone
        // even under a deletion (renaming it would corrupt the field code).
        let mut d = Dom::new();
        let drawing = d.new_element(W::drawing());
        let r = d.new_element(W::r());
        let instr = d.new_element(W::instr_text());
        d.add_text(instr, "FIELD");
        d.add(r, instr);
        d.add(drawing, r);
        delete_text_in_opaque(&mut d, drawing, CorrelationStatus::Deleted);
        assert_eq!(
            d.descendants(drawing, Some(&W::instr_text())).len(),
            1,
            "instrText untouched"
        );
        assert!(
            d.descendants(drawing, Some(&W::del_text())).is_empty(),
            "no delText fabricated from instrText"
        );
    }
}

#[cfg(test)]
mod tblpr_order_tests {
    //! Word-validity regression: a synthesized `w:tblW` must land in its
    //! `CT_TblPrBase` schema slot (after tblpPr/bidiVisual/...), not pinned
    //! after tblStyle — Word repairs an out-of-order `tblPr` child sequence.
    use super::*;

    #[test]
    fn tblw_inserted_after_tblppr_and_bidivisual() {
        let mut dom = Dom::new();
        let xml = concat!(
            "<w:tblPr xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">",
            "<w:tblStyle w:val=\"TableGrid\"/>",
            "<w:tblpPr w:leftFromText=\"0\"/>",
            "<w:bidiVisual/>",
            "</w:tblPr>"
        );
        let doc = dom.parse_xdocument(xml);
        let tblpr = dom.root(doc).expect("root");
        let tblw = dom.new_element(W::name("tblW"));
        add_tblpr_child_in_order(&mut dom, tblpr, tblw, "tblW");
        let order: Vec<String> = dom
            .elements(tblpr, None)
            .into_iter()
            .map(|e| dom.name(e).unwrap().local_name().to_string())
            .collect();
        let pos = |n: &str| order.iter().position(|x| x == n).unwrap();
        assert!(
            pos("tblW") > pos("tblpPr") && pos("tblW") > pos("bidiVisual"),
            "tblW must follow tblpPr and bidiVisual (CT_TblPrBase), got: {order:?}"
        );
    }
}