rhwp 0.9.1

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
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
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
//! HWPX 라운드트립 IR diff — `parse → serialize → parse` 한 IR을 원본과 비교.
//!
//! ## 원칙
//!
//! - **바이트 비교 금지**: XML 속성 순서·ZIP 압축율 유동성 때문에 브리틀함
//! - **IR 의미 비교**: Document 공개 필드 단위로 비교
//! - **누적 확장**: Stage 0에선 뼈대 필드(섹션 수·문단 수·리소스 카운트)만 비교하고,
//!   Stage 1~5 진행 시 비교 대상 필드를 누적 확장한다
//!
//! Stage 0 최소 세트:
//! - sections.len()
//! - 각 section의 paragraphs.len()
//! - doc_info의 리소스 카운트 (char_shapes, para_shapes, border_fills 등)
//! - bin_data_content.len()
//!
//! Task #1378 확장:
//! - 본문(top-level) 문단별 `char_shapes` 시퀀스 — `(start_pos, char_shape_id)` 전체 비교.
//!   serializer 의 run 평탄화(첫 run 서식으로 통일)를 검출한다.
//!   셀·글상자(Group 재귀)·각주/미주 내부 문단 재귀 비교 포함 (3단계).
//!
//! Task #1379 확장:
//! - 문단별 인라인 슬롯 컨트롤 타입 시퀀스 비교 (`is_hwpx_inline_slot` 기준, 본문 +
//!   #1378 재귀 동승). 셀·글상자 subList 의 컨트롤 소실(그림 등)을 검출한다.
//!   Bookmark 등 위치 없는 비슬롯 컨트롤은 비교 대상에서 제외.
//!
//! Task #1380 확장:
//! - 문단별 `line_segs` 9필드 비교 (`diff_linesegs`) 를 `ParagraphLinesegs` 로 변환해
//!   게이트 동승 (3단계). 파서 zero-default 주입 제거 + serializer 방출 생략(2단계)
//!   이후의 원본 무 ↔ RT 유 합성 비대칭(개수·값 불일치)을 검출한다.
//!
//! Task #1388 확장:
//! - 섹션별 `PageDef`(용지 크기·방향·제본 + 여백 7필드) 비교 (`diff_page_def`) 를
//!   `SectionPageDef` 로 게이트 동승. serializer 의 secPr 템플릿 고정값 방출
//!   (여백·gutterType 변형)을 검출한다.
//!
//! Task #1387 확장:
//! - 표 캡션 비교 (`diff_table_caption`) 를 `TableCaption` 으로 게이트 동승 —
//!   존재 비대칭/속성 5종/문단 수. 캡션 내부 문단은 char_shapes·controls·linesegs
//!   재귀에 `tbl.caption.p[k]` 경로로 동승한다.
//!
//! #1403 확장:
//! - 그림/도형/묶음 캡션을 `ObjectCaption` 으로 게이트 동승 — Picture 컨트롤은
//!   `pic.caption`, ShapeObject 는 `shape_caption` 접근자(그리기 도형 `drawing.caption`
//!   + Group/Chart/Ole/Picture 전용 필드) 경유. 비교·재귀는 #1387 경로 공유.

#![allow(dead_code)]

use super::section::is_hwpx_inline_slot;
use crate::model::document::Document;
use crate::parser::hwpx::parse_hwpx;
use crate::serializer::hwpx::serialize_hwpx;
use crate::serializer::SerializeError;

mod export_cache;
pub(crate) use export_cache::project_paragraphs as project_exported_line_caches;
pub use export_cache::{diff_exported_hwp_documents, diff_exported_hwpx_documents};

/// IR diff 결과 — 발견된 차이 목록을 보관.
#[derive(Debug, Default)]
pub struct IrDiff {
    pub differences: Vec<IrDifference>,
}

impl IrDiff {
    pub fn is_empty(&self) -> bool {
        self.differences.is_empty()
    }

    pub fn push(&mut self, d: IrDifference) {
        self.differences.push(d);
    }

    /// 관용 규칙 하에서 통과로 볼 수 있는가 (Stage 5에서 확장 예정).
    pub fn allowed(&self, _allow: IrDiffAllow) -> bool {
        self.is_empty()
    }
}

/// Stage 5에서 도형 raw 바이트 불일치 등을 허용하기 위한 옵션 (현재 미사용).
#[derive(Debug, Default, Clone, Copy)]
pub struct IrDiffAllow {
    pub shape_raw: bool,
}

/// 발견된 단일 차이.
#[derive(Debug, Clone)]
pub enum IrDifference {
    SectionCount {
        expected: usize,
        actual: usize,
    },
    ParagraphCount {
        section: usize,
        expected: usize,
        actual: usize,
    },
    CharShapeCount {
        expected: usize,
        actual: usize,
    },
    ParaShapeCount {
        expected: usize,
        actual: usize,
    },
    BorderFillCount {
        expected: usize,
        actual: usize,
    },
    TabDefCount {
        expected: usize,
        actual: usize,
    },
    NumberingCount {
        expected: usize,
        actual: usize,
    },
    StyleCount {
        expected: usize,
        actual: usize,
    },
    BinDataContentCount {
        expected: usize,
        actual: usize,
    },
    /// 문단의 char_shapes 시퀀스 불일치 — run 분할 보존 게이트 (#1378).
    ///
    /// `path` 는 중첩 위치 표기 — 본문 문단은 빈 문자열, 셀·글상자·각주/미주 내부
    /// 문단은 `/ctrl[i]tbl.cell[j].p[k]` 식의 경로.
    ParagraphCharShapes {
        section: usize,
        paragraph: usize,
        path: String,
        expected: String,
        actual: String,
    },
    /// 문단의 인라인 슬롯 컨트롤 타입 시퀀스 불일치 — 컨트롤 보존 게이트 (#1379).
    ///
    /// `path` 표기는 `ParagraphCharShapes` 와 동일.
    ParagraphControls {
        section: usize,
        paragraph: usize,
        path: String,
        expected: String,
        actual: String,
    },
    /// 문단의 `line_segs` 불일치 — lineseg 원본 보존 게이트 (#1380).
    ///
    /// `path` 표기는 `ParagraphCharShapes` 와 동일. `detail` 은 `LinesegDiffKind` 의
    /// 표시 문자열 (개수 불일치 또는 인덱스·필드 단위 값 불일치).
    ParagraphLinesegs {
        section: usize,
        paragraph: usize,
        path: String,
        detail: String,
    },
    /// 섹션 `PageDef`(용지·여백) 불일치 — secPr 페이지 여백 보존 게이트 (#1388).
    ///
    /// `detail` 은 불일치 필드별 "field: expected=.. actual=.." 을 세미콜론으로
    /// 연결한 문자열 (`diff_page_def`).
    SectionPageDef {
        section: usize,
        detail: String,
    },
    /// 섹션 `<hp:visibility>`(첫쪽 머리말/꼬리말/바탕쪽 숨김·테두리·배경·첫 빈줄 숨김)
    /// 불일치 — secPr visibility 보존 게이트 (#1637).
    ///
    /// 직렬화기가 visibility 를 IR 대신 템플릿 고정값으로 방출하면 hideFirstEmptyLine 등이
    /// 드롭되어 페이지네이션이 달라진다(IR-invisible 결함). `detail` 형식은 `diff_page_def` 동형.
    SectionVisibility {
        section: usize,
        detail: String,
    },
    /// 표 캡션 불일치 — 캡션 보존 게이트 (#1387).
    ///
    /// `path` 는 `…tbl.caption` 까지의 중첩 경로. `detail` 은 존재 비대칭 또는
    /// 불일치 필드별 "field: expected=.. actual=.." 세미콜론 연결 (`diff_table_caption`).
    TableCaption {
        section: usize,
        paragraph: usize,
        path: String,
        detail: String,
    },
    /// 그림/도형/묶음 캡션 불일치 — 캡션 보존 게이트 (#1403).
    ///
    /// `path` 는 `…pic.caption` / `…shape.caption` 등 중첩 경로. `detail` 형식은
    /// `TableCaption` 과 동일 (`diff_table_caption` 공유).
    ObjectCaption {
        section: usize,
        paragraph: usize,
        path: String,
        detail: String,
    },
    /// 그림/도형/수식/묶음 설명(`hp:shapeComment`) 불일치 — 설명 보존 게이트 (#1392).
    ///
    /// `path` 는 `…pic` / `…shape` / `…eq` 등 중첩 경로. `detail` 은
    /// `"expected={:?} actual={:?}"`.
    ObjectComment {
        section: usize,
        paragraph: usize,
        path: String,
        detail: String,
    },
    /// 필드 parameters / MEMO 본문 불일치 — 필드 보존 게이트 (#1391).
    ///
    /// `path` 는 `…field` (parameters) 또는 `…field.memo.p[k]` (본문 재귀).
    FieldContent {
        section: usize,
        paragraph: usize,
        path: String,
        detail: String,
    },
    /// 그림 크기 요소(curSz/imgRect/imgDim) 불일치 — 그림 크기 보존 게이트 (#1389).
    ///
    /// `path` 는 `…pic`. `detail` 은 불일치 필드별 "field: expected=.. actual=.."
    /// 세미콜론 연결.
    PictureSize {
        section: usize,
        paragraph: usize,
        path: String,
        detail: String,
    },
    /// 표 `page_break` 불일치 — 표 분할 속성 보존 게이트 (#1393).
    ///
    /// 방출(serializer)은 PR #1405 에서 정정됨 — 본 게이트는 회귀 봉인용.
    /// `path` 는 `…tbl`.
    TablePageBreak {
        section: usize,
        paragraph: usize,
        path: String,
        detail: String,
    },
    /// 개체 `holdAnchorAndSO`(IR `prevent_page_break`) 불일치 — 페이지 하단 앵커
    /// 개체에서 1→0 드롭 시 한글 페이지 붕괴를 유발(#1594). IR-invisible 였던 갭을 봉인.
    ObjectHoldAnchor {
        section: usize,
        paragraph: usize,
        path: String,
        detail: String,
    },
    /// 개체 `flowWithText`(IR `flow_with_text`) 불일치 — 표(treatAsChar)에서 0→1 드롭 시
    /// partial-split 임계가 흔들려 페이지네이션이 달라진다(#1637). IR-invisible 였던 갭을 봉인.
    ObjectFlowWithText {
        section: usize,
        paragraph: usize,
        path: String,
        detail: String,
    },
}

impl std::fmt::Display for IrDifference {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use IrDifference::*;
        match self {
            SectionCount { expected, actual } => {
                write!(f, "section count: expected={} actual={}", expected, actual)
            }
            ParagraphCount {
                section,
                expected,
                actual,
            } => write!(
                f,
                "section[{}] paragraph count: expected={} actual={}",
                section, expected, actual
            ),
            CharShapeCount { expected, actual } => write!(
                f,
                "char_shapes count: expected={} actual={}",
                expected, actual
            ),
            ParaShapeCount { expected, actual } => write!(
                f,
                "para_shapes count: expected={} actual={}",
                expected, actual
            ),
            BorderFillCount { expected, actual } => write!(
                f,
                "border_fills count: expected={} actual={}",
                expected, actual
            ),
            TabDefCount { expected, actual } => {
                write!(f, "tab_defs count: expected={} actual={}", expected, actual)
            }
            NumberingCount { expected, actual } => write!(
                f,
                "numberings count: expected={} actual={}",
                expected, actual
            ),
            StyleCount { expected, actual } => {
                write!(f, "styles count: expected={} actual={}", expected, actual)
            }
            BinDataContentCount { expected, actual } => write!(
                f,
                "bin_data_content count: expected={} actual={}",
                expected, actual
            ),
            ParagraphCharShapes {
                section,
                paragraph,
                path,
                expected,
                actual,
            } => write!(
                f,
                "section[{}] paragraph[{}]{} char_shapes: expected={} actual={}",
                section, paragraph, path, expected, actual
            ),
            ParagraphControls {
                section,
                paragraph,
                path,
                expected,
                actual,
            } => write!(
                f,
                "section[{}] paragraph[{}]{} controls: expected={} actual={}",
                section, paragraph, path, expected, actual
            ),
            ParagraphLinesegs {
                section,
                paragraph,
                path,
                detail,
            } => write!(
                f,
                "section[{}] paragraph[{}]{} linesegs: {}",
                section, paragraph, path, detail
            ),
            SectionPageDef { section, detail } => {
                write!(f, "section[{}] page_def: {}", section, detail)
            }
            SectionVisibility { section, detail } => {
                write!(f, "section[{}] visibility: {}", section, detail)
            }
            TableCaption {
                section,
                paragraph,
                path,
                detail,
            } => write!(
                f,
                "section[{}] paragraph[{}]{} caption: {}",
                section, paragraph, path, detail
            ),
            ObjectCaption {
                section,
                paragraph,
                path,
                detail,
            } => write!(
                f,
                "section[{}] paragraph[{}]{} caption: {}",
                section, paragraph, path, detail
            ),
            ObjectComment {
                section,
                paragraph,
                path,
                detail,
            } => write!(
                f,
                "section[{}] paragraph[{}]{} comment: {}",
                section, paragraph, path, detail
            ),
            FieldContent {
                section,
                paragraph,
                path,
                detail,
            } => write!(
                f,
                "section[{}] paragraph[{}]{} field: {}",
                section, paragraph, path, detail
            ),
            PictureSize {
                section,
                paragraph,
                path,
                detail,
            } => write!(
                f,
                "section[{}] paragraph[{}]{} pic_size: {}",
                section, paragraph, path, detail
            ),
            TablePageBreak {
                section,
                paragraph,
                path,
                detail,
            } => write!(
                f,
                "section[{}] paragraph[{}]{} tbl page_break: {}",
                section, paragraph, path, detail
            ),
            ObjectHoldAnchor {
                section,
                paragraph,
                path,
                detail,
            } => write!(
                f,
                "section[{}] paragraph[{}]{} holdAnchorAndSO: {}",
                section, paragraph, path, detail
            ),
            ObjectFlowWithText {
                section,
                paragraph,
                path,
                detail,
            } => write!(
                f,
                "section[{}] paragraph[{}]{} flowWithText: {}",
                section, paragraph, path, detail
            ),
        }
    }
}

/// 그림 크기 요소 비교 (#1389) — curSz(shape_attr current)·imgRect(border_x/y)·
/// imgDim. 불일치 필드를 세미콜론으로 연결. 일치하면 None.
fn diff_picture_size(
    a: &crate::model::image::Picture,
    b: &crate::model::image::Picture,
) -> Option<String> {
    let mut parts: Vec<String> = Vec::new();
    if a.shape_attr.current_width != b.shape_attr.current_width
        || a.shape_attr.current_height != b.shape_attr.current_height
    {
        parts.push(format!(
            "curSz: expected={}x{} actual={}x{}",
            a.shape_attr.current_width,
            a.shape_attr.current_height,
            b.shape_attr.current_width,
            b.shape_attr.current_height
        ));
    }
    if a.border_x != b.border_x || a.border_y != b.border_y {
        parts.push(format!(
            "imgRect: expected={:?}/{:?} actual={:?}/{:?}",
            a.border_x, a.border_y, b.border_x, b.border_y
        ));
    }
    if a.img_dim != b.img_dim {
        parts.push(format!(
            "imgDim: expected={:?} actual={:?}",
            a.img_dim, b.img_dim
        ));
    }
    // [#4668] hp:offset — 종전 pic writer 가 pos 유래로 재작성해도 이 게이트가
    // offset 을 비교하지 않아 잡히지 않았다(음수 wraparound offset 그림 노출).
    if a.shape_attr.offset_x != b.shape_attr.offset_x
        || a.shape_attr.offset_y != b.shape_attr.offset_y
    {
        parts.push(format!(
            "offset: expected=({}, {}) actual=({}, {})",
            a.shape_attr.offset_x,
            a.shape_attr.offset_y,
            b.shape_attr.offset_x,
            b.shape_attr.offset_y
        ));
    }
    if parts.is_empty() {
        None
    } else {
        Some(parts.join("; "))
    }
}

/// 두 `CommonObjAttr.description` 비교 (#1392). 다르면 detail 문자열, 같으면 None.
fn diff_object_comment(a: &str, b: &str) -> Option<String> {
    if a == b {
        None
    } else {
        Some(format!("expected={:?} actual={:?}", a, b))
    }
}

/// 두 개체의 `prevent_page_break`(holdAnchorAndSO) 비교 (#1594). 다르면 detail, 같으면 None.
fn diff_hold_anchor(
    a: &crate::model::shape::CommonObjAttr,
    b: &crate::model::shape::CommonObjAttr,
) -> Option<String> {
    if a.prevent_page_break == b.prevent_page_break {
        None
    } else {
        Some(format!(
            "expected={} actual={}",
            a.prevent_page_break, b.prevent_page_break
        ))
    }
}

/// 두 개체의 `flow_with_text`(flowWithText) 비교 (#1637). 다르면 detail, 같으면 None.
fn diff_flow_with_text(
    a: &crate::model::shape::CommonObjAttr,
    b: &crate::model::shape::CommonObjAttr,
) -> Option<String> {
    if a.flow_with_text == b.flow_with_text {
        None
    } else {
        Some(format!(
            "expected={} actual={}",
            a.flow_with_text, b.flow_with_text
        ))
    }
}

/// HWPX 바이트 → parse → serialize → parse → 원본 IR과 비교.
pub fn roundtrip_ir_diff(hwpx_bytes: &[u8]) -> Result<IrDiff, SerializeError> {
    let doc1 = parse_hwpx(hwpx_bytes)
        .map_err(|e| SerializeError::XmlError(format!("원본 HWPX 파싱 실패: {}", e)))?;
    let out = serialize_hwpx(&doc1)?;
    let doc2 = parse_hwpx(&out)
        .map_err(|e| SerializeError::XmlError(format!("재직렬화 HWPX 파싱 실패: {}", e)))?;
    Ok(diff_documents(&doc1, &doc2))
}

/// Stage 0 최소 필드 비교.
///
/// Stage 1~5에서 비교 대상 필드를 누적 확장한다 (문단 텍스트, 표·그림 속성 등).
/// `hwpx-roundtrip` 배치 진단(Task #1315)에서도 사용한다.
/// [#3505] 포맷을 넘는 변환에서 **비교할 수 없는 항목**을 걷어낸다.
///
/// `diff_documents` 는 HWPX 왕복(같은 포맷) 보존 가드로 만들어졌다. `convert` 처럼 포맷을
/// 넘는 변환에 그대로 쓰면 **대상 포맷에 자리가 없는 필드**가 차이로 잡혀, 진짜 손실이
/// 그 잡음에 묻힌다. 샘플 346건 실측에서 차이 224건 중 180건이 이 부류였다.
///
/// 걷어내는 것은 둘뿐이고, 각각 "내용이 보존됨"을 실측으로 확인한 것만 넣었다.
///
/// 1. **HWPX `<hp:parameters>` 원문**(`raw_parameters_xml`) — HWPX 전용 verbatim 필드(#1391)로
///    HWP5 에는 대응 표현이 없다. 하이퍼링크·Clickhere 의 실제 payload 는 `command` 와
///    필드 이름으로 보존된다(issue1893 fixture 11개 전수 확인: `command` 달라진 필드 0건).
/// 2. **원본이 값을 안 가진 `imgDim`** — 원본 `(0, 0)` 에 왕복본이 실제 치수를 채우는
///    방향이다. 잃은 것이 아니라 채운 것이라 손실이 아니다.
///
/// 같은 포맷 왕복(HWPX→HWPX, HWP5→HWP5)에는 **쓰지 않는다** — 그쪽에서는 두 필드 모두
/// 보존돼야 할 진짜 계약이다.
pub fn strip_cross_format_noise(diff: IrDiff) -> IrDiff {
    IrDiff {
        differences: diff
            .differences
            .into_iter()
            .filter(|d| !is_cross_format_incomparable(d))
            .collect(),
    }
}

/// HWP/HWP3를 HWPX로 저장할 때만 생기는 비교 불능 항목을 걷어낸다.
///
/// HWP 계열 필드에는 HWPX `<hp:parameters>` 원문을 실을 슬롯이 없다. 따라서
/// `Field.command`만 있던 HWP 필드를 HWPX로 내보내면 스키마가 요구하는 최소
/// `Command` 단일 parameters가 합성된다. 이는 command를 보존한 표현 변환이지 새 필드
/// 메타데이터가 아니므로, `export-hwpx --verify`에서는 해당 한 방향 차이만 제외한다
/// (#3739). 원문 parameters나 Command 외 항목의 차이는 계속 검출한다.
pub fn strip_hwp_to_hwpx_noise(diff: IrDiff) -> IrDiff {
    IrDiff {
        differences: diff
            .differences
            .into_iter()
            .filter(|d| !is_hwp_to_hwpx_incomparable(d))
            .collect(),
    }
}

/// HWP3를 HWPX로 저장할 때만 생기는 추가 표현 차이를 걷어낸다.
///
/// HWP3의 하이퍼텍스트 개체와 그림 crop 사각형은 HWPX와 같은 IR 자리가 없다.
/// 전자는 HWPX `HYPERLINK` field로, 후자는 HWPX가 요구하는 실제 이미지 사각형으로
/// 물질화한다. 두 경우 모두 원래 내용이나 배치 크기를 바꾸지는 않지만, HWP3 전용
/// `Control::Hyperlink`/영(0) 센티널과는 동일 비교할 수 없다. 이 함수는 그 두 방향의
/// 정확한 형태만 제외하며 HWP5에는 적용하지 않는다.
pub fn strip_hwp3_to_hwpx_noise(
    expected_document: &Document,
    actual_document: &Document,
    diff: IrDiff,
) -> IrDiff {
    let mut diff = strip_hwp_to_hwpx_noise(diff);
    diff.differences.retain(|difference| {
        !is_hwp3_to_hwpx_incomparable(expected_document, actual_document, difference)
    });
    diff
}

/// HWPX를 HWP5로 저장한 뒤에만 적용하는 추가 비교 불능 항목을 걷어낸다.
///
/// 한컴 2020은 HWPX 그림을 HWP5 `SC_PICTURE`로 저장할 때 extra의 original width/height
/// 두 칸을 의도적으로 `0`으로 둔다. 이 값은 `curSz`나 `imgRect`처럼 실제 배치·자르기
/// 기하를 뜻하지 않으며, HWPX `hp:imgDim`의 원본 이미지 메타와도 동등 비교할 수 없다.
/// 실제 물리 크기·자르기 차이가 함께 있으면 `detail`에 세미콜론으로 남으므로 절대 걷지
/// 않는다. HWP3/HML 등 다른 출처에는 적용하지 않는다.
pub fn strip_hwpx_to_hwp_noise(diff: IrDiff) -> IrDiff {
    let mut diff = strip_cross_format_noise(diff);
    diff.differences
        .retain(|difference| !is_hwpx_to_hwp_incomparable(difference));
    diff
}

fn is_cross_format_incomparable(d: &IrDifference) -> bool {
    match d {
        // HWPX verbatim parameters 소실 — 대상 포맷에 자리가 없다.
        IrDifference::FieldContent { detail, .. } => {
            detail.contains("parameters:") && detail.contains("actual=None")
        }
        // 원본이 값을 안 가진 imgDim 만 — 다른 크기 필드가 섞여 있으면 남긴다.
        IrDifference::PictureSize { detail, .. } => {
            detail.starts_with("imgDim: expected=(0, 0)") && !detail.contains(';')
        }
        _ => false,
    }
}

fn is_hwp_to_hwpx_incomparable(d: &IrDifference) -> bool {
    match d {
        // generated_field_parameters()가 raw_parameters_xml 없는 HWP 필드에만 만드는
        // 정확한 최소 표현. cnt·이름·요소 종류·닫는 태그까지 모두 고정해 다른 parameters
        // 손실이나 추가를 숨기지 않는다.
        IrDifference::FieldContent { detail, .. } => {
            const PREFIX: &str = r#"parameters: expected=None actual=Some("<hp:parameters cnt=\"1\" name=\"\"><hp:stringParam name=\"Command\">"#;
            const SUFFIX: &str = r#"</hp:stringParam></hp:parameters>")"#;
            if detail.starts_with(PREFIX) && detail.ends_with(SUFFIX) {
                return true;
            }
            // [#5866] 메모 승격의 의도된 정규화 두 건 — HWP5 원본은 command 만 갖고,
            // 산출 HWPX 재파싱은 memo_field_children_xml 이 만든 파라미터 6종
            // (Command 원문 포함)과 빈 subList 문단 1개를 갖는다. cnt·Command
            // prefix 까지 고정해 다른 parameters 변화를 숨기지 않는다.
            const MEMO_PREFIX: &str = r#"parameters: expected=None actual=Some("<hp:parameters cnt=\"6\" name=\"\"><hp:integerParam name=\"Prop\">0</hp:integerParam><hp:stringParam name=\"Command\">MEMO/"#;
            if detail.starts_with(MEMO_PREFIX) {
                return true;
            }
            detail == "memo paragraphs: expected=0 actual=1"
        }
        _ => false,
    }
}

fn is_hwp3_to_hwpx_incomparable(
    expected_document: &Document,
    actual_document: &Document,
    d: &IrDifference,
) -> bool {
    match d {
        // HWP3 하이퍼텍스트는 별도 Control::Hyperlink 개체지만 HWPX에는 대응 컨트롤이
        // 없어서 `fieldBegin type="HYPERLINK"`로 승격한다. 비교 축은 Hyperlink를
        // 비슬롯으로 두므로, HWP3 원본의 빈 슬롯과 재파싱된 HWPX field 하나만 정확히
        // 이 형태가 된다. 일반 HWP5 Field의 추가·소실에는 적용하지 않는다.
        IrDifference::ParagraphControls {
            section,
            paragraph,
            path,
            expected,
            actual,
        } => {
            expected == "[]"
                && actual == "[field]"
                && is_hwp3_top_level_hyperlink_field_materialization(
                    expected_document,
                    actual_document,
                    *section,
                    *paragraph,
                    path,
                )
        }
        // HWP3 SC_PICTURE의 영 imgRect는 crop 정보가 없다는 센티널이다. HWPX는
        // `(0,0,width,0)/(width,height,0,height)` 실제 사각형을 반드시 기록한다.
        // curSz·imgDim·다른 기하가 함께 달라지면 detail에 ';'가 붙으므로 남긴다.
        IrDifference::PictureSize { detail, .. } => is_hwp3_zero_img_rect_materialization(detail),
        _ => false,
    }
}

fn is_hwp3_top_level_hyperlink_field_materialization(
    expected_document: &Document,
    actual_document: &Document,
    section: usize,
    paragraph: usize,
    path: &str,
) -> bool {
    // 중첩 문단은 path를 해석해 원본 control까지 확인하는 경로가 아직 없으므로,
    // 추정으로 정규화하지 않고 보수적으로 diff를 남긴다.
    if !path.is_empty() {
        return false;
    }
    let Some(expected) = expected_document
        .sections
        .get(section)
        .and_then(|section| section.paragraphs.get(paragraph))
    else {
        return false;
    };
    let Some(actual) = actual_document
        .sections
        .get(section)
        .and_then(|section| section.paragraphs.get(paragraph))
    else {
        return false;
    };

    expected
        .controls
        .iter()
        .any(|control| matches!(control, crate::model::control::Control::Hyperlink(_)))
        && actual.controls.iter().any(|control| {
            matches!(
                control,
                crate::model::control::Control::Field(field)
                    if field.field_type == crate::model::control::FieldType::Hyperlink
            )
        })
}

fn is_hwp3_zero_img_rect_materialization(detail: &str) -> bool {
    const PREFIX: &str = "imgRect: expected=[0, 0, 0, 0]/[0, 0, 0, 0] actual=";
    if !detail.starts_with(PREFIX) || detail.contains(';') {
        return false;
    }

    let Some((x_part, y_part)) = detail[PREFIX.len()..].split_once('/') else {
        return false;
    };
    let x: Vec<i32> = x_part
        .strip_prefix('[')
        .unwrap_or_default()
        .strip_suffix(']')
        .unwrap_or_default()
        .split(", ")
        .filter_map(|value| value.parse().ok())
        .collect();
    let y: Vec<i32> = y_part
        .strip_prefix('[')
        .unwrap_or_default()
        .strip_suffix(']')
        .unwrap_or_default()
        .split(", ")
        .filter_map(|value| value.parse().ok())
        .collect();
    matches!(
        (x.as_slice(), y.as_slice()),
        ([0, 0, width, 0], [same_width, height, 0, same_height])
            if *width > 0
                && *height > 0
                && width == same_width
                && height == same_height
    )
}

fn is_hwpx_to_hwp_incomparable(d: &IrDifference) -> bool {
    match d {
        // 한컴 HWPX→HWP5 저장 계약의 SC_PICTURE original dimension 0 sentinel만 허용한다.
        // curSz/imgRect 등 다른 그림 기하가 함께 달라진 경우에는 세미콜론이 있으므로 남긴다.
        IrDifference::PictureSize { detail, .. } => {
            detail.starts_with("imgDim: expected=(")
                && detail.ends_with(" actual=(0, 0)")
                && !detail.contains(';')
        }
        _ => false,
    }
}
/// [#8306] `export-hwpx --verify` 의 기대 IR — 원본 IR 에 HWPX 저장의 **의도된 정규화**를
/// 저장기와 같은 규칙으로 먼저 적용한다.
///
/// - 같은 문단의 두 번째 이후 쪽 번호 위치(#6869): 저장기는 내지 않고 그 자리만큼 뒤
///   위치를 당긴다. 같은 판정([`super::section::hwpx_collapsed_page_number_pos_indices`])으로
///   컨트롤과 그 8유닛 자리를 걷어낸다([`Paragraph::remove_control_slot_like_hwpx_export`]).
/// - 줄이 모두 reflow 합성(bit 31)인 문단(#5847): 저장기는 `linesegarray` 를 내지 않는다
///   ([`super::section::line_segs_are_all_synthetic`]).
///
/// 재파싱 IR 에도 같은 함수를 적용한다 — 합성 줄은 rhwp 가 불러올 때 다시 만들고, 접기는
/// 이미 접힌 문단에서 아무것도 바꾸지 않는다. 비교 자체(`diff_documents`)는 바꾸지 않는다
/// (범용 `ir-diff` 도 그 함수를 쓴다). 이 정규화로 설명되지 않는 차이는 그대로 손실로
/// 보고된다.
///
/// [`Paragraph::remove_control_slot_like_hwpx_export`]: crate::model::paragraph::Paragraph::remove_control_slot_like_hwpx_export
pub fn hwpx_export_expected_document(doc: &Document) -> Document {
    let mut expected = doc.clone();
    for section in &mut expected.sections {
        for para in &mut section.paragraphs {
            normalize_paragraph_like_hwpx_export(para);
        }
    }
    expected
}

fn normalize_paragraph_like_hwpx_export(para: &mut crate::model::paragraph::Paragraph) {
    use crate::model::control::Control;

    for control in &mut para.controls {
        match control {
            Control::Table(table) => {
                for cell in &mut table.cells {
                    cell.paragraphs
                        .iter_mut()
                        .for_each(normalize_paragraph_like_hwpx_export);
                }
                if let Some(caption) = &mut table.caption {
                    caption
                        .paragraphs
                        .iter_mut()
                        .for_each(normalize_paragraph_like_hwpx_export);
                }
            }
            Control::Picture(picture) => {
                if let Some(caption) = &mut picture.caption {
                    caption
                        .paragraphs
                        .iter_mut()
                        .for_each(normalize_paragraph_like_hwpx_export);
                }
            }
            Control::Shape(shape) => {
                if let Some(text_box) = shape_text_box_mut(shape) {
                    text_box
                        .paragraphs
                        .iter_mut()
                        .for_each(normalize_paragraph_like_hwpx_export);
                }
                if let Some(caption) = shape_caption_mut(shape) {
                    caption
                        .paragraphs
                        .iter_mut()
                        .for_each(normalize_paragraph_like_hwpx_export);
                }
            }
            Control::Footnote(note) => note
                .paragraphs
                .iter_mut()
                .for_each(normalize_paragraph_like_hwpx_export),
            Control::Endnote(note) => note
                .paragraphs
                .iter_mut()
                .for_each(normalize_paragraph_like_hwpx_export),
            Control::Header(header) => header
                .paragraphs
                .iter_mut()
                .for_each(normalize_paragraph_like_hwpx_export),
            Control::Footer(footer) => footer
                .paragraphs
                .iter_mut()
                .for_each(normalize_paragraph_like_hwpx_export),
            _ => {}
        }
    }

    // 뒤에서부터 걷어내야 앞 컨트롤의 자리 좌표가 유지된다.
    for index in super::section::hwpx_collapsed_page_number_pos_indices(para)
        .into_iter()
        .rev()
    {
        para.remove_control_slot_like_hwpx_export(index);
    }
    if super::section::line_segs_are_all_synthetic(&para.line_segs) {
        para.line_segs.clear();
    }
}

fn shape_text_box_mut(
    s: &mut crate::model::shape::ShapeObject,
) -> Option<&mut crate::model::shape::TextBox> {
    use crate::model::shape::ShapeObject::*;
    match s {
        Line(x) => x.drawing.text_box.as_mut(),
        Rectangle(x) => x.drawing.text_box.as_mut(),
        Ellipse(x) => x.drawing.text_box.as_mut(),
        Arc(x) => x.drawing.text_box.as_mut(),
        Polygon(x) => x.drawing.text_box.as_mut(),
        Curve(x) => x.drawing.text_box.as_mut(),
        Chart(x) => x.drawing.text_box.as_mut(),
        Ole(x) => x.drawing.text_box.as_mut(),
        Group(_) | Picture(_) => None,
    }
}

fn shape_caption_mut(
    s: &mut crate::model::shape::ShapeObject,
) -> Option<&mut crate::model::shape::Caption> {
    use crate::model::shape::ShapeObject::*;
    match s {
        Line(x) => x.drawing.caption.as_mut(),
        Rectangle(x) => x.drawing.caption.as_mut(),
        Ellipse(x) => x.drawing.caption.as_mut(),
        Arc(x) => x.drawing.caption.as_mut(),
        Polygon(x) => x.drawing.caption.as_mut(),
        Curve(x) => x.drawing.caption.as_mut(),
        Chart(x) => x.caption.as_mut(),
        Ole(x) => x.caption.as_mut(),
        Group(x) => x.caption.as_mut(),
        Picture(x) => x.caption.as_mut(),
    }
}

pub fn diff_documents(a: &Document, b: &Document) -> IrDiff {
    let mut diff = IrDiff::default();

    // 섹션 수
    if a.sections.len() != b.sections.len() {
        diff.push(IrDifference::SectionCount {
            expected: a.sections.len(),
            actual: b.sections.len(),
        });
    }

    // 각 섹션의 문단 수 (섹션 수가 같을 때만 대응 비교)
    let pairs = a.sections.len().min(b.sections.len());
    for i in 0..pairs {
        let ap = a.sections[i].paragraphs.len();
        let bp = b.sections[i].paragraphs.len();
        if ap != bp {
            diff.push(IrDifference::ParagraphCount {
                section: i,
                expected: ap,
                actual: bp,
            });
        }

        // 섹션 PageDef(용지·여백) 비교 (#1388) — secPr 페이지 여백 보존 게이트.
        if let Some(detail) = diff_page_def(
            &a.sections[i].section_def.page_def,
            &b.sections[i].section_def.page_def,
        ) {
            diff.push(IrDifference::SectionPageDef { section: i, detail });
        }

        // 섹션 visibility(hideFirstEmptyLine 등) 비교 (#1637) — secPr visibility 보존 게이트.
        if let Some(detail) =
            diff_visibility(&a.sections[i].section_def, &b.sections[i].section_def)
        {
            diff.push(IrDifference::SectionVisibility { section: i, detail });
        }

        // 문단별 char_shapes 시퀀스 비교 (#1378) — run 분할 보존 게이트.
        // 본문 + 셀(Table)·글상자(Shape/TextBox)·각주/미주 내부 문단 재귀 (3단계 확장).
        let pp = ap.min(bp);
        for j in 0..pp {
            diff_paragraph_char_shapes(
                &mut diff,
                i,
                j,
                "",
                &a.sections[i].paragraphs[j],
                &b.sections[i].paragraphs[j],
            );
        }
    }

    // DocInfo 리소스 카운트
    if a.doc_info.char_shapes.len() != b.doc_info.char_shapes.len() {
        diff.push(IrDifference::CharShapeCount {
            expected: a.doc_info.char_shapes.len(),
            actual: b.doc_info.char_shapes.len(),
        });
    }
    if a.doc_info.para_shapes.len() != b.doc_info.para_shapes.len() {
        diff.push(IrDifference::ParaShapeCount {
            expected: a.doc_info.para_shapes.len(),
            actual: b.doc_info.para_shapes.len(),
        });
    }
    if a.doc_info.border_fills.len() != b.doc_info.border_fills.len() {
        diff.push(IrDifference::BorderFillCount {
            expected: a.doc_info.border_fills.len(),
            actual: b.doc_info.border_fills.len(),
        });
    }
    if a.doc_info.tab_defs.len() != b.doc_info.tab_defs.len() {
        diff.push(IrDifference::TabDefCount {
            expected: a.doc_info.tab_defs.len(),
            actual: b.doc_info.tab_defs.len(),
        });
    }
    if a.doc_info.numberings.len() != b.doc_info.numberings.len() {
        diff.push(IrDifference::NumberingCount {
            expected: a.doc_info.numberings.len(),
            actual: b.doc_info.numberings.len(),
        });
    }
    if a.doc_info.styles.len() != b.doc_info.styles.len() {
        diff.push(IrDifference::StyleCount {
            expected: a.doc_info.styles.len(),
            actual: b.doc_info.styles.len(),
        });
    }

    // BinData
    //
    // [#3505] 바이트가 0인 항목은 세지 않는다. HWP3 파서는 그림 컨트롤마다 id·확장자·
    // 바이트가 모두 빈 placeholder 를 만드는데(hwp3-sample10.hwp 3건), 저장기가 그것을
    // 쓰지 않는 것은 손실이 아니다. 실제 이미지는 컨트롤 내부 경로로 실려 렌더된다.
    // [#2550] 빈 판정에 전체 해제(`load()`)를 쓰지 않는다 — `is_empty()` 는 리졸버의
    // bounded 경로를 타므로 deflate bomb 에도 안전하다.
    let non_empty = |d: &Document| -> usize {
        d.bin_data_content
            .iter()
            .filter(|c| !c.data.is_empty())
            .count()
    };
    if non_empty(a) != non_empty(b) {
        diff.push(IrDifference::BinDataContentCount {
            expected: non_empty(a),
            actual: non_empty(b),
        });
    }

    // 문단별 line_segs 비교 (#1380) — lineseg 원본 보존 게이트 (3단계 동승).
    // 순회 경로는 diff_paragraph_char_shapes 와 동일 (본문 + 셀·글상자·각주/미주 재귀).
    for d in diff_linesegs(a, b) {
        diff.push(IrDifference::ParagraphLinesegs {
            section: d.section,
            paragraph: d.paragraph,
            path: d.path,
            detail: d.kind.to_string(),
        });
    }

    diff
}

/// 표 캡션 비교 (#1387). 존재 비대칭/속성/문단 수 불일치를 "field: expected=..
/// actual=.." 세미콜론 연결로 돌려준다. 일치하면 `None`.
/// 그림/도형/묶음 캡션(#1403)도 동일 비교를 공유한다 (`ObjectCaption` 으로 보고).
///
/// `vert_align` 은 비교 제외 — HWPX `hp:caption` 에 대응 속성이 없는 HWP5 유래
/// 필드라(#1387 1단계 전수 측정) serializer 가 방출하지 않으며, HWP5 출발 플로우
/// 비교에서 위양성을 만든다. 내부 문단의 상세 비교는 char_shapes/controls/linesegs
/// 재귀가 담당하므로 여기서는 문단 수만 본다.
fn diff_table_caption(
    a: &Option<crate::model::shape::Caption>,
    b: &Option<crate::model::shape::Caption>,
) -> Option<String> {
    let (a, b) = match (a, b) {
        (None, None) => return None,
        (Some(_), None) => return Some("missing: expected=Some actual=None".to_string()),
        (None, Some(_)) => return Some("synthetic: expected=None actual=Some".to_string()),
        (Some(a), Some(b)) => (a, b),
    };
    let mut parts: Vec<String> = Vec::new();
    if a.direction != b.direction {
        parts.push(format!(
            "side: expected={:?} actual={:?}",
            a.direction, b.direction
        ));
    }
    if a.include_margin != b.include_margin {
        parts.push(format!(
            "fullSz: expected={} actual={}",
            a.include_margin, b.include_margin
        ));
    }
    if a.width != b.width {
        parts.push(format!("width: expected={} actual={}", a.width, b.width));
    }
    if a.spacing != b.spacing {
        parts.push(format!("gap: expected={} actual={}", a.spacing, b.spacing));
    }
    if a.max_width != b.max_width {
        parts.push(format!(
            "lastWidth: expected={} actual={}",
            a.max_width, b.max_width
        ));
    }
    if a.paragraphs.len() != b.paragraphs.len() {
        parts.push(format!(
            "paragraphs: expected={} actual={}",
            a.paragraphs.len(),
            b.paragraphs.len()
        ));
    }
    if parts.is_empty() {
        None
    } else {
        Some(parts.join("; "))
    }
}

/// 섹션 `PageDef` 비교 (#1388). 불일치 필드를 "field: expected=.. actual=.." 로 모아
/// 세미콜론으로 연결해 돌려준다. 일치하면 `None`.
///
/// 비교 제외 필드와 사유:
/// - `attr`: 비트 원본 — `binding`/`landscape` 와 의미 중복 (해석 필드 쪽을 비교)
/// - `pagination_bottom_tolerance`: 렌더러 내부 허용치 — 파일 포맷 필드 아님
fn diff_page_def(
    a: &crate::model::page::PageDef,
    b: &crate::model::page::PageDef,
) -> Option<String> {
    let mut parts: Vec<String> = Vec::new();
    macro_rules! cmp_field {
        ($field:ident) => {
            if a.$field != b.$field {
                parts.push(format!(
                    "{}: expected={} actual={}",
                    stringify!($field),
                    a.$field,
                    b.$field
                ));
            }
        };
    }
    cmp_field!(width);
    cmp_field!(height);
    cmp_field!(margin_left);
    cmp_field!(margin_right);
    cmp_field!(margin_top);
    cmp_field!(margin_bottom);
    cmp_field!(margin_header);
    cmp_field!(margin_footer);
    cmp_field!(margin_gutter);
    cmp_field!(landscape);
    if a.binding != b.binding {
        parts.push(format!(
            "binding: expected={:?} actual={:?}",
            a.binding, b.binding
        ));
    }
    if parts.is_empty() {
        None
    } else {
        Some(parts.join("; "))
    }
}

/// 섹션 `<hp:visibility>` 플래그 비교 (#1637) — secPr visibility 보존 게이트.
///
/// IR(SectionDef)에 보존되는 8필드만 비교한다(hideFirstPageNum·showLineNumber 는
/// 파서가 IR 에 적재하지 않으므로 제외). 직렬화기가 visibility 를 IR 로 방출하지 않으면
/// (특히 hide_empty_line) 페이지네이션이 달라지는 IR-invisible 결함을 게이트화한다.
fn diff_visibility(
    a: &crate::model::document::SectionDef,
    b: &crate::model::document::SectionDef,
) -> Option<String> {
    let mut parts: Vec<String> = Vec::new();
    macro_rules! cmp_field {
        ($field:ident) => {
            if a.$field != b.$field {
                parts.push(format!(
                    "{}: expected={} actual={}",
                    stringify!($field),
                    a.$field,
                    b.$field
                ));
            }
        };
    }
    cmp_field!(hide_header);
    cmp_field!(hide_footer);
    cmp_field!(hide_master_page);
    cmp_field!(hide_border);
    cmp_field!(hide_fill);
    // [#5717] 구역 첫 쪽에만 테두리/배경 (visibility SHOW_FIRST) 보존 게이트
    cmp_field!(first_page_border);
    cmp_field!(first_page_fill);
    cmp_field!(hide_empty_line);
    if parts.is_empty() {
        None
    } else {
        Some(parts.join("; "))
    }
}

/// 문단별 lineseg 비교 결과 1건 (Task #1380).
///
/// `diff_documents` 가 `IrDifference::ParagraphLinesegs` 로 변환해 게이트에 동승하고
/// (3단계), `hwpx-roundtrip` 배치 진단의 필드 단위 TSV 측정에도 직접 사용한다.
///
/// `path` 표기는 `IrDifference::ParagraphCharShapes` 와 동일
/// (본문 문단은 빈 문자열, 중첩 문단은 `/ctrl[i]tbl.cell[j].p[k]` 식).
#[derive(Debug, Clone)]
pub struct LinesegDiff {
    pub section: usize,
    pub paragraph: usize,
    pub path: String,
    pub kind: LinesegDiffKind,
}

/// lineseg 불일치 종류.
#[derive(Debug, Clone)]
pub enum LinesegDiffKind {
    /// 문단의 lineseg 개수 불일치.
    CountMismatch { expected: usize, actual: usize },
    /// 같은 인덱스 lineseg 의 필드 값 불일치. `field` 는 HWPX 속성명
    /// (textpos/vertpos/vertsize/textheight/baseline/spacing/horzpos/horzsize/flags).
    ValueMismatch {
        index: usize,
        field: &'static str,
        expected: i64,
        actual: i64,
    },
}

impl std::fmt::Display for LinesegDiffKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LinesegDiffKind::CountMismatch { expected, actual } => {
                write!(f, "count: expected={} actual={}", expected, actual)
            }
            LinesegDiffKind::ValueMismatch {
                index,
                field,
                expected,
                actual,
            } => write!(
                f,
                "[{}].{}: expected={} actual={}",
                index, field, expected, actual
            ),
        }
    }
}

/// 문서 전체의 문단별 `line_segs` 를 비교한다 (Task #1380).
///
/// 1단계에서는 측정 전용이었고, 3단계부터 `diff_documents` 가 이 결과를
/// `ParagraphLinesegs` 로 변환해 baseline 게이트에 동승한다.
/// 순회 경로는 `diff_paragraph_char_shapes` 와 동일 (본문 + 셀·글상자(Group 재귀)·
/// 각주/미주). 개수 불일치 시에도 공통 구간(min)은 값 비교를 계속한다.
pub fn diff_linesegs(a: &Document, b: &Document) -> Vec<LinesegDiff> {
    let mut out = Vec::new();
    let pairs = a.sections.len().min(b.sections.len());
    for i in 0..pairs {
        let pp = a.sections[i]
            .paragraphs
            .len()
            .min(b.sections[i].paragraphs.len());
        for j in 0..pp {
            diff_paragraph_linesegs(
                &mut out,
                i,
                j,
                "",
                &a.sections[i].paragraphs[j],
                &b.sections[i].paragraphs[j],
            );
        }
    }
    out
}

/// [#5563] 비교 대상이 되는 줄 — 저장기가 실제로 파일에 실을 수 있는 접두부.
fn axis_comparable_line_segs(
    para: &crate::model::paragraph::Paragraph,
    axis_end: u32,
) -> &[crate::model::paragraph::LineSeg] {
    if axis_end == 0 {
        return &para.line_segs;
    }
    crate::serializer::body_text::line_segs_within_text_axis(&para.line_segs, axis_end)
}

/// [#5943] 이 문단에서 HWPX 슬롯 축 재기준화로 설명 가능한 `textpos` 이동 상한.
///
/// `hp:secPr`·`hp:colPr` 은 HWPX 문단 슬롯 축을 차지하지 않으므로 슬롯당 8유닛씩만
/// 내려갈 수 있다. 그 문단이 실제로 들고 있는 개수로 상한을 잡으므로, secd·cold 가
/// 없는 평범한 문단은 0 — 허용치가 전혀 생기지 않는다.
fn axis_rebase_cap(pa: &crate::model::paragraph::Paragraph) -> u32 {
    use crate::model::control::Control;
    8 * pa
        .controls
        .iter()
        .filter(|c| matches!(c, Control::SectionDef(_) | Control::ColumnDef(_)))
        .count() as u32
}

/// 문단 1쌍의 lineseg 비교 + 컨트롤 내부 문단 재귀 (`diff_paragraph_char_shapes` 와
/// 동일 경로 순회).
fn diff_paragraph_linesegs(
    out: &mut Vec<LinesegDiff>,
    section: usize,
    paragraph: usize,
    path: &str,
    pa: &crate::model::paragraph::Paragraph,
    pb: &crate::model::paragraph::Paragraph,
) {
    diff_paragraph_linesegs_with_axis(
        out,
        section,
        paragraph,
        path,
        pa,
        pb,
        pa.char_count,
        pb.char_count,
    );
}

fn diff_paragraph_linesegs_with_axis(
    out: &mut Vec<LinesegDiff>,
    section: usize,
    paragraph: usize,
    path: &str,
    pa: &crate::model::paragraph::Paragraph,
    pb: &crate::model::paragraph::Paragraph,
    a_axis_end: u32,
    b_axis_end: u32,
) {
    use crate::model::control::Control;

    // [#5563] 문단 축을 넘어서는 줄은 저장기가 파일에 싣지 않는다(HWPX·HWP5 공통
    // 계약 — `line_segs_within_text_axis`). 비교에서도 같은 규칙을 먼저 걸어야
    // "저장할 수 없는 줄"이 IR 차이로 잡히지 않는다. 축 증거가 없는 합성 IR
    // (`char_count == 0`)은 종전대로 전부 비교한다.
    // HWP3/HWPX adapter는 SectionDef·필드 안내문 슬롯을 저장 직전에 보강한다. live
    // 원본 IR의 char_count는 그대로인 반면 재적재본은 늘어난 축을 보고한다. 한쪽만
    // 작은 축으로 자르면 정상 lineseg가 새 손실로 보이므로, 두 문단이 공유하는 더 긴
    // 저장 축을 양쪽에 적용한다 (#5563, hwp3-table-caption).
    let comparable_axis_end = a_axis_end.max(b_axis_end);
    let la = axis_comparable_line_segs(pa, comparable_axis_end);
    let lb = axis_comparable_line_segs(pb, comparable_axis_end);
    if la.len() != lb.len() {
        out.push(LinesegDiff {
            section,
            paragraph,
            path: path.to_string(),
            kind: LinesegDiffKind::CountMismatch {
                expected: la.len(),
                actual: lb.len(),
            },
        });
    }
    // [#5943] HWP5 축 ↔ HWPX 축 교차 비교의 `textpos` 허용치.
    //
    // `hp:secPr`·`hp:colPr` 은 HWPX 문단 슬롯 축을 차지하지 않으므로, HWP5 출처를 HWPX 로
    // 내면 저장 lineseg 의 `textpos` 가 그만큼 내려간다(그렇게 내지 않으면 한글 2024 가
    // 본문을 폐기한다 — #5943). 그 산출을 다시 읽어 원본 IR 과 대면 비교하는 `--verify`
    // 에서는 두 축이 정당하게 다르므로, **그 문단에 실제로 있는 secd·cold 슬롯으로
    // 설명되는 만큼만** 봐준다. 위양성을 없애되 임의의 어긋남은 그대로 잡는다.
    let axis_rebase_cap = axis_rebase_cap(pa);
    for (idx, (sa, sb)) in la.iter().zip(lb.iter()).enumerate() {
        // [#5961] 비교 전에 **양쪽을 각자의 문단 축 보정폭으로 HWP5 축에 올린다**.
        //
        // 위 #5943 허용치는 HWP5 출처 → HWPX 산출 한 방향만 본다. 반대 방향
        // (HWPX 출처 → HWP5 산출)에서는 산출 쪽이 **더 큰** 축을 갖는다 — HWP5 파일은
        // 구역 정의와 첫 단 정의에 8유닛씩을 싣기 때문이다. 그대로 빼면 음수라
        // `checked_sub` 가 `u32::MAX` 로 흘러 허용치가 닿지 않고, 정당한 축 차이가
        // 저장 손실로 잡힌다(x2h 코퍼스 5건).
        //
        // 보정폭은 추측이 아니라 파서가 자기가 만들어 넣은 슬롯 수로 채운 사실이다
        // (`Paragraph::hwpx_axis_shift`). HWPX 출처 문단만 0 이 아니므로 같은 축끼리의
        // 비교에는 아무 영향이 없다.
        let ta = pa.line_seg_text_start_of(sa.text_start);
        let tb = pb.line_seg_text_start_of(sb.text_start);
        // 줄 하나가 내려간 폭이 8의 배수이고 상한 안이면 재기준화로 설명된다.
        let shift = ta.checked_sub(tb).unwrap_or(u32::MAX);
        let text_start_a = if shift > 0 && shift.is_multiple_of(8) && shift <= axis_rebase_cap {
            tb
        } else {
            ta
        };
        let fields: [(&'static str, i64, i64); 9] = [
            ("textpos", text_start_a as i64, tb as i64),
            ("vertpos", sa.vertical_pos as i64, sb.vertical_pos as i64),
            ("vertsize", sa.line_height as i64, sb.line_height as i64),
            ("textheight", sa.text_height as i64, sb.text_height as i64),
            (
                "baseline",
                sa.baseline_distance as i64,
                sb.baseline_distance as i64,
            ),
            ("spacing", sa.line_spacing as i64, sb.line_spacing as i64),
            ("horzpos", sa.column_start as i64, sb.column_start as i64),
            ("horzsize", sa.segment_width as i64, sb.segment_width as i64),
            ("flags", sa.tag as i64, sb.tag as i64),
        ];
        for (field, ea, eb) in fields {
            if ea != eb {
                out.push(LinesegDiff {
                    section,
                    paragraph,
                    path: path.to_string(),
                    kind: LinesegDiffKind::ValueMismatch {
                        index: idx,
                        field,
                        expected: ea,
                        actual: eb,
                    },
                });
            }
        }
    }

    for (ci, (ctrl_a, ctrl_b)) in pa.controls.iter().zip(pb.controls.iter()).enumerate() {
        match (ctrl_a, ctrl_b) {
            (Control::Table(ta), Control::Table(tb)) => {
                for (cell_i, (cea, ceb)) in ta.cells.iter().zip(tb.cells.iter()).enumerate() {
                    for (k, (qa, qb)) in
                        cea.paragraphs.iter().zip(ceb.paragraphs.iter()).enumerate()
                    {
                        let p = format!("{path}/ctrl[{ci}]tbl.cell[{cell_i}].p[{k}]");
                        diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
                    }
                }
                // 표 캡션 내부 문단 lineseg 재귀 (#1387) — 존재/속성 비교는
                // diff_paragraph_char_shapes 쪽 한 곳에서 수행.
                if let (Some(ca), Some(cb)) = (&ta.caption, &tb.caption) {
                    for (k, (qa, qb)) in ca.paragraphs.iter().zip(cb.paragraphs.iter()).enumerate()
                    {
                        let p = format!("{path}/ctrl[{ci}]tbl.caption.p[{k}]");
                        diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
                    }
                }
            }
            // 그림 캡션 내부 문단 lineseg 재귀 (#1403 후속 — char_shapes 쪽과 대칭 복원).
            (Control::Picture(pia), Control::Picture(pib)) => {
                if let (Some(ca), Some(cb)) = (&pia.caption, &pib.caption) {
                    for (k, (qa, qb)) in ca.paragraphs.iter().zip(cb.paragraphs.iter()).enumerate()
                    {
                        let p = format!("{path}/ctrl[{ci}]pic.caption.p[{k}]");
                        diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
                    }
                }
            }
            (Control::Shape(sa), Control::Shape(sb)) => {
                let p = format!("{path}/ctrl[{ci}]shape");
                diff_shape_linesegs(out, section, paragraph, &p, sa, sb);
            }
            (Control::Footnote(na), Control::Footnote(nb)) => {
                for (k, (qa, qb)) in na.paragraphs.iter().zip(nb.paragraphs.iter()).enumerate() {
                    let p = format!("{path}/ctrl[{ci}]fn.p[{k}]");
                    diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
                }
            }
            (Control::Endnote(na), Control::Endnote(nb)) => {
                for (k, (qa, qb)) in na.paragraphs.iter().zip(nb.paragraphs.iter()).enumerate() {
                    let p = format!("{path}/ctrl[{ci}]en.p[{k}]");
                    diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
                }
            }
            // MEMO 본문 문단 lineseg 재귀 (#1391).
            (Control::Field(fa), Control::Field(fb)) => {
                for (k, (qa, qb)) in fa
                    .memo_paragraphs
                    .iter()
                    .zip(fb.memo_paragraphs.iter())
                    .enumerate()
                {
                    let p = format!("{path}/ctrl[{ci}]field.memo.p[{k}]");
                    diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
                }
            }
            _ => {}
        }
    }
}

/// 도형 내부 글상자(TextBox) 문단 lineseg 재귀 비교 — Group 은 자식 도형까지 재귀.
fn diff_shape_linesegs(
    out: &mut Vec<LinesegDiff>,
    section: usize,
    paragraph: usize,
    path: &str,
    sa: &crate::model::shape::ShapeObject,
    sb: &crate::model::shape::ShapeObject,
) {
    use crate::model::shape::ShapeObject;
    if let (Some(ta), Some(tb)) = (shape_text_box(sa), shape_text_box(sb)) {
        for (k, (qa, qb)) in ta.paragraphs.iter().zip(tb.paragraphs.iter()).enumerate() {
            let p = format!("{path}.tb.p[{k}]");
            diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
        }
    }
    // 도형/묶음 캡션 내부 문단 lineseg 재귀 (#1403 후속 — char_shapes 쪽과 대칭 복원).
    if let (Some(ca), Some(cb)) = (shape_caption(sa), shape_caption(sb)) {
        for (k, (qa, qb)) in ca.paragraphs.iter().zip(cb.paragraphs.iter()).enumerate() {
            let p = format!("{path}.caption.p[{k}]");
            diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
        }
    }
    if let (ShapeObject::Group(ga), ShapeObject::Group(gb)) = (sa, sb) {
        for (k, (c1, c2)) in ga.children.iter().zip(gb.children.iter()).enumerate() {
            let p = format!("{path}.child[{k}]");
            diff_shape_linesegs(out, section, paragraph, &p, c1, c2);
        }
    }
}

/// 문단 char_shapes 시퀀스(#1378)와 인라인 슬롯 컨트롤 타입 시퀀스(#1379)를 비교하고,
/// 컨트롤 내부 문단(셀·글상자·각주/미주)을 재귀 비교한다.
///
/// 컨트롤 쌍의 재귀는 인덱스 대응(zip)으로만 내려간다 — 수·타입 불일치는
/// `ParagraphControls` 가 해당 문단 수준에서 검출한다.
fn diff_paragraph_char_shapes(
    diff: &mut IrDiff,
    section: usize,
    paragraph: usize,
    path: &str,
    pa: &crate::model::paragraph::Paragraph,
    pb: &crate::model::paragraph::Paragraph,
) {
    use crate::model::control::Control;

    let ca = &pa.char_shapes;
    let cb = &pb.char_shapes;
    let same = ca.len() == cb.len()
        && ca
            .iter()
            .zip(cb.iter())
            .all(|(x, y)| x.start_pos == y.start_pos && x.char_shape_id == y.char_shape_id);
    if !same {
        diff.push(IrDifference::ParagraphCharShapes {
            section,
            paragraph,
            path: path.to_string(),
            expected: format_char_shapes(ca),
            actual: format_char_shapes(cb),
        });
    }

    // 인라인 슬롯 컨트롤 타입 시퀀스 비교 (#1379) — subList 컨트롤 소실 검출.
    // Bookmark 등 위치 정보가 없는 비슬롯 컨트롤은 제외 (serializer 가 문단 선두로
    // 재배치하므로 순서 비교가 성립하지 않음).
    let sa: Vec<&Control> = pa
        .controls
        .iter()
        .filter(|c| is_hwpx_inline_slot(c))
        .collect();
    let sb: Vec<&Control> = pb
        .controls
        .iter()
        .filter(|c| is_hwpx_inline_slot(c))
        .collect();
    let ctrl_same = sa.len() == sb.len()
        && sa
            .iter()
            .zip(sb.iter())
            .all(|(x, y)| control_type_name(x) == control_type_name(y));
    if !ctrl_same {
        diff.push(IrDifference::ParagraphControls {
            section,
            paragraph,
            path: path.to_string(),
            expected: format_control_types(&sa),
            actual: format_control_types(&sb),
        });
    }
    for (ci, (ctrl_a, ctrl_b)) in pa.controls.iter().zip(pb.controls.iter()).enumerate() {
        match (ctrl_a, ctrl_b) {
            (Control::Table(ta), Control::Table(tb)) => {
                // 표 page_break 비교 (#1393) — 방출은 PR #1405 정정, 게이트 회귀 봉인.
                if ta.page_break != tb.page_break {
                    diff.push(IrDifference::TablePageBreak {
                        section,
                        paragraph,
                        path: format!("{path}/ctrl[{ci}]tbl"),
                        detail: format!("expected={:?} actual={:?}", ta.page_break, tb.page_break),
                    });
                }
                // [#1594] holdAnchorAndSO 보존 게이트 — 페이지 하단 앵커 개체 붕괴 봉인.
                if let Some(detail) = diff_hold_anchor(&ta.common, &tb.common) {
                    diff.push(IrDifference::ObjectHoldAnchor {
                        section,
                        paragraph,
                        path: format!("{path}/ctrl[{ci}]tbl"),
                        detail,
                    });
                }
                // [#1637] flowWithText 보존 게이트 — 표 partial-split 임계 변동 봉인.
                if let Some(detail) = diff_flow_with_text(&ta.common, &tb.common) {
                    diff.push(IrDifference::ObjectFlowWithText {
                        section,
                        paragraph,
                        path: format!("{path}/ctrl[{ci}]tbl"),
                        detail,
                    });
                }
                for (cell_i, (cea, ceb)) in ta.cells.iter().zip(tb.cells.iter()).enumerate() {
                    for (k, (qa, qb)) in
                        cea.paragraphs.iter().zip(ceb.paragraphs.iter()).enumerate()
                    {
                        let p = format!("{path}/ctrl[{ci}]tbl.cell[{cell_i}].p[{k}]");
                        diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
                    }
                }
                // 표 캡션 비교 (#1387) — 존재/속성/문단 수 + 내부 문단 재귀.
                if let Some(detail) = diff_table_caption(&ta.caption, &tb.caption) {
                    diff.push(IrDifference::TableCaption {
                        section,
                        paragraph,
                        path: format!("{path}/ctrl[{ci}]tbl.caption"),
                        detail,
                    });
                }
                if let (Some(ca), Some(cb)) = (&ta.caption, &tb.caption) {
                    for (k, (qa, qb)) in ca.paragraphs.iter().zip(cb.paragraphs.iter()).enumerate()
                    {
                        let p = format!("{path}/ctrl[{ci}]tbl.caption.p[{k}]");
                        diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
                    }
                }
            }
            // 그림 캡션 비교 (#1403) — 존재/속성/문단 수 + 내부 문단 재귀.
            (Control::Picture(pia), Control::Picture(pib)) => {
                // 그림 크기 요소 비교 (#1389) — curSz/imgRect/imgDim IR 보존 게이트.
                if let Some(detail) = diff_picture_size(pia, pib) {
                    diff.push(IrDifference::PictureSize {
                        section,
                        paragraph,
                        path: format!("{path}/ctrl[{ci}]pic"),
                        detail,
                    });
                }
                if let Some(detail) = diff_table_caption(&pia.caption, &pib.caption) {
                    diff.push(IrDifference::ObjectCaption {
                        section,
                        paragraph,
                        path: format!("{path}/ctrl[{ci}]pic.caption"),
                        detail,
                    });
                }
                // 그림 설명 비교 (#1392).
                if let Some(detail) =
                    diff_object_comment(&pia.common.description, &pib.common.description)
                {
                    diff.push(IrDifference::ObjectComment {
                        section,
                        paragraph,
                        path: format!("{path}/ctrl[{ci}]pic"),
                        detail,
                    });
                }
                // [#1594] holdAnchorAndSO 보존 게이트.
                if let Some(detail) = diff_hold_anchor(&pia.common, &pib.common) {
                    diff.push(IrDifference::ObjectHoldAnchor {
                        section,
                        paragraph,
                        path: format!("{path}/ctrl[{ci}]pic"),
                        detail,
                    });
                }
                if let (Some(ca), Some(cb)) = (&pia.caption, &pib.caption) {
                    for (k, (qa, qb)) in ca.paragraphs.iter().zip(cb.paragraphs.iter()).enumerate()
                    {
                        let p = format!("{path}/ctrl[{ci}]pic.caption.p[{k}]");
                        diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
                    }
                }
            }
            // 수식 설명 비교 (#1392) — equation 은 본문 텍스트 비교 대상이 아니므로
            // description 만 동승.
            (Control::Equation(ea), Control::Equation(eb)) => {
                if let Some(detail) =
                    diff_object_comment(&ea.common.description, &eb.common.description)
                {
                    diff.push(IrDifference::ObjectComment {
                        section,
                        paragraph,
                        path: format!("{path}/ctrl[{ci}]eq"),
                        detail,
                    });
                }
                // [#1594] holdAnchorAndSO 보존 게이트.
                if let Some(detail) = diff_hold_anchor(&ea.common, &eb.common) {
                    diff.push(IrDifference::ObjectHoldAnchor {
                        section,
                        paragraph,
                        path: format!("{path}/ctrl[{ci}]eq"),
                        detail,
                    });
                }
                // [#1655] 수식 flowWithText 보존 게이트.
                if let Some(detail) = diff_flow_with_text(&ea.common, &eb.common) {
                    diff.push(IrDifference::ObjectFlowWithText {
                        section,
                        paragraph,
                        path: format!("{path}/ctrl[{ci}]eq"),
                        detail,
                    });
                }
            }
            (Control::Shape(sa), Control::Shape(sb)) => {
                let p = format!("{path}/ctrl[{ci}]shape");
                diff_shape_char_shapes(diff, section, paragraph, &p, sa, sb);
            }
            (Control::Footnote(na), Control::Footnote(nb)) => {
                for (k, (qa, qb)) in na.paragraphs.iter().zip(nb.paragraphs.iter()).enumerate() {
                    let p = format!("{path}/ctrl[{ci}]fn.p[{k}]");
                    diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
                }
            }
            (Control::Endnote(na), Control::Endnote(nb)) => {
                for (k, (qa, qb)) in na.paragraphs.iter().zip(nb.paragraphs.iter()).enumerate() {
                    let p = format!("{path}/ctrl[{ci}]en.p[{k}]");
                    diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
                }
            }
            // 필드 parameters / MEMO 본문 비교 (#1391).
            (Control::Field(fa), Control::Field(fb)) => {
                if fa.raw_parameters_xml != fb.raw_parameters_xml {
                    diff.push(IrDifference::FieldContent {
                        section,
                        paragraph,
                        path: format!("{path}/ctrl[{ci}]field"),
                        detail: format!(
                            "parameters: expected={:?} actual={:?}",
                            fa.raw_parameters_xml, fb.raw_parameters_xml
                        ),
                    });
                }
                if fa.memo_paragraphs.len() != fb.memo_paragraphs.len() {
                    diff.push(IrDifference::FieldContent {
                        section,
                        paragraph,
                        path: format!("{path}/ctrl[{ci}]field"),
                        detail: format!(
                            "memo paragraphs: expected={} actual={}",
                            fa.memo_paragraphs.len(),
                            fb.memo_paragraphs.len()
                        ),
                    });
                }
                for (k, (qa, qb)) in fa
                    .memo_paragraphs
                    .iter()
                    .zip(fb.memo_paragraphs.iter())
                    .enumerate()
                {
                    let p = format!("{path}/ctrl[{ci}]field.memo.p[{k}]");
                    diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
                }
            }
            _ => {}
        }
    }
}

/// 도형 내부 글상자(TextBox) 문단 재귀 비교 — Group 은 자식 도형까지 재귀.
fn diff_shape_char_shapes(
    diff: &mut IrDiff,
    section: usize,
    paragraph: usize,
    path: &str,
    sa: &crate::model::shape::ShapeObject,
    sb: &crate::model::shape::ShapeObject,
) {
    use crate::model::shape::ShapeObject;
    if let (Some(ta), Some(tb)) = (shape_text_box(sa), shape_text_box(sb)) {
        for (k, (qa, qb)) in ta.paragraphs.iter().zip(tb.paragraphs.iter()).enumerate() {
            let p = format!("{path}.tb.p[{k}]");
            diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
        }
    }
    // 도형/묶음 캡션 비교 (#1403) — 존재/속성/문단 수 + 내부 문단 재귀.
    let (capa, capb) = (shape_caption(sa), shape_caption(sb));
    if let Some(detail) = diff_table_caption(capa, capb) {
        diff.push(IrDifference::ObjectCaption {
            section,
            paragraph,
            path: format!("{path}.caption"),
            detail,
        });
    }
    if let (Some(ca), Some(cb)) = (capa, capb) {
        for (k, (qa, qb)) in ca.paragraphs.iter().zip(cb.paragraphs.iter()).enumerate() {
            let p = format!("{path}.caption.p[{k}]");
            diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
        }
    }
    // 도형/묶음 설명 비교 (#1392).
    if let Some(detail) =
        diff_object_comment(&shape_common(sa).description, &shape_common(sb).description)
    {
        diff.push(IrDifference::ObjectComment {
            section,
            paragraph,
            path: path.to_string(),
            detail,
        });
    }
    if let (ShapeObject::Group(ga), ShapeObject::Group(gb)) = (sa, sb) {
        for (k, (c1, c2)) in ga.children.iter().zip(gb.children.iter()).enumerate() {
            let p = format!("{path}.child[{k}]");
            diff_shape_char_shapes(diff, section, paragraph, &p, c1, c2);
        }
    }
}

/// ShapeObject 에서 `CommonObjAttr` 참조를 꺼낸다 (#1392 — description 비교용).
fn shape_common(s: &crate::model::shape::ShapeObject) -> &crate::model::shape::CommonObjAttr {
    use crate::model::shape::ShapeObject::*;
    match s {
        Line(x) => &x.common,
        Rectangle(x) => &x.common,
        Ellipse(x) => &x.common,
        Arc(x) => &x.common,
        Polygon(x) => &x.common,
        Curve(x) => &x.common,
        Chart(x) => &x.common,
        Ole(x) => &x.common,
        Group(x) => &x.common,
        Picture(x) => &x.common,
    }
}

/// ShapeObject 에서 글상자(TextBox) 참조를 꺼낸다 (없으면 None).
fn shape_text_box(s: &crate::model::shape::ShapeObject) -> Option<&crate::model::shape::TextBox> {
    use crate::model::shape::ShapeObject::*;
    match s {
        Line(x) => x.drawing.text_box.as_ref(),
        Rectangle(x) => x.drawing.text_box.as_ref(),
        Ellipse(x) => x.drawing.text_box.as_ref(),
        Arc(x) => x.drawing.text_box.as_ref(),
        Polygon(x) => x.drawing.text_box.as_ref(),
        Curve(x) => x.drawing.text_box.as_ref(),
        Chart(x) => x.drawing.text_box.as_ref(),
        Ole(x) => x.drawing.text_box.as_ref(),
        Group(_) | Picture(_) => None,
    }
}

/// ShapeObject 에서 캡션 필드 참조를 꺼낸다 (#1403).
/// 그리기 도형은 `drawing.caption`, 묶음/그림/차트/OLE 는 각자의 caption 필드.
fn shape_caption(s: &crate::model::shape::ShapeObject) -> &Option<crate::model::shape::Caption> {
    use crate::model::shape::ShapeObject::*;
    match s {
        Line(x) => &x.drawing.caption,
        Rectangle(x) => &x.drawing.caption,
        Ellipse(x) => &x.drawing.caption,
        Arc(x) => &x.drawing.caption,
        Polygon(x) => &x.drawing.caption,
        Curve(x) => &x.drawing.caption,
        Chart(x) => &x.caption,
        Ole(x) => &x.caption,
        Group(x) => &x.caption,
        Picture(x) => &x.caption,
    }
}

/// 컨트롤 타입 표기 — diff 메시지·시퀀스 비교용 (`render_control_slot` 디스패치 대상).
fn control_type_name(c: &crate::model::control::Control) -> &'static str {
    use crate::model::control::Control::*;
    match c {
        Table(_) => "tbl",
        Picture(_) => "pic",
        Shape(_) => "shape",
        Equation(_) => "eq",
        Footnote(_) => "fn",
        Endnote(_) => "en",
        Field(_) => "field",
        Form(_) => "form",
        Header(_) => "header",
        Footer(_) => "footer",
        AutoNumber(_) => "autoNum",
        PageHide(_) => "pageHide",
        PageNumberPos(_) => "pageNumPos",
        NewNumber(_) => "newNum",
        CharOverlap(_) => "charOverlap",
        Ruby(_) => "ruby",
        _ => "other",
    }
}

/// 컨트롤 타입 시퀀스를 `[tbl,pic, ...]` 형태로 표기 (diff 메시지용).
fn format_control_types(controls: &[&crate::model::control::Control]) -> String {
    let inner = controls
        .iter()
        .map(|c| control_type_name(c))
        .collect::<Vec<_>>()
        .join(",");
    format!("[{}]", inner)
}

/// char_shapes 시퀀스를 `[(start_pos,id), ...]` 형태로 표기 (diff 메시지용).
fn format_char_shapes(refs: &[crate::model::paragraph::CharShapeRef]) -> String {
    let inner = refs
        .iter()
        .map(|r| format!("({},{})", r.start_pos, r.char_shape_id))
        .collect::<Vec<_>>()
        .join(",");
    format!("[{}]", inner)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::paragraph::{CharShapeRef, Paragraph};

    /// char_shapes 시퀀스를 가진 단일 문단 Document 생성.
    fn doc_with_char_shapes(refs: &[(u32, u32)]) -> Document {
        let mut para = Paragraph::default();
        para.char_shapes = refs
            .iter()
            .map(|&(start_pos, char_shape_id)| CharShapeRef {
                start_pos,
                char_shape_id,
            })
            .collect();
        let mut doc = Document::default();
        let mut section: crate::model::document::Section = Default::default();
        section.paragraphs.push(para);
        doc.sections.push(section);
        doc
    }

    #[test]
    fn ir_diff_empty_default() {
        let diff = IrDiff::default();
        assert!(diff.is_empty());
    }

    #[test]
    fn diff_documents_empty_is_empty() {
        let a = Document::default();
        let b = Document::default();
        let diff = diff_documents(&a, &b);
        assert!(diff.is_empty(), "empty vs empty must have no diff");
    }

    #[test]
    fn diff_documents_same_char_shapes_is_empty() {
        let a = doc_with_char_shapes(&[(0, 5), (3, 2), (10, 5)]);
        let b = doc_with_char_shapes(&[(0, 5), (3, 2), (10, 5)]);
        assert!(diff_documents(&a, &b).is_empty());
    }

    #[test]
    fn diff_documents_detects_flattened_char_shapes() {
        // run 평탄화: 다중 char_shapes → 첫 entry 만 출력된 경우를 검출해야 한다.
        let a = doc_with_char_shapes(&[(0, 5), (3, 2)]);
        let b = doc_with_char_shapes(&[(0, 5)]);
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1);
        match &diff.differences[0] {
            IrDifference::ParagraphCharShapes {
                section,
                paragraph,
                path,
                expected,
                actual,
            } => {
                assert_eq!(*section, 0);
                assert_eq!(*paragraph, 0);
                assert_eq!(path, "");
                assert_eq!(expected, "[(0,5),(3,2)]");
                assert_eq!(actual, "[(0,5)]");
            }
            other => panic!("ParagraphCharShapes 여야 함: {:?}", other),
        }
    }

    #[test]
    fn diff_documents_detects_char_shape_pos_change() {
        // 같은 id 라도 start_pos 가 어긋나면 차이로 검출.
        let a = doc_with_char_shapes(&[(0, 5), (3, 2)]);
        let b = doc_with_char_shapes(&[(0, 5), (4, 2)]);
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1);
        assert!(matches!(
            diff.differences[0],
            IrDifference::ParagraphCharShapes { .. }
        ));
    }

    /// `(start_pos, char_shape_id)` 목록 → CharShapeRef 목록.
    fn to_refs(refs: &[(u32, u32)]) -> Vec<CharShapeRef> {
        refs.iter()
            .map(|&(start_pos, char_shape_id)| CharShapeRef {
                start_pos,
                char_shape_id,
            })
            .collect()
    }

    /// 본문 문단 1개 + 컨트롤 1개를 가진 Document 생성.
    fn doc_with_control(ctrl: crate::model::control::Control) -> Document {
        let mut para = Paragraph::default();
        para.controls.push(ctrl);
        let mut doc = Document::default();
        let mut section: crate::model::document::Section = Default::default();
        section.paragraphs.push(para);
        doc.sections.push(section);
        doc
    }

    /// 1x1 표 컨트롤 — 셀 문단의 char_shapes 를 지정.
    fn table_control(cell_refs: &[(u32, u32)]) -> crate::model::control::Control {
        use crate::model::table::{Cell, Table};
        let mut cell_para = Paragraph::default();
        cell_para.char_shapes = to_refs(cell_refs);
        let mut cell = Cell::default();
        cell.col_span = 1;
        cell.row_span = 1;
        cell.paragraphs.push(cell_para);
        let mut t = Table::default();
        t.row_count = 1;
        t.col_count = 1;
        t.cells.push(cell);
        t.rebuild_grid();
        crate::model::control::Control::Table(Box::new(t))
    }

    /// 글상자(Rectangle drawText) 컨트롤 — 문단의 char_shapes 를 지정.
    fn textbox_control(refs: &[(u32, u32)]) -> crate::model::control::Control {
        use crate::model::shape::{RectangleShape, ShapeObject, TextBox};
        let mut p = Paragraph::default();
        p.char_shapes = to_refs(refs);
        let mut tb = TextBox::default();
        tb.paragraphs.push(p);
        let mut rect = RectangleShape::default();
        rect.drawing.text_box = Some(tb);
        crate::model::control::Control::Shape(Box::new(ShapeObject::Rectangle(rect)))
    }

    /// 각주 컨트롤 — 문단의 char_shapes 를 지정.
    fn footnote_control(refs: &[(u32, u32)]) -> crate::model::control::Control {
        let mut p = Paragraph::default();
        p.char_shapes = to_refs(refs);
        let mut note = crate::model::footnote::Footnote::default();
        note.paragraphs.push(p);
        crate::model::control::Control::Footnote(Box::new(note))
    }

    /// 단일 ParagraphCharShapes 차이의 path 를 단언.
    fn assert_single_char_shapes_diff(diff: &IrDiff, expected_path: &str) {
        assert_eq!(diff.differences.len(), 1, "차이 1건이어야 함: {:?}", diff);
        match &diff.differences[0] {
            IrDifference::ParagraphCharShapes { path, .. } => {
                assert_eq!(path, expected_path);
            }
            other => panic!("ParagraphCharShapes 여야 함: {:?}", other),
        }
    }

    #[test]
    fn diff_documents_detects_cell_char_shapes() {
        // 셀 내부 문단 평탄화 검출 (#1378 3단계 게이트 재귀 확장).
        let a = doc_with_control(table_control(&[(0, 1), (3, 2)]));
        let b = doc_with_control(table_control(&[(0, 1)]));
        assert_single_char_shapes_diff(&diff_documents(&a, &b), "/ctrl[0]tbl.cell[0].p[0]");
    }

    #[test]
    fn diff_documents_same_cell_char_shapes_is_empty() {
        let a = doc_with_control(table_control(&[(0, 1), (3, 2)]));
        let b = doc_with_control(table_control(&[(0, 1), (3, 2)]));
        assert!(diff_documents(&a, &b).is_empty());
    }

    #[test]
    fn diff_documents_detects_textbox_char_shapes() {
        // 글상자 내부 문단 평탄화 검출.
        let a = doc_with_control(textbox_control(&[(0, 1), (3, 2)]));
        let b = doc_with_control(textbox_control(&[(0, 1)]));
        assert_single_char_shapes_diff(&diff_documents(&a, &b), "/ctrl[0]shape.tb.p[0]");
    }

    #[test]
    fn diff_documents_detects_footnote_char_shapes() {
        // 각주 내부 문단 평탄화 검출.
        let a = doc_with_control(footnote_control(&[(0, 1), (3, 2)]));
        let b = doc_with_control(footnote_control(&[(0, 1)]));
        assert_single_char_shapes_diff(&diff_documents(&a, &b), "/ctrl[0]fn.p[0]");
    }

    /// serialize → parse 왕복용 본문 구성: p0(빈 첫 문단) + p1(컨트롤 1개, slot 정합).
    fn roundtrip_doc_with_control(ctrl: crate::model::control::Control) -> Document {
        use crate::model::style::CharShape;
        let p0 = Paragraph::default();
        let mut p1 = Paragraph::default();
        p1.char_count = 9; // 슬롯 1개(8) + 1 — inferred_control_slot_count 정합
        p1.char_shapes = to_refs(&[(0, 1)]);
        p1.controls.push(ctrl);
        let mut doc = Document::default();
        doc.doc_info.char_shapes = vec![
            CharShape::default(),
            CharShape::default(),
            CharShape::default(),
        ];
        // 셀 경로는 para_shape/style id 도 reference 하므로 0번을 등록해 둔다.
        doc.doc_info.para_shapes = vec![Default::default()];
        doc.doc_info.styles = vec![Default::default()];
        let mut section: crate::model::document::Section = Default::default();
        section.paragraphs.push(p0);
        section.paragraphs.push(p1);
        doc.sections.push(section);
        doc
    }

    fn shapes_of(p: &Paragraph) -> Vec<(u32, u32)> {
        p.char_shapes
            .iter()
            .map(|r| (r.start_pos, r.char_shape_id))
            .collect()
    }

    #[test]
    fn serialize_parse_roundtrip_preserves_cell_char_shapes() {
        // 셀 다중 run 의 serialize → parse 왕복 보존 (#1378 3단계).
        let mut doc = roundtrip_doc_with_control(table_control(&[(0, 1), (2, 2)]));
        if let crate::model::control::Control::Table(t) =
            &mut doc.sections[0].paragraphs[1].controls[0]
        {
            let para = &mut t.cells[0].paragraphs[0];
            para.text = "abcd".to_string();
            para.char_offsets = vec![0, 1, 2, 3];
            para.char_count = 5;
        } else {
            panic!("Table 컨트롤이어야 함");
        }

        let bytes = serialize_hwpx(&doc).expect("serialize");
        let doc2 = parse_hwpx(&bytes).expect("parse");
        let cell_para = match &doc2.sections[0].paragraphs[1].controls[0] {
            crate::model::control::Control::Table(t) => &t.cells[0].paragraphs[0],
            other => panic!("Table 컨트롤이어야 함: {:?}", other),
        };
        assert_eq!(shapes_of(cell_para), vec![(0, 1), (2, 2)], "셀 문단");
    }

    #[test]
    fn task2784_table_affect_line_spacing_roundtrips() {
        // [#2784] 표 affectLSpacing="1"(줄 간격에 영향)이 HWPX serialize→parse 왕복에서
        // 보존되는지. 종전엔 방출측(table.rs write_pos)의 "0" 하드코딩 + 파서(section.rs
        // pos 루프)의 arm 부재로 1→0 드롭됐다. 방출과 파서 양쪽이 load-bearing 이므로
        // 어느 한쪽만 되돌려도 이 테스트가 red 가 된다(레드→그린 분리 검증 대상).
        let mut doc = roundtrip_doc_with_control(table_control(&[(0, 1)]));
        if let crate::model::control::Control::Table(t) =
            &mut doc.sections[0].paragraphs[1].controls[0]
        {
            t.common.affect_line_spacing = true;
        } else {
            panic!("Table 컨트롤이어야 함");
        }

        let bytes = serialize_hwpx(&doc).expect("serialize");
        let doc2 = parse_hwpx(&bytes).expect("parse");
        let preserved = match &doc2.sections[0].paragraphs[1].controls[0] {
            crate::model::control::Control::Table(t) => t.common.affect_line_spacing,
            other => panic!("Table 컨트롤이어야 함: {:?}", other),
        };
        assert!(preserved, "표 affectLSpacing 이 왕복 보존돼야 함");
    }

    #[test]
    fn serialize_parse_roundtrip_preserves_textbox_char_shapes() {
        // 글상자 다중 run 의 serialize → parse 왕복 보존 (#1378 3단계).
        let mut doc = roundtrip_doc_with_control(textbox_control(&[(0, 1), (2, 2)]));
        if let crate::model::control::Control::Shape(s) =
            &mut doc.sections[0].paragraphs[1].controls[0]
        {
            if let crate::model::shape::ShapeObject::Rectangle(r) = s.as_mut() {
                let para = &mut r.drawing.text_box.as_mut().unwrap().paragraphs[0];
                para.text = "abcd".to_string();
                para.char_offsets = vec![0, 1, 2, 3];
                para.char_count = 5;
            } else {
                panic!("Rectangle 이어야 함");
            }
        } else {
            panic!("Shape 컨트롤이어야 함");
        }

        let bytes = serialize_hwpx(&doc).expect("serialize");
        let doc2 = parse_hwpx(&bytes).expect("parse");
        let tb_para = match &doc2.sections[0].paragraphs[1].controls[0] {
            crate::model::control::Control::Shape(s) => match s.as_ref() {
                crate::model::shape::ShapeObject::Rectangle(r) => {
                    &r.drawing.text_box.as_ref().expect("text_box").paragraphs[0]
                }
                other => panic!("Rectangle 이어야 함: {:?}", other),
            },
            other => panic!("Shape 컨트롤이어야 함: {:?}", other),
        };
        assert_eq!(shapes_of(tb_para), vec![(0, 1), (2, 2)], "글상자 문단");
    }

    /// 셀 문단에 지정한 컨트롤을 가진 1x1 표 컨트롤 (#1379 게이트 테스트용).
    fn table_control_with_cell_controls(
        ctrls: Vec<crate::model::control::Control>,
    ) -> crate::model::control::Control {
        use crate::model::table::{Cell, Table};
        let mut cell_para = Paragraph::default();
        cell_para.controls = ctrls;
        let mut cell = Cell::default();
        cell.col_span = 1;
        cell.row_span = 1;
        cell.paragraphs.push(cell_para);
        let mut t = Table::default();
        t.row_count = 1;
        t.col_count = 1;
        t.cells.push(cell);
        t.rebuild_grid();
        crate::model::control::Control::Table(Box::new(t))
    }

    fn picture_control() -> crate::model::control::Control {
        crate::model::control::Control::Picture(Box::default())
    }

    /// 단일 ParagraphControls 차이의 path/expected/actual 을 단언.
    fn assert_single_controls_diff(diff: &IrDiff, path0: &str, exp: &str, act: &str) {
        assert_eq!(diff.differences.len(), 1, "차이 1건이어야 함: {:?}", diff);
        match &diff.differences[0] {
            IrDifference::ParagraphControls {
                path,
                expected,
                actual,
                ..
            } => {
                assert_eq!(path, path0);
                assert_eq!(expected, exp);
                assert_eq!(actual, act);
            }
            other => panic!("ParagraphControls 여야 함: {:?}", other),
        }
    }

    #[test]
    fn diff_documents_detects_body_control_loss() {
        // 본문 문단의 인라인 슬롯 컨트롤 소실 검출 (#1379).
        let a = doc_with_control(picture_control());
        let mut b = Document::default();
        let mut section: crate::model::document::Section = Default::default();
        section.paragraphs.push(Paragraph::default());
        b.sections.push(section);
        assert_single_controls_diff(&diff_documents(&a, &b), "", "[pic]", "[]");
    }

    #[test]
    fn diff_documents_detects_cell_control_loss() {
        // 셀 내부 문단의 컨트롤 소실 검출 (#1379) — subList 컨트롤 미출력 양상.
        let a = doc_with_control(table_control_with_cell_controls(vec![picture_control()]));
        let b = doc_with_control(table_control_with_cell_controls(vec![]));
        assert_single_controls_diff(
            &diff_documents(&a, &b),
            "/ctrl[0]tbl.cell[0].p[0]",
            "[pic]",
            "[]",
        );
    }

    #[test]
    fn diff_documents_detects_control_type_change() {
        // 수는 같아도 타입이 다르면 검출.
        let a = doc_with_control(table_control_with_cell_controls(vec![picture_control()]));
        let b = doc_with_control(table_control_with_cell_controls(vec![
            crate::model::control::Control::Equation(Box::default()),
        ]));
        assert_single_controls_diff(
            &diff_documents(&a, &b),
            "/ctrl[0]tbl.cell[0].p[0]",
            "[pic]",
            "[eq]",
        );
    }

    #[test]
    fn diff_documents_bookmark_not_compared_as_control() {
        // Bookmark 는 비슬롯 — serializer 가 문단 선두로 재배치하므로 비교 제외.
        let mut a = doc_with_control(crate::model::control::Control::Bookmark(
            crate::model::control::Bookmark {
                name: "b".to_string(),
            },
        ));
        a.sections[0].paragraphs[0].controls.push(picture_control());
        let b = doc_with_control(picture_control());
        assert!(diff_documents(&a, &b).is_empty());
    }

    #[test]
    fn issue4388_diff_documents_hyperlink_not_compared_as_control() {
        // [#4388 후속] Hyperlink 도 Bookmark 와 동형으로 비교 제외해야 한다.
        // is_hwpx_inline_slot 에 한때 등록했다가 되돌린 회귀 가드 — 등록하면
        // `roundtrip::diff_documents`(포맷 비종속, `convert`(HWP5 대상) `--verify` 도
        // 재사용)가 HWP5 직렬화기의 기존(이슈 범위 밖) Hyperlink ctrl_id=0 고정 손실을
        // 새로 "검출"해, hwp3-sample16.hwp 를 쓰는
        // `tests/issue_hwp3_bookmark_native.rs::bookmarks_survive_saving_to_hwp5` 처럼
        // 하이퍼링크와 무관한 기존 테스트가 깨진다(실측 확인됨). Hyperlink 가
        // 사라져도 diff 가 비어 있어야 한다 — HWPX 직렬화기 자체의 드롭 경고는
        // `warn_if_unrepresentable_in_hwpx` 가 별도로 담당(section.rs).
        use crate::model::control::{Control, Hyperlink};

        let mut a = doc_with_control(Control::Hyperlink(Hyperlink {
            url: "http://example.com".to_string(),
            text: "example".to_string(),
        }));
        a.sections[0].paragraphs[0].controls.push(picture_control());
        let b = doc_with_control(picture_control());
        assert!(
            diff_documents(&a, &b).is_empty(),
            "Hyperlink 손실은 diff_documents 비교에서 제외되어야 함(is_hwpx_inline_slot 미등록)"
        );
    }

    #[test]
    fn issue4388_diff_documents_unknown_not_compared_as_control() {
        // [#4388 후속] Unknown 도 동일 이유로 비교 제외.
        use crate::model::control::{Control, UnknownControl};

        let mut a = doc_with_control(Control::Unknown(UnknownControl {
            ctrl_id: 0x1234_5678,
        }));
        a.sections[0].paragraphs[0].controls.push(picture_control());
        let b = doc_with_control(picture_control());
        assert!(
            diff_documents(&a, &b).is_empty(),
            "Unknown 손실은 diff_documents 비교에서 제외되어야 함(is_hwpx_inline_slot 미등록)"
        );
    }

    #[test]
    fn diff_documents_same_cell_controls_is_empty() {
        let a = doc_with_control(table_control_with_cell_controls(vec![picture_control()]));
        let b = doc_with_control(table_control_with_cell_controls(vec![picture_control()]));
        assert!(diff_documents(&a, &b).is_empty());
    }

    #[test]
    fn diff_documents_detects_section_count() {
        let a = Document::default();
        let mut b = Document::default();
        b.sections.push(Default::default());
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1);
        assert!(matches!(
            diff.differences[0],
            IrDifference::SectionCount {
                expected: 0,
                actual: 1
            }
        ));
    }

    // ---------- #1380: diff_linesegs (게이트 동승 + 배치 TSV 측정) ----------

    use crate::model::paragraph::LineSeg;

    /// 지정 lineseg 들을 가진 단일 문단 Document 생성.
    fn doc_with_linesegs(segs: Vec<LineSeg>) -> Document {
        let mut para = Paragraph::default();
        para.line_segs = segs;
        let mut doc = Document::default();
        let mut section: crate::model::document::Section = Default::default();
        section.paragraphs.push(para);
        doc.sections.push(section);
        doc
    }

    fn seg(vertical_pos: i32, line_height: i32) -> LineSeg {
        LineSeg {
            vertical_pos,
            line_height,
            text_height: 1000,
            baseline_distance: 850,
            line_spacing: 600,
            segment_width: 42520,
            tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
            ..Default::default()
        }
    }

    #[test]
    fn diff_linesegs_equal_is_empty() {
        let a = doc_with_linesegs(vec![seg(0, 1200), seg(1200, 1200)]);
        let b = doc_with_linesegs(vec![seg(0, 1200), seg(1200, 1200)]);
        assert!(diff_linesegs(&a, &b).is_empty());
    }

    #[test]
    fn diff_linesegs_detects_value_mismatch() {
        let a = doc_with_linesegs(vec![seg(0, 21974)]);
        let b = doc_with_linesegs(vec![seg(0, 19924)]);
        let diffs = diff_linesegs(&a, &b);
        assert_eq!(diffs.len(), 1, "{diffs:?}");
        match &diffs[0].kind {
            LinesegDiffKind::ValueMismatch {
                index,
                field,
                expected,
                actual,
            } => {
                assert_eq!(*index, 0);
                assert_eq!(*field, "vertsize");
                assert_eq!(*expected, 21974);
                assert_eq!(*actual, 19924);
            }
            other => panic!("ValueMismatch 여야 함: {other:?}"),
        }
        assert_eq!(diffs[0].path, "");
    }

    #[test]
    fn diff_linesegs_detects_count_mismatch_and_compares_common() {
        // 개수 불일치 + 공통 구간(min) 값 비교 계속.
        let a = doc_with_linesegs(vec![seg(0, 1200), seg(1200, 1200)]);
        let b = doc_with_linesegs(vec![seg(0, 1000)]);
        let diffs = diff_linesegs(&a, &b);
        assert!(
            diffs.iter().any(|d| matches!(
                d.kind,
                LinesegDiffKind::CountMismatch {
                    expected: 2,
                    actual: 1
                }
            )),
            "{diffs:?}"
        );
        assert!(
            diffs.iter().any(|d| matches!(
                d.kind,
                LinesegDiffKind::ValueMismatch {
                    index: 0,
                    field: "vertsize",
                    ..
                }
            )),
            "{diffs:?}"
        );
    }

    #[test]
    fn diff_linesegs_recurses_into_cell() {
        // 셀 내부 문단의 lineseg 차이를 path 와 함께 검출.
        let make = |lh: i32| {
            let mut doc = doc_with_control(table_control(&[(0, 1)]));
            if let crate::model::control::Control::Table(t) =
                &mut doc.sections[0].paragraphs[0].controls[0]
            {
                t.cells[0].paragraphs[0].line_segs = vec![seg(0, lh)];
            }
            doc
        };
        let a = make(1200);
        let b = make(1000);
        let diffs = diff_linesegs(&a, &b);
        assert_eq!(diffs.len(), 1, "{diffs:?}");
        assert_eq!(diffs[0].path, "/ctrl[0]tbl.cell[0].p[0]");
        assert!(matches!(
            diffs[0].kind,
            LinesegDiffKind::ValueMismatch {
                field: "vertsize",
                ..
            }
        ));
    }

    #[test]
    fn task1380_lineseg_in_gate() {
        // lineseg 값 차이는 diff_documents(게이트)에서 검출되어야 한다 (3단계 동승).
        let a = doc_with_linesegs(vec![seg(0, 21974)]);
        let b = doc_with_linesegs(vec![seg(0, 19924)]);
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::ParagraphLinesegs {
                section,
                paragraph,
                path,
                detail,
            } => {
                assert_eq!(*section, 0);
                assert_eq!(*paragraph, 0);
                assert_eq!(path, "");
                assert_eq!(detail, "[0].vertsize: expected=21974 actual=19924");
            }
            other => panic!("ParagraphLinesegs 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1380_gate_detects_synthetic_lineseg_asymmetry() {
        // #1380 결함 본체였던 원본 무 → RT 유 합성 비대칭(종전 파서 주입/serializer
        // fallback 패턴)을 게이트가 개수 불일치로 검출하는지 고정.
        let a = doc_with_linesegs(vec![]);
        let b = doc_with_linesegs(vec![seg(0, 1000)]);
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::ParagraphLinesegs { detail, .. } => {
                assert_eq!(detail, "count: expected=0 actual=1");
            }
            other => panic!("ParagraphLinesegs 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1380_two_round_stable_with_empty_linesegs() {
        // linesegarray 부재 문단(38건)을 실제로 가진 H1 샘플의 2-round 안정성
        // (구현계획서 3.3): round1·round2 모두 게이트(IrDiff, lineseg 동승) 0 —
        // 빈 line_segs 가 어느 라운드에서도 합성(주입)되거나 소실되지 않는다.
        let bytes = std::fs::read("samples/hwpx/business_overview.hwpx").expect("샘플 읽기");
        let doc1 = parse_hwpx(&bytes).expect("parse 원본");
        assert!(
            doc1.sections
                .iter()
                .flat_map(|s| &s.paragraphs)
                .any(|p| p.line_segs.is_empty()),
            "픽스처 전제: linesegarray 부재(빈 line_segs) 문단이 있어야 한다"
        );

        let out1 = serialize_hwpx(&doc1).expect("serialize r1");
        let doc2 = parse_hwpx(&out1).expect("parse r1");
        let d1 = diff_documents(&doc1, &doc2);
        assert!(d1.is_empty(), "round1: {:?}", d1.differences);

        let out2 = serialize_hwpx(&doc2).expect("serialize r2");
        let doc3 = parse_hwpx(&out2).expect("parse r2");
        let d2 = diff_documents(&doc2, &doc3);
        assert!(d2.is_empty(), "round2: {:?}", d2.differences);
    }

    // ---------- #1387: diff_table_caption (게이트 동승) ----------

    fn caption_with_paras(n: usize) -> crate::model::shape::Caption {
        let mut c = crate::model::shape::Caption::default();
        for _ in 0..n {
            c.paragraphs.push(Paragraph::default());
        }
        c
    }

    fn table_with_caption(
        cap: Option<crate::model::shape::Caption>,
    ) -> crate::model::control::Control {
        match table_control(&[]) {
            crate::model::control::Control::Table(mut t) => {
                t.caption = cap;
                crate::model::control::Control::Table(t)
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn task1387_caption_loss_in_gate() {
        // #1387 결함 본체였던 캡션 소실(원본 유 → RT 무)을 게이트가 검출하는지 고정.
        let a = doc_with_control(table_with_caption(Some(caption_with_paras(1))));
        let b = doc_with_control(table_with_caption(None));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::TableCaption { path, detail, .. } => {
                assert_eq!(path, "/ctrl[0]tbl.caption");
                assert_eq!(detail, "missing: expected=Some actual=None");
            }
            other => panic!("TableCaption 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1387_caption_attr_mismatch_in_gate() {
        let mut ca = caption_with_paras(1);
        ca.spacing = 850;
        let mut cb = caption_with_paras(1);
        cb.spacing = 0;
        cb.direction = crate::model::shape::CaptionDirection::Top;
        let a = doc_with_control(table_with_caption(Some(ca)));
        let b = doc_with_control(table_with_caption(Some(cb)));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::TableCaption { detail, .. } => {
                assert_eq!(
                    detail,
                    "side: expected=Bottom actual=Top; gap: expected=850 actual=0"
                );
            }
            other => panic!("TableCaption 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1387_caption_paragraph_recursed_in_gate() {
        // 캡션 내부 문단의 char_shapes 차이가 `tbl.caption.p[k]` 경로로 검출.
        let mut ca = caption_with_paras(1);
        ca.paragraphs[0].char_shapes = to_refs(&[(0, 6)]);
        let mut cb = caption_with_paras(1);
        cb.paragraphs[0].char_shapes = to_refs(&[(0, 7)]);
        let a = doc_with_control(table_with_caption(Some(ca)));
        let b = doc_with_control(table_with_caption(Some(cb)));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::ParagraphCharShapes { path, .. } => {
                assert_eq!(path, "/ctrl[0]tbl.caption.p[0]");
            }
            other => panic!("ParagraphCharShapes 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1387_ta_pic_001_r_roundtrip_caption_gate_zero() {
        // 캡션 보유 실샘플의 roundtrip 게이트 0 — 2단계 serializer 수정 + 캡션
        // 동승 후 기대치 (autoNum #1382 변위는 텍스트 축 — 게이트 비교 항목 밖).
        let bytes = std::fs::read("samples/hwpx/ta-pic-001-r.hwpx").expect("샘플 읽기");
        let doc1 = parse_hwpx(&bytes).expect("parse 원본");
        let out = serialize_hwpx(&doc1).expect("serialize");
        let doc2 = parse_hwpx(&out).expect("reparse");
        let diff = diff_documents(&doc1, &doc2);
        assert!(diff.is_empty(), "{:?}", diff.differences);
    }

    // ---------- #1388: diff_page_def (게이트 동승) ----------

    fn doc_with_page_def(pd: crate::model::page::PageDef) -> Document {
        let mut doc = Document::default();
        let mut section = crate::model::document::Section::default();
        section.section_def.page_def = pd;
        doc.sections.push(section);
        doc
    }

    #[test]
    fn task1388_page_def_in_gate() {
        // 여백·제본 차이는 diff_documents(게이트)에서 검출되어야 한다.
        // 값은 온새미로 sec0 실측: 원본 left=7086 right=14173 LEFT_RIGHT →
        // 종전 RT 템플릿 고정값 left=8504 right=8504 LEFT_ONLY.
        let mut a_pd = crate::model::page::PageDef::default();
        a_pd.margin_left = 7086;
        a_pd.margin_right = 14173;
        a_pd.binding = crate::model::page::BindingMethod::DuplexSided;
        let mut b_pd = a_pd.clone();
        b_pd.margin_left = 8504;
        b_pd.margin_right = 8504;
        b_pd.binding = crate::model::page::BindingMethod::SingleSided;

        let diff = diff_documents(&doc_with_page_def(a_pd), &doc_with_page_def(b_pd));
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::SectionPageDef { section, detail } => {
                assert_eq!(*section, 0);
                assert_eq!(
                    detail,
                    "margin_left: expected=7086 actual=8504; \
                     margin_right: expected=14173 actual=8504; \
                     binding: expected=DuplexSided actual=SingleSided"
                );
            }
            other => panic!("SectionPageDef 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1388_page_def_equal_is_empty() {
        // 동일 PageDef 는 차이 0 — attr/pagination_bottom_tolerance 는 비교 제외.
        let mut a_pd = crate::model::page::PageDef::default();
        a_pd.margin_left = 7086;
        let mut b_pd = a_pd.clone();
        b_pd.attr = 0xFF;
        b_pd.pagination_bottom_tolerance = 100;
        let diff = diff_documents(&doc_with_page_def(a_pd), &doc_with_page_def(b_pd));
        assert!(diff.is_empty(), "{:?}", diff.differences);
    }

    #[test]
    fn task1388_roundtrip_preserves_page_def() {
        // 비템플릿 여백(left/right=4252)을 가진 실샘플의 roundtrip 에서
        // PageDef 차이 0 — 2단계 serializer 수정의 게이트 검증.
        let bytes = std::fs::read("samples/hwpx/ta-pic-001-r.hwpx").expect("샘플 읽기");
        let doc1 = parse_hwpx(&bytes).expect("parse 원본");
        let pd = &doc1.sections[0].section_def.page_def;
        assert!(
            pd.margin_left != 8504 || pd.margin_right != 8504,
            "픽스처 전제: 템플릿 고정값과 다른 여백이어야 한다 (left={} right={})",
            pd.margin_left,
            pd.margin_right
        );

        let out = serialize_hwpx(&doc1).expect("serialize");
        let doc2 = parse_hwpx(&out).expect("reparse");
        let diff = diff_documents(&doc1, &doc2);
        assert!(diff.is_empty(), "{:?}", diff.differences);
    }

    // ---------- #1637: secPr visibility (hideFirstEmptyLine 등 게이트 동승) ----------

    fn doc_with_visibility(hide_empty_line: bool, hide_header: bool) -> Document {
        let mut doc = Document::default();
        let mut section = crate::model::document::Section::default();
        section.section_def.hide_empty_line = hide_empty_line;
        section.section_def.hide_header = hide_header;
        doc.sections.push(section);
        doc
    }

    #[test]
    fn task1637_visibility_in_gate() {
        // hideFirstEmptyLine 등 visibility 차이는 diff_documents(게이트)에서 검출되어야 한다.
        let a = doc_with_visibility(true, false);
        let b = doc_with_visibility(false, false);
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::SectionVisibility { section, detail } => {
                assert_eq!(*section, 0);
                assert_eq!(detail, "hide_empty_line: expected=true actual=false");
            }
            other => panic!("SectionVisibility 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1637_visibility_equal_is_empty() {
        // 동일 visibility 는 차이 0.
        let diff = diff_documents(
            &doc_with_visibility(true, true),
            &doc_with_visibility(true, true),
        );
        assert!(diff.is_empty(), "{:?}", diff.differences);
    }

    #[test]
    fn task1637_roundtrip_preserves_hide_empty_line() {
        // hideFirstEmptyLine="1" 문서의 roundtrip 에서 값 보존 + 게이트 0 (직렬화기
        // visibility IR 치환 검증). 종전엔 템플릿 고정값 "0" 으로 드롭되어 페이지네이션 변동.
        // serialize_hwpx 는 HWPX 패키지(ZIP)를 반환하므로 reparse 로 값 보존을 검증한다.
        let doc = doc_with_visibility(true, true);
        let out = serialize_hwpx(&doc).expect("serialize");
        let doc2 = parse_hwpx(&out).expect("reparse");
        assert!(
            doc2.sections[0].section_def.hide_empty_line,
            "hide_empty_line=1 이 roundtrip 에서 보존되어야 한다"
        );
        assert!(
            doc2.sections[0].section_def.hide_header,
            "hide_header=1 이 roundtrip 에서 보존되어야 한다"
        );
        // visibility 축의 게이트 0 (다른 축의 near-empty-doc 직렬화 산물은 본 테스트 범위 밖).
        assert!(
            diff_visibility(&doc.sections[0].section_def, &doc2.sections[0].section_def).is_none(),
            "visibility roundtrip 차이가 없어야 한다"
        );
    }

    #[test]
    fn task1637_table_flow_with_text_in_gate() {
        // 표 flowWithText 차이는 diff_documents(게이트)에서 ObjectFlowWithText 로 검출.
        use crate::model::table::Table;
        let mut ta = Table::default();
        ta.common.flow_with_text = false;
        let mut tb = Table::default();
        tb.common.flow_with_text = true;
        let a = doc_with_control(crate::model::control::Control::Table(Box::new(ta)));
        let b = doc_with_control(crate::model::control::Control::Table(Box::new(tb)));
        let diff = diff_documents(&a, &b);
        assert!(
            diff.differences
                .iter()
                .any(|d| matches!(d, IrDifference::ObjectFlowWithText { .. })),
            "표 flowWithText 차이는 게이트에서 검출되어야 한다: {:?}",
            diff.differences
        );
    }

    #[test]
    fn task1655_equation_flow_with_text_in_gate() {
        // 수식 flowWithText 차이도 diff_documents(게이트)에서 ObjectFlowWithText 로 검출.
        let mut ea = crate::model::control::Equation::default();
        ea.common.flow_with_text = false;
        let mut eb = crate::model::control::Equation::default();
        eb.common.flow_with_text = true;
        let a = doc_with_control(crate::model::control::Control::Equation(Box::new(ea)));
        let b = doc_with_control(crate::model::control::Control::Equation(Box::new(eb)));
        let diff = diff_documents(&a, &b);
        assert!(
            diff.differences
                .iter()
                .any(|d| matches!(d, IrDifference::ObjectFlowWithText { .. })),
            "수식 flowWithText 차이는 게이트에서 검출되어야 한다: {:?}",
            diff.differences
        );
    }

    // ---------- #1403: 그림/도형/묶음 캡션 (게이트 동승) ----------

    #[test]
    fn task1403_pic_caption_lineseg_recursed_in_gate() {
        // #1403 후속 — 객체 캡션 내부 문단의 lineseg 차이가 char_shapes 와 대칭으로
        // `pic.caption.p[k]` 경로에서 검출되는지 고정 (merge 시 보완 1건).
        let mut ca = caption_with_paras(1);
        ca.paragraphs[0].line_segs = vec![seg(0, 1000)];
        let mut cb = caption_with_paras(1);
        cb.paragraphs[0].line_segs = vec![seg(0, 2000)];
        let mut pa = crate::model::image::Picture::default();
        pa.caption = Some(ca);
        let mut pb = crate::model::image::Picture::default();
        pb.caption = Some(cb);
        let a = doc_with_control(crate::model::control::Control::Picture(Box::new(pa)));
        let b = doc_with_control(crate::model::control::Control::Picture(Box::new(pb)));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::ParagraphLinesegs { path, detail, .. } => {
                assert_eq!(path, "/ctrl[0]pic.caption.p[0]");
                assert_eq!(detail, "[0].vertsize: expected=1000 actual=2000");
            }
            other => panic!("ParagraphLinesegs 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1403_shape_caption_lineseg_recursed_in_gate() {
        // 도형(drawing.caption) 경로의 lineseg 재귀 — `shape.caption.p[k]`.
        let mk = |vs: i32| {
            let mut cap = caption_with_paras(1);
            cap.paragraphs[0].line_segs = vec![seg(0, vs)];
            let mut el = crate::model::shape::EllipseShape::default();
            el.drawing.caption = Some(cap);
            doc_with_control(crate::model::control::Control::Shape(Box::new(
                crate::model::shape::ShapeObject::Ellipse(el),
            )))
        };
        let diff = diff_documents(&mk(1000), &mk(2000));
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::ParagraphLinesegs { path, .. } => {
                assert_eq!(path, "/ctrl[0]shape.caption.p[0]");
            }
            other => panic!("ParagraphLinesegs 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1403_pic_caption_loss_in_gate() {
        // #1403 결함 본체였던 그림 캡션 소실(원본 유 → RT 무)을 게이트가 검출하는지 고정.
        let mut pa = crate::model::image::Picture::default();
        pa.caption = Some(caption_with_paras(1));
        let pb = crate::model::image::Picture::default();
        let a = doc_with_control(crate::model::control::Control::Picture(Box::new(pa)));
        let b = doc_with_control(crate::model::control::Control::Picture(Box::new(pb)));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::ObjectCaption { path, detail, .. } => {
                assert_eq!(path, "/ctrl[0]pic.caption");
                assert_eq!(detail, "missing: expected=Some actual=None");
            }
            other => panic!("ObjectCaption 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1403_line_caption_loss_in_gate() {
        // 그리기 도형(drawing.caption) 경로 — line 캡션 소실 검출.
        let mut la = crate::model::shape::LineShape::default();
        la.drawing.caption = Some(caption_with_paras(1));
        let lb = crate::model::shape::LineShape::default();
        let a = doc_with_control(crate::model::control::Control::Shape(Box::new(
            crate::model::shape::ShapeObject::Line(la),
        )));
        let b = doc_with_control(crate::model::control::Control::Shape(Box::new(
            crate::model::shape::ShapeObject::Line(lb),
        )));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::ObjectCaption { path, detail, .. } => {
                assert_eq!(path, "/ctrl[0]shape.caption");
                assert_eq!(detail, "missing: expected=Some actual=None");
            }
            other => panic!("ObjectCaption 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1403_legacy_shape_caption_roundtrips() {
        // legacy 문자열 경로(ellipse/arc/polygon/curve/chart/ole)의 캡션 방출 검증 —
        // HWP5 파서는 모든 도형 캡션을 적재하므로(parser/control/shape.rs) 미방출 시
        // HWP5→HWPX 변환에서 소실된다. serialize→reparse 후 게이트 차이 0 이어야 한다.
        let mut cap = caption_with_paras(1);
        cap.width = 8504;
        cap.paragraphs[0].text = "타원 캡션".to_string();
        // 빈 char_shapes 는 reparse 시 [(0,0)] 으로 돌아오므로(픽스처 노이즈) 명시한다.
        cap.paragraphs[0].char_shapes = to_refs(&[(0, 0)]);
        let mut el = crate::model::shape::EllipseShape::default();
        el.drawing.caption = Some(cap);
        let mut a = roundtrip_doc_with_control(crate::model::control::Control::Shape(Box::new(
            crate::model::shape::ShapeObject::Ellipse(el),
        )));
        a.sections[0].paragraphs[0].char_shapes = to_refs(&[(0, 0)]);
        let out = serialize_hwpx(&a).expect("serialize");
        let b = parse_hwpx(&out).expect("reparse");
        let diff = diff_documents(&a, &b);
        assert!(diff.is_empty(), "{:?}", diff.differences);
        // 텍스트 보존 직접 확인
        match &b.sections[0].paragraphs[1].controls[0] {
            crate::model::control::Control::Shape(s) => match s.as_ref() {
                crate::model::shape::ShapeObject::Ellipse(e2) => {
                    let c2 = e2.drawing.caption.as_ref().expect("캡션 보존");
                    assert_eq!(c2.paragraphs[0].text, "타원 캡션");
                }
                other => panic!("Ellipse 여야 함: {other:?}"),
            },
            other => panic!("Shape 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1403_group_caption_loss_in_gate() {
        // 묶음 개체(GroupShape.caption) 경로 — container 캡션 소실 검출.
        let mut ga = crate::model::shape::GroupShape::default();
        ga.caption = Some(caption_with_paras(1));
        let gb = crate::model::shape::GroupShape::default();
        let a = doc_with_control(crate::model::control::Control::Shape(Box::new(
            crate::model::shape::ShapeObject::Group(ga),
        )));
        let b = doc_with_control(crate::model::control::Control::Shape(Box::new(
            crate::model::shape::ShapeObject::Group(gb),
        )));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::ObjectCaption { path, detail, .. } => {
                assert_eq!(path, "/ctrl[0]shape.caption");
                assert_eq!(detail, "missing: expected=Some actual=None");
            }
            other => panic!("ObjectCaption 여야 함: {other:?}"),
        }
    }

    // ---------- #4319: 차트·OLE 캡션 (게이트 동승) ----------
    //
    // #1403 은 pic/line/group 캡션 소실 검출을 고정했지만 Chart/Ole 는 빠졌다.
    // shape_caption() 자체는 이미 `Chart(x) => &x.caption, Ole(x) => &x.caption`
    // 로 올바른 필드를 보므로(비교기는 문제 없음), 아래 두 테스트는 그 사실을
    // 고정한다. 진짜 결함은 HWPX 파서가 `<hp:chart>`/`<hp:ole>` 의 `<hp:caption>`
    // 을 애초에 파싱하지 않아 `x.caption` 이 원본 파싱 시점부터 항상 None 이었다는
    // 것 — 그러면 저장 전/후 IR 비교(diff_documents)는 None==None 이라 손실이
    // 보이지 않는다(이 파일의 게이트가 비교하는 두 IR 모두 같은 파서를 거치므로).
    // 아래 issue4319_*_caption_roundtrips 는 실제 파서·직렬화기를 왕복시켜
    // 그 손실 자체(및 재발 방지 수정)를 고정한다.

    #[test]
    fn issue4319_ole_caption_loss_in_gate() {
        // OLE 개체(OleShape.caption) 경로 — #1403 에 빠졌던 변형을 채운다.
        let mut oa = crate::model::shape::OleShape::default();
        oa.caption = Some(caption_with_paras(1));
        let ob = crate::model::shape::OleShape::default();
        let a = doc_with_control(crate::model::control::Control::Shape(Box::new(
            crate::model::shape::ShapeObject::Ole(Box::new(oa)),
        )));
        let b = doc_with_control(crate::model::control::Control::Shape(Box::new(
            crate::model::shape::ShapeObject::Ole(Box::new(ob)),
        )));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::ObjectCaption { path, detail, .. } => {
                assert_eq!(path, "/ctrl[0]shape.caption");
                assert_eq!(detail, "missing: expected=Some actual=None");
            }
            other => panic!("ObjectCaption 여야 함: {other:?}"),
        }
    }

    #[test]
    fn issue4319_chart_caption_loss_in_gate() {
        // HWPX 차트는 OleShape(chart_id_ref=Some) 로 모델링된다 — chart_id_ref 유무와
        // 무관하게 같은 shape_caption() 분기(Ole)를 타는지 고정.
        let mut oa = crate::model::shape::OleShape::default();
        oa.chart_id_ref = Some("Chart/chart1.xml".to_string());
        oa.caption = Some(caption_with_paras(1));
        let mut ob = crate::model::shape::OleShape::default();
        ob.chart_id_ref = Some("Chart/chart1.xml".to_string());
        let a = doc_with_control(crate::model::control::Control::Shape(Box::new(
            crate::model::shape::ShapeObject::Ole(Box::new(oa)),
        )));
        let b = doc_with_control(crate::model::control::Control::Shape(Box::new(
            crate::model::shape::ShapeObject::Ole(Box::new(ob)),
        )));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::ObjectCaption { path, detail, .. } => {
                assert_eq!(path, "/ctrl[0]shape.caption");
                assert_eq!(detail, "missing: expected=Some actual=None");
            }
            other => panic!("ObjectCaption 여야 함: {other:?}"),
        }
    }

    #[test]
    fn issue4319_ole_caption_roundtrips() {
        // 실제 파서·직렬화기 왕복(serialize_hwpx → parse_hwpx) — 종전엔
        // parse_hp_ole_element 에 caption arm 이 없어 재파싱 후 캡션이 사라졌다
        // (write_ole 자체는 이미 캡션을 써 왔다 — 파서만 못 읽었다).
        let mut cap = caption_with_paras(1);
        cap.paragraphs[0].text = "OLE 캡션".to_string();
        cap.paragraphs[0].char_shapes = to_refs(&[(0, 0)]);
        let mut ole = crate::model::shape::OleShape::default();
        ole.caption = Some(cap);
        let mut a = roundtrip_doc_with_control(crate::model::control::Control::Shape(Box::new(
            crate::model::shape::ShapeObject::Ole(Box::new(ole)),
        )));
        a.sections[0].paragraphs[0].char_shapes = to_refs(&[(0, 0)]);
        let out = serialize_hwpx(&a).expect("serialize");
        let b = parse_hwpx(&out).expect("reparse");
        let diff = diff_documents(&a, &b);
        assert!(diff.is_empty(), "{:?}", diff.differences);
        match &b.sections[0].paragraphs[1].controls[0] {
            crate::model::control::Control::Shape(s) => match s.as_ref() {
                crate::model::shape::ShapeObject::Ole(o2) => {
                    let c2 = o2.caption.as_ref().expect("캡션 보존 (#4319)");
                    assert_eq!(c2.paragraphs[0].text, "OLE 캡션");
                }
                other => panic!("Ole 여야 함: {other:?}"),
            },
            other => panic!("Shape 여야 함: {other:?}"),
        }
    }

    #[test]
    fn issue4319_chart_caption_roundtrips() {
        // hp:chart 재방출 경로(write_chart_element/parse_hp_chart_element) 왕복 —
        // 파서 수정만으로는 부족하다: write_chart_element 는 종전 write_caption 호출이
        // 없어 파서를 고쳐도 저장 시 다시 유실됐다(hp:ole 방출 경로와 달리 hp:chart
        // 재방출 경로만 캡션을 안 썼다). 두 수정이 함께 있어야 왕복이 무손실이다.
        let mut cap = caption_with_paras(1);
        cap.paragraphs[0].text = "차트 캡션".to_string();
        cap.paragraphs[0].char_shapes = to_refs(&[(0, 0)]);
        let mut ole = crate::model::shape::OleShape::default();
        ole.chart_id_ref = Some("Chart/chart1.xml".to_string());
        ole.bin_data_id = 60001;
        ole.caption = Some(cap);
        let mut a = roundtrip_doc_with_control(crate::model::control::Control::Shape(Box::new(
            crate::model::shape::ShapeObject::Ole(Box::new(ole)),
        )));
        a.sections[0].paragraphs[0].char_shapes = to_refs(&[(0, 0)]);
        let out = serialize_hwpx(&a).expect("serialize");
        let b = parse_hwpx(&out).expect("reparse");
        let diff = diff_documents(&a, &b);
        assert!(diff.is_empty(), "{:?}", diff.differences);
        match &b.sections[0].paragraphs[1].controls[0] {
            crate::model::control::Control::Shape(s) => match s.as_ref() {
                crate::model::shape::ShapeObject::Ole(o2) => {
                    let c2 = o2.caption.as_ref().expect("캡션 보존 (#4319)");
                    assert_eq!(c2.paragraphs[0].text, "차트 캡션");
                }
                other => panic!("Ole(chart) 여야 함: {other:?}"),
            },
            other => panic!("Shape 여야 함: {other:?}"),
        }
    }

    // ---------- #1392: shapeComment(객체 설명) 게이트 동승 ----------

    #[test]
    fn task1392_pic_comment_loss_in_gate() {
        let mut pa = crate::model::image::Picture::default();
        pa.common.description = "그림입니다.".to_string();
        let pb = crate::model::image::Picture::default();
        let a = doc_with_control(crate::model::control::Control::Picture(Box::new(pa)));
        let b = doc_with_control(crate::model::control::Control::Picture(Box::new(pb)));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::ObjectComment { path, detail, .. } => {
                assert_eq!(path, "/ctrl[0]pic");
                assert_eq!(detail, "expected=\"그림입니다.\" actual=\"\"");
            }
            other => panic!("ObjectComment 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1392_equation_comment_loss_in_gate() {
        let mut ea = crate::model::control::Equation::default();
        ea.common.description = "수식 설명".to_string();
        let eb = crate::model::control::Equation::default();
        let a = doc_with_control(crate::model::control::Control::Equation(Box::new(ea)));
        let b = doc_with_control(crate::model::control::Control::Equation(Box::new(eb)));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::ObjectComment { path, .. } => assert_eq!(path, "/ctrl[0]eq"),
            other => panic!("ObjectComment 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1392_shape_comment_loss_in_gate() {
        let mut el = crate::model::shape::EllipseShape::default();
        el.common.description = "타원 설명".to_string();
        let a = doc_with_control(crate::model::control::Control::Shape(Box::new(
            crate::model::shape::ShapeObject::Ellipse(el),
        )));
        let b = doc_with_control(crate::model::control::Control::Shape(Box::new(
            crate::model::shape::ShapeObject::Ellipse(crate::model::shape::EllipseShape::default()),
        )));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::ObjectComment { path, .. } => assert_eq!(path, "/ctrl[0]shape"),
            other => panic!("ObjectComment 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1392_equal_comment_no_diff() {
        let mut pa = crate::model::image::Picture::default();
        pa.common.description = "동일".to_string();
        let mut pb = crate::model::image::Picture::default();
        pb.common.description = "동일".to_string();
        let a = doc_with_control(crate::model::control::Control::Picture(Box::new(pa)));
        let b = doc_with_control(crate::model::control::Control::Picture(Box::new(pb)));
        assert!(diff_documents(&a, &b).is_empty());
    }

    #[test]
    fn task1451_legacy_shape_comment_serialize_roundtrip() {
        // #1451: render_common_shape_xml 경유 도형(polygon 등)의 shapeComment 가
        // serialize → parse 왕복에서 보존되는지 직접 가드한다.
        // 기존 task1392 게이트는 IR diff 검출만 하므로, 여기서 "보존 성공" 방향을 가드한다.
        let mut poly = crate::model::shape::PolygonShape::default();
        poly.common.description = "다각형입니다.".to_string();
        let doc = roundtrip_doc_with_control(crate::model::control::Control::Shape(Box::new(
            crate::model::shape::ShapeObject::Polygon(poly),
        )));

        let bytes = serialize_hwpx(&doc).expect("serialize");
        let doc2 = parse_hwpx(&bytes).expect("parse");
        let desc = match &doc2.sections[0].paragraphs[1].controls[0] {
            crate::model::control::Control::Shape(s) => match s.as_ref() {
                crate::model::shape::ShapeObject::Polygon(p) => &p.common.description,
                other => panic!("Polygon 이어야 함: {other:?}"),
            },
            other => panic!("Shape 컨트롤이어야 함: {other:?}"),
        };
        assert_eq!(desc, "다각형입니다.", "polygon shapeComment 왕복 보존");
    }

    // ---------- #1391: 필드 parameters / MEMO 본문 게이트 동승 ----------

    #[test]
    fn task1391_field_parameters_loss_in_gate() {
        let mut fa = crate::model::control::Field::default();
        fa.raw_parameters_xml = Some("<hp:parameters cnt=\"1\"></hp:parameters>".into());
        let fb = crate::model::control::Field::default();
        let a = doc_with_control(crate::model::control::Control::Field(fa));
        let b = doc_with_control(crate::model::control::Control::Field(fb));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::FieldContent { path, detail, .. } => {
                assert_eq!(path, "/ctrl[0]field");
                assert!(detail.starts_with("parameters: expected="), "{detail}");
            }
            other => panic!("FieldContent 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1391_memo_paragraph_loss_in_gate() {
        let mut fa = crate::model::control::Field::default();
        fa.field_type = crate::model::control::FieldType::Memo;
        fa.memo_paragraphs.push(Paragraph::default());
        let mut fb = crate::model::control::Field::default();
        fb.field_type = crate::model::control::FieldType::Memo;
        let a = doc_with_control(crate::model::control::Control::Field(fa));
        let b = doc_with_control(crate::model::control::Control::Field(fb));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::FieldContent { detail, .. } => {
                assert_eq!(detail, "memo paragraphs: expected=1 actual=0");
            }
            other => panic!("FieldContent 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1391_aift_memo_roundtrips() {
        // 실샘플 — aift MEMO 2건 parameters + 본문 보존, roundtrip 게이트 0.
        let bytes = std::fs::read("samples/hwpx/aift.hwpx").expect("샘플 읽기");
        let doc1 = parse_hwpx(&bytes).expect("parse 원본");
        let memo_count = doc1
            .sections
            .iter()
            .flat_map(|s| &s.paragraphs)
            .flat_map(|p| &p.controls)
            .filter(|c| {
                matches!(c, crate::model::control::Control::Field(f)
                if f.field_type == crate::model::control::FieldType::Memo)
            })
            .count();
        assert_eq!(memo_count, 2, "aift MEMO 2건");
        let out = serialize_hwpx(&doc1).expect("serialize");
        let doc2 = parse_hwpx(&out).expect("reparse");
        let diff = diff_documents(&doc1, &doc2);
        assert!(diff.is_empty(), "{:?}", diff.differences);
    }

    // ---------- #1389: 그림 크기 요소 게이트 동승 ----------

    #[test]
    fn task1389_picture_size_diff_in_gate() {
        let mut pa = crate::model::image::Picture::default();
        pa.shape_attr.current_width = 1366;
        pa.img_dim = (49380, 45840);
        let pb = crate::model::image::Picture::default(); // 크기 0
        let a = doc_with_control(crate::model::control::Control::Picture(Box::new(pa)));
        let b = doc_with_control(crate::model::control::Control::Picture(Box::new(pb)));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::PictureSize { path, detail, .. } => {
                assert_eq!(path, "/ctrl[0]pic");
                assert!(
                    detail.contains("curSz") && detail.contains("imgDim"),
                    "{detail}"
                );
            }
            other => panic!("PictureSize 여야 함: {other:?}"),
        }
    }

    /// [#4668] offset 재작성이 게이트에 잡혀야 한다 — 종전 PictureSize 비교가
    /// curSz/imgRect/imgDim 만 보고 offset 을 비교하지 않아, pic writer 의 pos
    /// 유래 offset 재작성이 왕복 검증을 통과했다.
    #[test]
    fn issue4668_picture_offset_diff_in_gate() {
        let mut pa = crate::model::image::Picture::default();
        pa.shape_attr.offset_x = 5250;
        pa.shape_attr.offset_y = -4332;
        let pb = crate::model::image::Picture::default(); // offset (0, 0)
        let a = doc_with_control(crate::model::control::Control::Picture(Box::new(pa)));
        let b = doc_with_control(crate::model::control::Control::Picture(Box::new(pb)));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::PictureSize { path, detail, .. } => {
                assert_eq!(path, "/ctrl[0]pic");
                assert!(
                    detail.contains("offset: expected=(5250, -4332) actual=(0, 0)"),
                    "{detail}"
                );
            }
            other => panic!("PictureSize 여야 함: {other:?}"),
        }
    }

    #[test]
    fn hwpx_to_hwp_zero_img_dim_sentinel_is_not_a_layout_loss() {
        let diff = IrDiff {
            differences: vec![
                IrDifference::PictureSize {
                    section: 0,
                    paragraph: 0,
                    path: "/ctrl[0]pic".to_string(),
                    detail: "imgDim: expected=(76800, 42240) actual=(0, 0)".to_string(),
                },
                IrDifference::PictureSize {
                    section: 0,
                    paragraph: 1,
                    path: "/ctrl[1]pic".to_string(),
                    detail: "curSz: expected=2400x1800 actual=0x0; imgDim: expected=(76800, 42240) actual=(0, 0)".to_string(),
                },
            ],
        };

        let filtered = strip_hwpx_to_hwp_noise(diff);
        assert_eq!(
            filtered.differences.len(),
            1,
            "실제 기하 손실은 남겨야 한다"
        );
        assert!(matches!(
            &filtered.differences[0],
            IrDifference::PictureSize { detail, .. } if detail.starts_with("curSz:")
        ));
    }

    #[test]
    fn issue_3739_hwp_to_hwpx_generated_command_parameters_are_incomparable() {
        let diff = IrDiff {
            differences: vec![
                IrDifference::FieldContent {
                    section: 0,
                    paragraph: 0,
                    path: "/ctrl[0]field".to_string(),
                    detail: r#"parameters: expected=None actual=Some("<hp:parameters cnt=\"1\" name=\"\"><hp:stringParam name=\"Command\">https://example.test</hp:stringParam></hp:parameters>")"#.to_string(),
                },
                IrDifference::FieldContent {
                    section: 0,
                    paragraph: 1,
                    path: "/ctrl[1]field".to_string(),
                    detail: r#"parameters: expected=None actual=Some("<hp:parameters cnt=\"2\" name=\"\"><hp:stringParam name=\"Command\">keep</hp:stringParam><hp:stringParam name=\"Direction\">keep</hp:stringParam></hp:parameters>")"#.to_string(),
                },
                IrDifference::CharShapeCount {
                    expected: 1,
                    actual: 2,
                },
            ],
        };

        let filtered = strip_hwp_to_hwpx_noise(diff);
        assert_eq!(
            filtered.differences.len(),
            2,
            "합성 Command 단일 parameters 외 차이는 남겨야 한다"
        );
        assert!(matches!(
            &filtered.differences[0],
            IrDifference::FieldContent { detail, .. } if detail.contains("cnt=\\\"2\\\"")
        ));
        assert!(matches!(
            &filtered.differences[1],
            IrDifference::CharShapeCount { .. }
        ));
    }

    #[test]
    fn issue_3739_hwp3_to_hwpx_materializes_hyperlink_and_empty_img_rect_only() {
        use crate::model::control::{Control, Field, FieldType, Hyperlink};

        let mut expected_document = Document::default();
        let mut actual_document = Document::default();
        let mut expected_section: crate::model::document::Section = Default::default();
        let mut actual_section: crate::model::document::Section = Default::default();
        for index in 0..4 {
            let mut expected = Paragraph::default();
            let mut actual = Paragraph::default();
            if index == 0 {
                expected.controls.push(Control::Hyperlink(Hyperlink {
                    url: "https://example.test".to_string(),
                    text: "example".to_string(),
                }));
                actual.controls.push(Control::Field(Field {
                    field_type: FieldType::Hyperlink,
                    command: "https://example.test".to_string(),
                    ..Default::default()
                }));
            }
            expected_section.paragraphs.push(expected);
            actual_section.paragraphs.push(actual);
        }
        expected_document.sections.push(expected_section);
        actual_document.sections.push(actual_section);

        let diff = IrDiff {
            differences: vec![
                IrDifference::ParagraphControls {
                    section: 0,
                    paragraph: 0,
                    path: String::new(),
                    expected: "[]".to_string(),
                    actual: "[field]".to_string(),
                },
                IrDifference::PictureSize {
                    section: 0,
                    paragraph: 1,
                    path: "/ctrl[0]pic".to_string(),
                    detail: "imgRect: expected=[0, 0, 0, 0]/[0, 0, 0, 0] actual=[0, 0, 2228, 0]/[2228, 2372, 0, 2372]".to_string(),
                },
                IrDifference::ParagraphControls {
                    section: 0,
                    paragraph: 2,
                    path: String::new(),
                    expected: "[pic]".to_string(),
                    actual: "[field]".to_string(),
                },
                IrDifference::PictureSize {
                    section: 0,
                    paragraph: 3,
                    path: "/ctrl[0]pic".to_string(),
                    detail: "curSz: expected=1x1 actual=2x2; imgRect: expected=[0, 0, 0, 0]/[0, 0, 0, 0] actual=[0, 0, 2, 0]/[2, 2, 0, 2]".to_string(),
                },
            ],
        };

        let filtered = strip_hwp3_to_hwpx_noise(&expected_document, &actual_document, diff);
        assert_eq!(
            filtered.differences.len(),
            2,
            "실제 control/기하 차이는 남겨야 한다"
        );
        assert!(matches!(
            &filtered.differences[0],
            IrDifference::ParagraphControls { expected, actual, .. }
                if expected == "[pic]" && actual == "[field]"
        ));
        assert!(matches!(
            &filtered.differences[1],
            IrDifference::PictureSize { detail, .. } if detail.starts_with("curSz:")
        ));
    }

    #[test]
    fn task1389_ta_pic_size_roundtrips() {
        // 실샘플 — ta-pic 셀 내 그림 curSz/imgRect/imgDim 보존, roundtrip 게이트 0.
        let bytes = std::fs::read("samples/hwpx/ta-pic-001-r.hwpx").expect("샘플 읽기");
        let doc1 = parse_hwpx(&bytes).expect("parse 원본");
        // 셀 내 pic 의 img_dim 이 적재됐는지 전제 확인 (49380 등 비0).
        let has_dim = doc1
            .sections
            .iter()
            .flat_map(|s| &s.paragraphs)
            .flat_map(|p| &p.controls)
            .any(|c| matches!(c, crate::model::control::Control::Table(t)
                if t.cells.iter().flat_map(|ce| &ce.paragraphs).flat_map(|q| &q.controls)
                    .any(|cc| matches!(cc, crate::model::control::Control::Picture(pic) if pic.img_dim.0 > 0))));
        assert!(has_dim, "셀 내 pic img_dim 적재 전제");
        let out = serialize_hwpx(&doc1).expect("serialize");
        let doc2 = parse_hwpx(&out).expect("reparse");
        let diff = diff_documents(&doc1, &doc2);
        assert!(diff.is_empty(), "{:?}", diff.differences);
    }

    // ---------- #1393: 표 page_break 게이트 동승 ----------

    #[test]
    fn task1393_table_page_break_diff_in_gate() {
        use crate::model::table::TablePageBreak;
        fn tbl(pb: TablePageBreak) -> crate::model::control::Control {
            match table_control(&[]) {
                crate::model::control::Control::Table(mut t) => {
                    t.page_break = pb;
                    crate::model::control::Control::Table(t)
                }
                _ => unreachable!(),
            }
        }
        let a = doc_with_control(tbl(TablePageBreak::RowBreak));
        let b = doc_with_control(tbl(TablePageBreak::CellBreak));
        let diff = diff_documents(&a, &b);
        assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
        match &diff.differences[0] {
            IrDifference::TablePageBreak { path, detail, .. } => {
                assert_eq!(path, "/ctrl[0]tbl");
                assert_eq!(detail, "expected=RowBreak actual=CellBreak");
            }
            other => panic!("TablePageBreak 여야 함: {other:?}"),
        }
    }

    #[test]
    fn task1393_form_002_page_break_roundtrips() {
        // 실샘플 — form-002 표 page_break(CELL=RowBreak) 보존, roundtrip 게이트 0.
        let bytes = std::fs::read("samples/hwpx/form-002.hwpx").expect("샘플 읽기");
        let doc1 = parse_hwpx(&bytes).expect("parse 원본");
        let out = serialize_hwpx(&doc1).expect("serialize");
        let doc2 = parse_hwpx(&out).expect("reparse");
        let diff = diff_documents(&doc1, &doc2);
        assert!(diff.is_empty(), "{:?}", diff.differences);
    }
}