croma-core 1.4.0

Library-first ABC to MusicXML exporter
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
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
//! Reader tests.
//!
//! Two layers:
//!
//! 1. **Per-element unit tests** (hard asserts): each TDD'd against one element
//!    class, asserting BOTH the XML re-emission idempotence
//!    `write(read(write(score))) == write(score)` AND a reconstructed model
//!    field directly (so the test fails loudly if the reader builds a Score that
//!    happens to re-write the same bytes for the wrong reason).
//! 2. **Corpus measurement** (env-gated, mirrors `croma-fmt`'s `corpus_proof`):
//!    walks the 10k corpus, runs the idempotence loop per file, counts
//!    idempotent files and tallies the first diverging XML tag. It asserts no
//!    hard count for S1 (most files use later-stage elements) โ€” it reports so
//!    the orchestrator can read the number.

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

use crate::model::{Fraction, Score, TempoBeatRole, TimedEventKind};
use crate::musicxml::read::read_musicxml;
use crate::musicxml::write_score_partwise;
use crate::{AbcWriteOptions, export_musicxml, write_abc, write_musicxml};

/// `export_musicxml` for ABC that is expected to lower cleanly.
fn export(abc: &str) -> String {
    export_musicxml(abc)
        .unwrap_or_else(|error| panic!("ABC should export: {error:?}"))
        .musicxml
}

/// The S1 round-trip: ABC -> X1 -> read -> X2. Returns `(x1, x2, score)`.
fn round_trip(abc: &str) -> (String, String, Score) {
    let x1 = export(abc);
    let report = read_musicxml(&x1);
    let x2 = write_score_partwise(&report.value).value;
    (x1, x2, report.value)
}

/// Remove the `<key>...</key>` and `<time>...</time>` sub-blocks that the writer
/// always emits inside the first `<attributes>`. These are **stage S2** (the
/// reader does not reconstruct `<key>`/`<time>` yet), and every ABC tune
/// necessarily carries a `K:` (and usually an `M:`), so a header-attribute-free
/// fixture is impossible via the ABC path. Stripping exactly these two deferred
/// blocks scopes the unit-test idempotence assertion to the **S1-supported
/// subset** โ€” note/measure/duration/metadata reconstruction โ€” which is the
/// design's "0 diffs on the supported subset" contract. The corpus measurement
/// below deliberately keeps the FULL, unmodified byte comparison so the reported
/// idempotent count stays honest.
fn strip_stage2_attributes(xml: &str) -> String {
    let mut out = String::with_capacity(xml.len());
    let mut skip_until: Option<&'static str> = None;
    for line in xml.lines() {
        if let Some(close) = skip_until {
            if line.trim() == close {
                skip_until = None;
            }
            continue;
        }
        match line.trim() {
            "<key>" => skip_until = Some("</key>"),
            line_trimmed if line_trimmed == "<time>" || line_trimmed.starts_with("<time ") => {
                skip_until = Some("</time>");
            }
            _ => {
                out.push_str(line);
                out.push('\n');
            }
        }
    }
    out
}

/// Assert the re-emission is byte-identical on the S1-supported subset (see
/// [`strip_stage2_attributes`]) and return the reconstructed score for direct
/// model-field assertions.
fn assert_idempotent(abc: &str) -> Score {
    let (x1, x2, score) = round_trip(abc);
    assert_eq!(
        strip_stage2_attributes(&x1),
        strip_stage2_attributes(&x2),
        "write(read(write(score))) must equal write(score) on the S1-supported subset"
    );
    score
}

/// Remove only the **stage S3+** writer blocks (`<score-instrument>` /
/// `<midi-instrument>`) so an S2 idempotence assertion keeps `<key>`/`<time>`/
/// `<clef>`/`<transpose>` in the byte comparison โ€” those are reconstructed now โ€”
/// while still ignoring the part-list MIDI that S3 will own.
fn strip_stage3_blocks(xml: &str) -> String {
    let mut out = String::with_capacity(xml.len());
    let mut skip_until: Option<&'static str> = None;
    for line in xml.lines() {
        if let Some(close) = skip_until {
            if line.trim() == close {
                skip_until = None;
            }
            continue;
        }
        let trimmed = line.trim();
        if trimmed.starts_with("<score-instrument") {
            skip_until = Some("</score-instrument>");
        } else if trimmed.starts_with("<midi-instrument") {
            skip_until = Some("</midi-instrument>");
        } else {
            out.push_str(line);
            out.push('\n');
        }
    }
    out
}

/// Assert the re-emission is byte-identical on the **S2-supported subset**: the
/// full header `<attributes>` (`<key>`/`<time>`/`<clef>`/`<transpose>`) must
/// survive verbatim; only the still-deferred S3 part-list MIDI is stripped.
fn assert_idempotent_s2(abc: &str) -> Score {
    let (x1, x2, score) = round_trip(abc);
    assert_eq!(
        strip_stage3_blocks(&x1),
        strip_stage3_blocks(&x2),
        "write(read(write(score))) must equal write(score) on the S2-supported subset"
    );
    score
}

fn first_note_pitch(score: &Score) -> &crate::model::Pitch {
    match &score.parts[0].voices[0].events[0].kind {
        TimedEventKind::Note(note) => &note.pitch,
        other => panic!("expected first event to be a note, got {other:?}"),
    }
}

#[test]
fn malformed_xml_is_total_and_diagnosed() {
    let report = read_musicxml("<score-partwise><part></broken>");
    assert!(
        report
            .diagnostics
            .iter()
            .any(|d| d.code.starts_with("musicxml.read")),
        "a malformed document must yield a reader diagnostic, got {:?}",
        report.diagnostics
    );
    // Totality: an empty/minimal Score, no panic.
    assert!(
        report.value.parts.is_empty() || report.value.parts.iter().all(|p| p.voices.len() <= 1)
    );
}

#[test]
fn non_partwise_root_is_diagnosed() {
    let report = read_musicxml("<?xml version=\"1.0\"?><score-timewise></score-timewise>");
    assert!(
        report
            .diagnostics
            .iter()
            .any(|d| d.code == "musicxml.read.unsupported_root"),
        "a non-partwise root must warn, got {:?}",
        report.diagnostics
    );
}

#[test]
fn doctype_prefixed_document_is_read_not_rejected() {
    // R2b: every real-world MusicXML file (abc2xml / MuseScore / Finale /
    // Sibelius) carries a `<!DOCTYPE score-partwise PUBLIC ...>` declaration.
    // The reader must be DTD-tolerant: this minimal-but-valid doctype-prefixed
    // document must reconstruct a NON-empty Score (>=1 part, the expected note),
    // not bail at the parse gate with `musicxml.read.parse_error`. With the
    // default `allow_dtd: false` this returns an empty Score (the bug).
    let xml = concat!(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
        "<!DOCTYPE score-partwise PUBLIC \"-//Recordare//DTD MusicXML 3.0 Partwise//EN\" ",
        "\"http://www.musicxml.org/dtds/partwise.dtd\">\n",
        "<score-partwise>\n",
        "  <part-list><score-part id=\"P1\"><part-name>Music</part-name></score-part></part-list>\n",
        "  <part id=\"P1\"><measure number=\"1\">\n",
        "    <attributes><divisions>2</divisions></attributes>\n",
        "    <note><pitch><step>D</step><octave>5</octave></pitch>\n",
        "    <duration>2</duration><voice>1</voice><type>quarter</type></note>\n",
        "  </measure></part>\n",
        "</score-partwise>\n",
    );
    let report = read_musicxml(xml);
    // No parse-gate rejection.
    assert!(
        report
            .diagnostics
            .iter()
            .all(|d| d.code != "musicxml.read.parse_error"),
        "a DOCTYPE-prefixed document must not be rejected at the parse gate, got {:?}",
        report.diagnostics
    );
    // A non-empty Score with the expected single note reconstructed.
    assert_eq!(report.value.parts.len(), 1, "expected exactly one part");
    let pitch = first_note_pitch(&report.value);
    assert_eq!(pitch.step, 'D');
    assert_eq!(pitch.octave, 5);
    assert_eq!(pitch.alter, 0);
    assert_eq!(
        report.value.parts[0].voices[0].events[0].duration,
        Fraction::new(1, 4),
        "a <duration>2</duration> at <divisions>2</divisions> is a quarter note"
    );
}

#[test]
fn doctype_then_garbage_is_total_and_diagnosed() {
    // R2b totality guard: enabling DTD tolerance must NOT make a genuinely
    // malformed document parse. A valid doctype followed by a truncated /
    // mismatched body must still degrade to the graceful empty Score PLUS a
    // reader diagnostic, never a panic.
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<!DOCTYPE score-partwise PUBLIC \"-//Recordare//DTD MusicXML 3.0 Partwise//EN\" ",
        "\"http://www.musicxml.org/dtds/partwise.dtd\">\n",
        "<score-partwise><part></not-the-same-tag> &&& <<< broken",
    );
    let report = read_musicxml(xml);
    assert!(
        report
            .diagnostics
            .iter()
            .any(|d| d.code.starts_with("musicxml.read")),
        "a DTD-prefixed-but-malformed document must yield a reader diagnostic, got {:?}",
        report.diagnostics
    );
    // Totality: a minimal/empty Score, no panic, no reconstructed parts.
    assert!(
        report.value.parts.is_empty(),
        "a malformed document must degrade to an empty Score, got {} part(s)",
        report.value.parts.len()
    );
}

#[test]
fn single_note_round_trips_and_reconstructs_pitch() {
    let score = assert_idempotent("X:1\nT:One\nL:1/4\nK:C\nC\n");
    let pitch = first_note_pitch(&score);
    assert_eq!(pitch.step, 'C');
    assert_eq!(pitch.octave, 4);
    assert_eq!(pitch.alter, 0);
    assert_eq!(
        score.parts[0].voices[0].events[0].duration,
        Fraction::new(1, 4),
        "a quarter note must reconstruct as 1/4"
    );
}

#[test]
fn altered_pitch_reconstructs_alter_and_written_accidental() {
    // ^F is F-sharp: <alter>1</alter> (sounding pitch +1) plus an explicit
    // <accidental>sharp</accidental> the reader reconstructs as a written mark.
    let score = assert_idempotent("X:1\nT:Sharp\nL:1/4\nK:C\n^F\n");
    let pitch = first_note_pitch(&score);
    assert_eq!(pitch.step, 'F');
    assert_eq!(pitch.alter, 1);
    let written = match &score.parts[0].voices[0].events[0].kind {
        TimedEventKind::Note(note) => note.written_accidental,
        other => panic!("expected a note, got {other:?}"),
    };
    let written = written.expect("an explicit ^ accidental must reconstruct a written mark");
    assert_eq!(written.kind, crate::model::Accidental::Sharp);
    assert!(written.explicit);
}

// --- Stage R2d: decimal `<alter>` parsing -----------------------------------
//
// The MusicXML spec types `<alter>` (and the `<*-alter>` family) as `decimal`,
// and abc2xml / music21 / MuseScore / Finale all emit it as a FLOAT
// (`<alter>1.0</alter>`). The reader must parse the decimal and round to the
// nearest whole semitone; a bare-integer parse drops every float-encoded
// accidental, silently corrupting the sounding pitch. These cases feed a raw,
// hand-authored foreign-dialect `<pitch>` so the alter text is arbitrary.

/// A one-measure foreign score whose single quarter note carries `alter_xml`
/// verbatim inside its `<pitch>` (e.g. `<alter>1.0</alter>`, or `""` for none).
fn foreign_pitch_score(alter_xml: &str) -> crate::parse::ParseReport<Score> {
    let xml = format!(
        r#"<?xml version="1.0"?>
<score-partwise>
  <part-list><score-part id="P1"><part-name>P</part-name></score-part></part-list>
  <part id="P1">
    <measure number="1">
      <attributes><divisions>8</divisions></attributes>
      <note>
        <pitch><step>C</step>{alter_xml}<octave>5</octave></pitch>
        <duration>8</duration>
        <voice>1</voice>
        <type>quarter</type>
      </note>
    </measure>
  </part>
</score-partwise>"#
    );
    read_musicxml(&xml)
}

/// The reconstructed `alter` of the foreign score's first note.
fn foreign_pitch_alter(alter_xml: &str) -> i8 {
    let score = foreign_pitch_score(alter_xml).value;
    first_note_pitch(&score).alter
}

#[test]
fn float_alter_sharp_reconstructs_as_one() {
    // abc2xml/music21 emit `<alter>1.0</alter>`; a bare-i8 parse drops it and the
    // note reads natural. The decimal parse must recover the +1 semitone.
    assert_eq!(
        foreign_pitch_alter("<alter>1.0</alter>"),
        1,
        "<alter>1.0</alter> must reconstruct a +1 (sharp) sounding alter"
    );
}

#[test]
fn foreign_additive_meter_parenthesises_for_abc() {
    // A foreign <time> with an additive numerator (<beats>11+7</beats>, also <beats>4+3</beats>)
    // must project to ABC as the parenthesised `M:(11+7)/16`. The bare `M:11+7/16` is
    // not valid ABC, so the parser dropped the WHOLE meter, losing it on re-export
    // (PDMX composite-time: pdmx_0894, pdmx_1389). The parenthesised form round-trips
    // back to <beats>11+7</beats>.
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list><score-part id=\"P1\"><part-name>P</part-name></score-part></part-list>\n",
        "  <part id=\"P1\"><measure number=\"1\">\n",
        "    <attributes><divisions>4</divisions>",
        "<time><beats>11+7</beats><beat-type>16</beat-type></time></attributes>\n",
        "    <note><pitch><step>C</step><octave>5</octave></pitch><duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
        "  </measure></part>\n",
        "</score-partwise>\n",
    );
    let score = read_musicxml(xml).value;
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("M:(11+7)/16"),
        "an additive foreign meter must project as parenthesised ABC `M:(11+7)/16`; got:\n{abc}"
    );
    let roundtrip = export_musicxml(&abc).expect("additive-meter ABC should export");
    assert!(
        roundtrip.musicxml.contains("<beats>11+7</beats>")
            && roundtrip.musicxml.contains("<beat-type>16</beat-type>"),
        "round-trip MusicXML must restore the additive <beats>11+7</beats>:\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn float_alter_flat_reconstructs_as_negative_one() {
    assert_eq!(
        foreign_pitch_alter("<alter>-1.0</alter>"),
        -1,
        "<alter>-1.0</alter> must reconstruct a -1 (flat) sounding alter"
    );
}

#[test]
fn float_alter_double_sharp_reconstructs_as_two() {
    assert_eq!(
        foreign_pitch_alter("<alter>2.0</alter>"),
        2,
        "<alter>2.0</alter> must reconstruct a +2 (double-sharp) sounding alter"
    );
}

#[test]
fn integer_alter_still_reconstructs_without_regression() {
    // croma's OWN writer emits a bare integer `<alter>`; the decimal parse of "1"
    // must still yield exactly 1 (the f64 round-trip is exact for small integers).
    assert_eq!(
        foreign_pitch_alter("<alter>1</alter>"),
        1,
        "integer <alter>1</alter> must still reconstruct as +1"
    );
}

#[test]
fn quarter_tone_alter_rounds_and_diagnoses_without_panic() {
    // A genuine quarter-tone `<alter>0.5</alter>` is unrepresentable in croma's
    // whole-semitone model: keep the rounded value (0 or 1) AND emit a diagnostic,
    // never panic, never silently drop.
    let report = foreign_pitch_score("<alter>0.5</alter>");
    let alter = first_note_pitch(&report.value).alter;
    assert!(
        alter == 0 || alter == 1,
        "a 0.5 quarter-tone alter must round to the nearest semitone (0 or 1), got {alter}"
    );
    assert!(
        report
            .diagnostics
            .iter()
            .any(|d| d.code == "musicxml.read.fractional_alter"),
        "a non-integer (quarter-tone) alter must emit a diagnostic"
    );
}

#[test]
fn float_alter_note_round_trips_to_integer_alter_and_is_stable() {
    // Reading a float-alter note then re-emitting must produce an INTEGER
    // `<alter>` (croma's writer never emits a decimal), and re-reading that is
    // stable at the same +1 alter.
    let x1 = r#"<?xml version="1.0"?>
<score-partwise>
  <part-list><score-part id="P1"><part-name>P</part-name></score-part></part-list>
  <part id="P1">
    <measure number="1">
      <attributes><divisions>8</divisions></attributes>
      <note>
        <pitch><step>C</step><alter>1.0</alter><octave>5</octave></pitch>
        <duration>8</duration>
        <voice>1</voice>
        <type>quarter</type>
      </note>
    </measure>
  </part>
</score-partwise>"#;
    let score = read_musicxml(x1).value;
    let x2 = write_score_partwise(&score).value;
    assert!(
        x2.contains("<alter>1</alter>"),
        "re-emission must carry an INTEGER <alter>1</alter>, got:\n{x2}"
    );
    assert!(
        !x2.contains("<alter>1.0</alter>"),
        "the writer must never emit a decimal <alter>"
    );
    let reread = read_musicxml(&x2).value;
    assert_eq!(
        first_note_pitch(&reread).alter,
        1,
        "the re-read float-alter note must stay +1"
    );
}

#[test]
fn rest_round_trips_and_reconstructs_kind() {
    let score = assert_idempotent("X:1\nT:Rest\nL:1/4\nK:C\nz\n");
    assert!(
        matches!(
            score.parts[0].voices[0].events[0].kind,
            TimedEventKind::Rest(_)
        ),
        "a z rest must reconstruct as a Rest event"
    );
}

#[test]
fn dotted_and_typed_durations_round_trip() {
    // C3/2 under L:1/4 is a dotted quarter (<type>quarter</type><dot/>);
    // the following note keeps the bar honest.
    let score = assert_idempotent("X:1\nT:Dotted\nM:3/4\nL:1/4\nK:C\nC3/2 D/2 E\n");
    assert_eq!(
        score.parts[0].voices[0].events[0].duration,
        Fraction::new(3, 8),
        "C3/2 under L:1/4 is 3/8 of a whole note"
    );
}

#[test]
fn multi_measure_round_trips_with_measure_ids() {
    let score = assert_idempotent("X:1\nT:Two Bars\nM:4/4\nL:1/4\nK:C\nC D E F | G A B c |\n");
    let measures = &score.parts[0].voices[0].measures;
    assert_eq!(measures.len(), 2, "two written bars -> two measures");
    assert_eq!(measures[0].id.number, 1);
    assert_eq!(measures[1].id.number, 2);
    // 8 quarter-note events spread over the two bars.
    assert_eq!(score.parts[0].voices[0].events.len(), 8);
}

#[test]
fn whole_measure_rest_reconstructs_measure_attribute() {
    // A bar that is exactly one rest long emits <rest measure="yes">; the
    // reader must reproduce it (so the attribute survives the round-trip).
    let x1 = export("X:1\nT:Full Rest\nM:4/4\nL:1/4\nK:C\nC D E F | z4 |\n");
    assert!(
        x1.contains("measure=\"yes\""),
        "precondition: a full-bar rest must emit measure=\"yes\""
    );
    let score = assert_idempotent("X:1\nT:Full Rest\nM:4/4\nL:1/4\nK:C\nC D E F | z4 |\n");
    // The second measure's single rest reconstructs with expected==actual.
    let second = &score.parts[0].voices[0].measures[1];
    assert_eq!(second.expected_duration, Some(Fraction::new(1, 1)));
    assert_eq!(second.actual_duration, Fraction::new(1, 1));
}

#[test]
fn invisible_rest_round_trips() {
    // `x` is an invisible rest -> <note print-object="no"><rest/>.
    let abc = "X:1\nT:Hidden\nM:4/4\nL:1/4\nK:C\nC x C x |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("print-object=\"no\""),
        "precondition: invisible rest emits print-object=\"no\""
    );
    assert_idempotent(abc);
}

#[test]
fn multi_part_skeleton_round_trips_with_names() {
    // Two %%score voices -> two parts; each part-name must survive the
    // round-trip and the reader must rebuild both parts with their names.
    let abc = "X:1\nT:Duet\nM:4/4\nL:1/4\n%%score (V1 V2)\nV:1 name=\"Flute\"\nV:2 name=\"Cello\"\nK:C\n[V:1] C D E F |\n[V:2] G,2 A,2 |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<part-name>Flute</part-name>") && x1.contains("<part-name>Cello</part-name>"),
        "precondition: both part-names are emitted"
    );
    let score = assert_idempotent(abc);
    assert_eq!(score.parts.len(), 2, "two %%score voices -> two parts");
    let names: Vec<_> = score
        .parts
        .iter()
        .filter_map(|part| part.name.as_ref().map(|line| line.text.clone()))
        .collect();
    assert_eq!(names, vec!["Flute".to_owned(), "Cello".to_owned()]);
}

#[test]
fn foreign_part_names_project_to_voice_headers() {
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <score-part id=\"P1\"><part-name>Flute</part-name></score-part>\n",
        "    <score-part id=\"P2\"><part-name>Cello</part-name></score-part>\n",
        "  </part-list>\n",
        "  <part id=\"P1\"><measure number=\"1\">\n",
        "    <attributes><divisions>4</divisions></attributes>\n",
        "    <note><pitch><step>C</step><octave>5</octave></pitch><duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
        "  </measure></part>\n",
        "  <part id=\"P2\"><measure number=\"1\">\n",
        "    <attributes><divisions>4</divisions></attributes>\n",
        "    <note><pitch><step>C</step><octave>3</octave></pitch><duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
        "  </measure></part>\n",
        "</score-partwise>\n",
    );

    let score = read_musicxml(xml).value;
    let abc = write_abc(&score, AbcWriteOptions::default());

    assert!(
        abc.contains("V:P1 name=\"Flute\"\n"),
        "MusicXML part-name must survive into ABC voice metadata; got:\n{abc}"
    );
    assert!(
        abc.contains("V:P2 name=\"Cello\"\n"),
        "MusicXML part-name must survive into ABC voice metadata; got:\n{abc}"
    );
}

#[test]
fn foreign_part_name_newline_does_not_break_voice_header() {
    // A multi-line foreign <part-name> (a display line-break, e.g. "S\nA" or
    // "Violoncello 1ยฐ\nconcertante") is inexpressible in a single-line ABC `V:`
    // header. An unescaped newline split the header line and corrupted every
    // following note on re-parse (PDMX pitch cluster: pdmx_1055, pdmx_1414). The
    // newline must normalise to a space so the header stays one line and the music
    // round-trips intact.
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <score-part id=\"P1\"><part-name>S\nA</part-name></score-part>\n",
        "  </part-list>\n",
        "  <part id=\"P1\"><measure number=\"1\">\n",
        "    <attributes><divisions>4</divisions></attributes>\n",
        "    <note><pitch><step>C</step><octave>5</octave></pitch><duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
        "  </measure></part>\n",
        "</score-partwise>\n",
    );
    let score = read_musicxml(xml).value;
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("V:P1 name=\"S A\"\n"),
        "a part-name newline must become a space, keeping the V: header on one line:\n{abc}"
    );
    // The ABC must re-export with the note intact (no line-break cascade).
    let roundtrip = export_musicxml(&abc).expect("name-normalised ABC should export");
    assert!(
        roundtrip.musicxml.contains("<step>C</step>"),
        "the following note must survive the part-name normalisation:\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn foreign_multi_voice_part_synthesizes_parenthesized_score_group() {
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <score-part id=\"P1\"><part-name>Piano</part-name></score-part>\n",
        "  </part-list>\n",
        "  <part id=\"P1\"><measure number=\"1\">\n",
        "    <attributes><divisions>4</divisions></attributes>\n",
        "    <note><pitch><step>C</step><octave>4</octave></pitch><duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
        "    <backup><duration>4</duration></backup>\n",
        "    <note><pitch><step>E</step><octave>4</octave></pitch><duration>4</duration><voice>2</voice><type>quarter</type></note>\n",
        "  </measure></part>\n",
        "</score-partwise>\n",
    );

    let score = read_musicxml(xml).value;
    let abc = write_abc(&score, AbcWriteOptions::default());

    assert!(
        abc.contains("%%score (P1 P1#2)\n"),
        "multiple MusicXML voices in one part must stay grouped in ABC; got:\n{abc}"
    );
    let roundtrip = export_musicxml(&abc).expect("grouped ABC should export");
    assert_eq!(
        roundtrip.musicxml.matches("<score-part id=").count(),
        1,
        "ABC->MusicXML must keep the two voices in one score-part:\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn foreign_voice_numbers_survive_abc_projection() {
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <score-part id=\"P1\"><part-name>Piano</part-name></score-part>\n",
        "  </part-list>\n",
        "  <part id=\"P1\"><measure number=\"1\">\n",
        "    <attributes><divisions>4</divisions></attributes>\n",
        "    <note><pitch><step>C</step><octave>4</octave></pitch><duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
        "    <backup><duration>4</duration></backup>\n",
        "    <note><pitch><step>G</step><octave>4</octave></pitch><duration>4</duration><voice>5</voice><type>quarter</type></note>\n",
        "  </measure></part>\n",
        "</score-partwise>\n",
    );

    let score = read_musicxml(xml).value;
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("%%score (P1 P1#5)\n"),
        "imported sparse MusicXML voice numbers must be visible in the ABC ownership group; got:\n{abc}"
    );

    let roundtrip = export_musicxml(&abc).expect("sparse voice ABC should export");
    assert!(
        roundtrip.musicxml.contains("<voice>5</voice>"),
        "ABC->MusicXML must preserve imported voice 5, not renumber it to voice 2:\n{}",
        roundtrip.musicxml
    );
    assert!(
        !roundtrip.musicxml.contains("<voice>2</voice>"),
        "imported sparse voice 5 must not be normalized to sequential voice 2:\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn foreign_single_unpitched_instrument_round_trips() {
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <score-part id=\"P1\">\n",
        "      <part-name>Percussion</part-name>\n",
        "      <score-instrument id=\"P1-I1\"><instrument-name>Wood Block</instrument-name></score-instrument>\n",
        "      <midi-instrument id=\"P1-I1\">\n",
        "        <midi-channel>10</midi-channel>\n",
        "        <midi-unpitched>76</midi-unpitched>\n",
        "      </midi-instrument>\n",
        "    </score-part>\n",
        "  </part-list>\n",
        "  <part id=\"P1\"><measure number=\"1\">\n",
        "    <attributes><divisions>4</divisions></attributes>\n",
        "    <note>\n",
        "      <unpitched><display-step>C</display-step><display-octave>5</display-octave></unpitched>\n",
        "      <duration>4</duration><voice>1</voice><type>quarter</type>\n",
        "      <instrument id=\"P1-I1\"/>\n",
        "    </note>\n",
        "  </measure></part>\n",
        "</score-partwise>\n",
    );

    let score = read_musicxml(xml).value;
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("%%MIDI midi-unpitched 76"),
        "MusicXML <midi-unpitched> must survive the ABC leg; got:\n{abc}"
    );

    let roundtrip = export_musicxml(&abc).expect("unpitched ABC carrier should export");
    assert!(
        roundtrip
            .musicxml
            .contains("<midi-unpitched>76</midi-unpitched>"),
        "ABC->MusicXML must preserve the unpitched MIDI map:\n{}",
        roundtrip.musicxml
    );
    assert!(
        roundtrip.musicxml.contains("<unpitched>")
            && roundtrip
                .musicxml
                .contains("<display-step>C</display-step>")
            && roundtrip
                .musicxml
                .contains("<display-octave>5</display-octave>"),
        "the note must remain an unpitched display note, not disappear or become a pitched note:\n{}",
        roundtrip.musicxml
    );
    assert!(
        !roundtrip.musicxml.contains("<pitch>"),
        "single unpitched percussion note must not round-trip as a pitched note:\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn foreign_single_voice_multi_instrument_map_round_trips() {
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <score-part id=\"P1\">\n",
        "      <part-name>Percussion</part-name>\n",
        "      <score-instrument id=\"P1-I1\"><instrument-name>Snare Drum</instrument-name></score-instrument>\n",
        "      <score-instrument id=\"P1-I2\"><instrument-name>Wood Block</instrument-name></score-instrument>\n",
        "      <midi-instrument id=\"P1-I1\"><midi-channel>10</midi-channel><midi-unpitched>39</midi-unpitched></midi-instrument>\n",
        "      <midi-instrument id=\"P1-I2\"><midi-channel>10</midi-channel><midi-unpitched>76</midi-unpitched></midi-instrument>\n",
        "    </score-part>\n",
        "  </part-list>\n",
        "  <part id=\"P1\"><measure number=\"1\">\n",
        "    <attributes><divisions>4</divisions></attributes>\n",
        "    <note>\n",
        "      <unpitched><display-step>D</display-step><display-octave>5</display-octave></unpitched>\n",
        "      <duration>4</duration><instrument id=\"P1-I1\"/><voice>1</voice><type>quarter</type>\n",
        "    </note>\n",
        "    <note>\n",
        "      <unpitched><display-step>C</display-step><display-octave>5</display-octave></unpitched>\n",
        "      <duration>4</duration><instrument id=\"P1-I2\"/><voice>1</voice><type>quarter</type>\n",
        "    </note>\n",
        "  </measure></part>\n",
        "</score-partwise>\n",
    );

    let score = read_musicxml(xml).value;
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("%%croma-musicxml-instrument id=\"P1-I1\" name=\"Snare Drum\"")
            && abc.contains("midi-unpitched=39")
            && abc.contains("%%croma-musicxml-instrument id=\"P1-I2\" name=\"Wood Block\"")
            && abc.contains("midi-unpitched=76"),
        "MusicXML part-list instruments must survive into the ABC carrier; got:\n{abc}"
    );
    assert!(
        abc.contains("[I:croma-note-instrument id=\"P1-I1\"]")
            && abc.contains("[I:croma-note-instrument id=\"P1-I2\"]"),
        "per-note MusicXML instrument refs must survive into the ABC carrier; got:\n{abc}"
    );

    let roundtrip = export_musicxml(&abc).expect("multi-instrument ABC carrier should export");
    assert!(
        roundtrip
            .musicxml
            .contains("<score-instrument id=\"P1-I1\">")
            && roundtrip
                .musicxml
                .contains("<instrument-name>Snare Drum</instrument-name>")
            && roundtrip
                .musicxml
                .contains("<midi-unpitched>39</midi-unpitched>")
            && roundtrip
                .musicxml
                .contains("<score-instrument id=\"P1-I2\">")
            && roundtrip
                .musicxml
                .contains("<instrument-name>Wood Block</instrument-name>")
            && roundtrip
                .musicxml
                .contains("<midi-unpitched>76</midi-unpitched>"),
        "ABC->MusicXML must preserve all part-list instruments:\n{}",
        roundtrip.musicxml
    );
    assert!(
        roundtrip.musicxml.contains("<instrument id=\"P1-I1\"/>")
            && roundtrip.musicxml.contains("<instrument id=\"P1-I2\"/>"),
        "ABC->MusicXML must preserve per-note instrument ids:\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn foreign_empty_instrument_name_does_not_gain_gm_fallback() {
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <score-part id=\"P1\">\n",
        "      <part-name></part-name>\n",
        "      <score-instrument id=\"P1-I1\"><instrument-name></instrument-name></score-instrument>\n",
        "      <midi-instrument id=\"P1-I1\">\n",
        "        <midi-channel>1</midi-channel>\n",
        "        <midi-program>1</midi-program>\n",
        "        <volume>78.74</volume>\n",
        "        <pan>0.00</pan>\n",
        "      </midi-instrument>\n",
        "    </score-part>\n",
        "  </part-list>\n",
        "  <part id=\"P1\"><measure number=\"1\">\n",
        "    <attributes><divisions>4</divisions></attributes>\n",
        "    <note><pitch><step>C</step><octave>4</octave></pitch><duration>4</duration><instrument id=\"P1-I1\"/><voice>1</voice><type>quarter</type></note>\n",
        "  </measure></part>\n",
        "</score-partwise>\n",
    );

    let score = read_musicxml(xml).value;
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("%%croma-musicxml-instrument id=\"P1-I1\" name=\"\""),
        "an explicit empty MusicXML instrument name must survive into ABC as name=\"\"; got:\n{abc}"
    );

    let roundtrip = export_musicxml(&abc).expect("empty-name instrument carrier should export");
    assert!(
        roundtrip
            .musicxml
            .contains("<instrument-name></instrument-name>"),
        "ABC->MusicXML must preserve the explicit empty instrument name:\n{}",
        roundtrip.musicxml
    );
    assert!(
        roundtrip
            .musicxml
            .contains("<midi-channel>1</midi-channel>")
            && roundtrip
                .musicxml
                .contains("<midi-program>1</midi-program>")
            && roundtrip.musicxml.contains("<volume>78.74</volume>")
            && roundtrip.musicxml.contains("<pan>0.00</pan>"),
        "empty-name round-trip must preserve the sibling MIDI fields:\n{}",
        roundtrip.musicxml
    );
    assert!(
        !roundtrip.musicxml.contains("acoustic_grand_piano"),
        "explicit empty instrument names must not be replaced by a GM fallback:\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn backup_forward_durations_are_read() {
    // A multi-voice bar forces a <backup> between the two voices; reading the
    // backup duration keeps onsets aligned so the bar re-emits identically.
    let abc = "X:1\nT:Backup\nM:4/4\nL:1/4\n%%score (V1 V2)\nV:1\nV:2\nK:C\n[V:1] C2 D2 |\n[V:2] E2 F2 |\n";
    let x1 = export(abc);
    if x1.contains("<backup>") {
        // The reader must at least not panic and must read the duration; full
        // multi-voice idempotence is S6, so we only assert totality here.
        let report = read_musicxml(&x1);
        assert!(
            !report.value.parts.is_empty(),
            "backup/forward parsing must still yield parts"
        );
    }
    // A single-voice file with a leading rest exercises forward-free onset
    // bookkeeping and must be idempotent.
    assert_idempotent("X:1\nT:Lead\nM:4/4\nL:1/4\nK:C\nz C2 z |\n");
}

#[test]
fn divisions_are_recovered() {
    // Mixed durations push divisions above 1; the reader must read the emitted
    // <divisions> so it can invert <duration>.
    let score = assert_idempotent("X:1\nT:Div\nM:4/4\nL:1/8\nK:C\nC2 D/2 E/2 F G A |\n");
    assert!(
        score.divisions >= 1,
        "divisions must be a positive integer, got {}",
        score.divisions
    );
    // Round-trip a 1/16-ish note: ensure the reconstructed duration is exact.
    let first = &score.parts[0].voices[0].events[0];
    assert_eq!(first.duration, Fraction::new(1, 4), "C2 under L:1/8 is 1/4");
}

// --- Stage S2: <attributes> (key / time / clef / transpose) ----------------

/// The reconstructed header key (`score.metadata.key`).
fn header_key(score: &Score) -> &crate::model::KeySignatureModel {
    score
        .metadata
        .key
        .as_ref()
        .expect("S2 must reconstruct the header <key> into score.metadata.key")
}

#[test]
fn header_key_fifths_sharp_round_trips() {
    // K:D is two sharps -> <fifths>2</fifths>.
    let score = assert_idempotent_s2("X:1\nT:Sharps\nL:1/4\nK:D\nD\n");
    assert_eq!(header_key(&score).fifths, 2, "K:D is 2 sharps");
    assert!(
        header_key(&score).explicit_accidentals.is_empty(),
        "a traditional key emits no explicit key accidentals"
    );
}

#[test]
fn header_key_fifths_flat_round_trips() {
    // K:F is one flat -> <fifths>-1</fifths>.
    let score = assert_idempotent_s2("X:1\nT:Flats\nL:1/4\nK:F\nF\n");
    assert_eq!(header_key(&score).fifths, -1, "K:F is 1 flat");
}

#[test]
fn header_key_fifths_zero_round_trips() {
    // K:C is no accidentals -> <fifths>0</fifths>.
    let score = assert_idempotent_s2("X:1\nT:Natural\nL:1/4\nK:C\nC\n");
    assert_eq!(header_key(&score).fifths, 0, "K:C is 0 fifths");
}

#[test]
fn header_key_minor_negative_fifths_round_trips() {
    // K:Cm is three flats -> <fifths>-3</fifths>.
    let score = assert_idempotent_s2("X:1\nT:Minor\nL:1/4\nK:Cm\nC\n");
    assert_eq!(header_key(&score).fifths, -3, "K:Cm is 3 flats");
}

#[test]
fn explicit_key_accidentals_round_trip() {
    // K:C exp ^f _b emits two (key-step, key-alter, key-accidental) triples that
    // the reader must rebuild into explicit_accidentals, preserving order.
    let abc = "X:1\nT:Exp\nL:1/4\nK:C exp ^f _b\nC\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<key-step>F</key-step>")
            && x1.contains("<key-accidental>flat</key-accidental>"),
        "precondition: explicit key accidentals are emitted"
    );
    let score = assert_idempotent_s2(abc);
    let accidentals = &header_key(&score).explicit_accidentals;
    assert_eq!(accidentals.len(), 2, "two explicit key accidentals");
    assert_eq!(accidentals[0].step, 'F');
    assert_eq!(accidentals[0].accidental, crate::model::Accidental::Sharp);
    assert_eq!(accidentals[1].step, 'B');
    assert_eq!(accidentals[1].accidental, crate::model::Accidental::Flat);
}

#[test]
fn header_meter_round_trips_and_reconstructs() {
    // M:6/8 -> <time><beats>6</beats><beat-type>8</beat-type>.
    let score = assert_idempotent_s2("X:1\nT:Compound\nM:6/8\nL:1/8\nK:C\nC2C2C2\n");
    let meter = score
        .metadata
        .meter
        .as_ref()
        .expect("S2 must reconstruct the header <time> into score.metadata.meter");
    assert_eq!(
        meter.display, "6/8",
        "reconstructed meter display drives re-emission"
    );
    assert!(!meter.free_meter);
}

#[test]
fn common_time_symbol_round_trips() {
    // M:C emits <time symbol="common">; the reconstructed meter must re-emit it.
    let abc = "X:1\nT:Common\nM:C\nL:1/4\nK:C\nCCCC\n";
    let x1 = export(abc);
    assert!(
        x1.contains("symbol=\"common\""),
        "precondition: M:C emits symbol=\"common\""
    );
    let score = assert_idempotent_s2(abc);
    let meter = score.metadata.meter.as_ref().expect("meter present");
    assert_eq!(meter.display, "C");
}

#[test]
fn cut_time_symbol_round_trips() {
    // M:C| emits <time symbol="cut">.
    let abc = "X:1\nT:Cut\nM:C|\nL:1/4\nK:C\nCCCC\n";
    let x1 = export(abc);
    assert!(
        x1.contains("symbol=\"cut\""),
        "precondition: M:C| emits symbol=\"cut\""
    );
    let score = assert_idempotent_s2(abc);
    assert_eq!(score.metadata.meter.as_ref().expect("meter").display, "C|");
}

#[test]
fn free_meter_round_trips() {
    // M:none emits NO <time>; both None and Some(free) meter re-emit nothing, so
    // idempotence holds with the reader leaving meter unset for an absent <time>.
    let abc = "X:1\nT:Free\nM:none\nL:1/4\nK:C\nCCCC\n";
    let x1 = export(abc);
    assert!(
        !x1.contains("<time"),
        "precondition: M:none emits no <time> element"
    );
    assert_idempotent_s2(abc);
}

#[test]
fn bass_clef_round_trips() {
    // clef=bass -> <sign>F</sign><line>4</line>; the reader must populate the
    // staff voice's initial_properties.clef so write_clefs re-emits F/4.
    let abc = "X:1\nT:Bass\nL:1/4\nK:C clef=bass\nC,\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<sign>F</sign>"),
        "precondition: clef=bass emits sign F"
    );
    assert_idempotent_s2(abc);
}

#[test]
fn alto_clef_round_trips() {
    // clef=alto -> <sign>C</sign><line>3</line>.
    let abc = "X:1\nT:Alto\nL:1/4\nK:C clef=alto\nC\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<sign>C</sign>"),
        "precondition: clef=alto emits sign C"
    );
    assert_idempotent_s2(abc);
}

#[test]
fn octave_clef_round_trips() {
    // clef=treble-8 -> G/2 plus <clef-octave-change>-1</clef-octave-change>.
    let abc = "X:1\nT:Octave\nL:1/4\nK:C clef=treble-8\nC\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<clef-octave-change>-1</clef-octave-change>"),
        "precondition: clef=treble-8 emits octave-change -1"
    );
    assert_idempotent_s2(abc);
}

#[test]
fn default_treble_clef_round_trips() {
    // No clef= -> the default <sign>G</sign><line>2</line> with no octave change.
    let score = assert_idempotent_s2("X:1\nT:Treble\nL:1/4\nK:C\nC\n");
    // The reconstructed staff voice carries a clef whose text maps back to G/2.
    assert!(
        !score.parts.is_empty(),
        "default clef file must still reconstruct a part"
    );
}

#[test]
fn midi_transpose_reconstructs_chromatic() {
    // %%MIDI transpose -12 -> <transpose><chromatic>-12</chromatic>; the reader
    // reconstructs voice.midi_transpose so re-emission reproduces it.
    let abc = "X:1\nT:Trans\nL:1/4\nK:C\n%%MIDI transpose -12\nC\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<chromatic>-12</chromatic>"),
        "precondition: %%MIDI transpose -12 emits chromatic -12"
    );
    let score = assert_idempotent_s2(abc);
    assert_eq!(
        score.parts[0].voices[0].midi_transpose,
        Some(-12),
        "midi_transpose must reconstruct the chromatic value"
    );
}

#[test]
fn positive_midi_transpose_reconstructs() {
    let abc = "X:1\nT:Up\nL:1/4\nK:C\n%%MIDI transpose 7\nC\n";
    let score = assert_idempotent_s2(abc);
    assert_eq!(score.parts[0].voices[0].midi_transpose, Some(7));
}

// --- Stage S3: <part-list> MIDI instruments (closes the %%MIDI loop) ---------

/// Assert FULL-byte idempotence โ€” S3 reconstructs the `<part-list>`
/// `<score-instrument>`/`<midi-instrument>` blocks, so nothing is stripped any
/// more for a single-voice file. This is the closed-loop gate the stage exists
/// for. Returns the reconstructed score for direct `midi_instrument` asserts.
fn assert_idempotent_s3(abc: &str) -> Score {
    let (x1, x2, score) = round_trip(abc);
    assert_eq!(
        x1, x2,
        "write(read(write(score))) must equal write(score) byte-for-byte (S3 full loop)"
    );
    score
}

/// The reconstructed first voice's MIDI instrument.
fn first_midi(score: &Score) -> crate::model::MidiInstrumentModel {
    score.parts[0].voices[0]
        .midi_instrument
        .expect("S3 must reconstruct voice.midi_instrument from the part-list")
}

#[test]
fn midi_program_reconstructs_zero_based() {
    // %%MIDI program 73 -> <midi-program>74</midi-program> (1-based); the reader
    // must invert to the 0-based program 73, regenerating the same GM name +
    // <midi-program> on re-write.
    let abc = "X:1\nT:P\nL:1/4\nK:C\n%%MIDI program 73\nC\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<midi-program>74</midi-program>")
            && x1.contains("<instrument-name>flute</instrument-name>"),
        "precondition: program 73 emits 1-based 74 + GM name flute"
    );
    let midi = first_midi(&assert_idempotent_s3(abc));
    assert_eq!(
        midi.program,
        Some(73),
        "<midi-program>74 inverts to 0-based 73"
    );
    assert_eq!(midi.channel, None);
    assert_eq!(midi.volume_cc, None);
    assert_eq!(midi.pan_cc, None);
}

#[test]
fn midi_program_with_channel_reconstructs_both() {
    // The two-integer `program <chan> <prog>` form -> <midi-channel> + 1-based
    // <midi-program>; the reader recovers channel and 0-based program.
    let abc = "X:1\nT:PC\nL:1/4\nK:C\n%%MIDI program 1 56\nC\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<midi-channel>1</midi-channel>")
            && x1.contains("<midi-program>57</midi-program>"),
        "precondition: program 1 56 emits channel 1 + 1-based program 57"
    );
    let midi = first_midi(&assert_idempotent_s3(abc));
    assert_eq!(midi.program, Some(56));
    assert_eq!(midi.channel, Some(1));
}

#[test]
fn standalone_channel_reconstructs_with_no_program() {
    // A standalone `%%MIDI channel 10` emits ONLY <midi-channel> and falls back
    // to the PART NAME for <instrument-name> (program is None). The reader must
    // leave program = None so re-write reproduces the part-name fallback, not a
    // GM name.
    let abc = "X:1\nT:Ch\nL:1/4\nK:C\n%%MIDI channel 10\nC\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<midi-channel>10</midi-channel>")
            && !x1.contains("<midi-program>")
            && x1.contains("<instrument-name>Ch</instrument-name>"),
        "precondition: standalone channel emits no program + part-name fallback"
    );
    let midi = first_midi(&assert_idempotent_s3(abc));
    assert_eq!(
        midi.program, None,
        "no program -> re-write must use the part name"
    );
    assert_eq!(midi.channel, Some(10));
}

#[test]
fn control7_volume_reconstructs_cc() {
    // %%MIDI control 7 64 -> <volume>50.39</volume>; the reader must invert the
    // float back to the exact integer CC 64 (round(50.39 * 1.27) == 64).
    let abc = "X:1\nT:Vol\nL:1/4\nK:C\n%%MIDI control 7 64\nC\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<volume>50.39</volume>"),
        "precondition: control 7 64 emits volume 50.39"
    );
    let midi = first_midi(&assert_idempotent_s3(abc));
    assert_eq!(midi.volume_cc, Some(64), "<volume>50.39 inverts to CC 64");
    assert_eq!(midi.program, None);
}

#[test]
fn control10_pan_reconstructs_cc() {
    // %%MIDI control 10 64 is the MIDI center; MusicXML center is exactly 0.
    let abc = "X:1\nT:Pan\nL:1/4\nK:C\n%%MIDI control 10 64\nC\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<pan>0.00</pan>"),
        "precondition: control 10 64 emits exact center pan"
    );
    let midi = first_midi(&assert_idempotent_s3(abc));
    assert_eq!(midi.pan_cc, Some(64), "<pan>0.00 inverts to CC 64");
}

#[test]
fn pan_extremes_reconstruct() {
    // CC 0 -> <pan>-90.00</pan>, CC 127 -> <pan>90.00</pan>; the boundary values
    // must invert exactly (no off-by-one at the signed extremes).
    let low = "X:1\nT:PanLo\nL:1/4\nK:C\n%%MIDI control 10 0\nC\n";
    assert_eq!(first_midi(&assert_idempotent_s3(low)).pan_cc, Some(0));
    let high = "X:1\nT:PanHi\nL:1/4\nK:C\n%%MIDI control 10 127\nC\n";
    assert_eq!(first_midi(&assert_idempotent_s3(high)).pan_cc, Some(127));
}

#[test]
fn full_midi_instrument_reconstructs_all_fields() {
    // program + channel + CC7 + CC10 in one <midi-instrument>; every field must
    // round-trip and reconstruct, and the whole document must be byte-identical.
    let abc = "X:1\nT:All\nL:1/4\nK:C\n%%MIDI program 1 56\n%%MIDI control 7 100\n%%MIDI control 10 30\nC\n";
    let midi = first_midi(&assert_idempotent_s3(abc));
    assert_eq!(midi.program, Some(56));
    assert_eq!(midi.channel, Some(1));
    assert_eq!(midi.volume_cc, Some(100));
    assert_eq!(midi.pan_cc, Some(30));
}

#[test]
fn midi_unpitched_reconstructs_and_writes_unpitched_notes() {
    let abc = "X:1\nT:Block\nL:1/4\nK:C\n%%MIDI channel 10\n%%MIDI midi-unpitched 76\nc\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<midi-unpitched>76</midi-unpitched>"),
        "precondition: midi-unpitched emits a MusicXML percussion map"
    );
    assert!(
        x1.contains("<unpitched>") && !x1.contains("<pitch>"),
        "precondition: a voice-level unpitched MIDI map emits notes as <unpitched>, not <pitch>:\n{x1}"
    );
    let midi = first_midi(&assert_idempotent_s3(abc));
    assert_eq!(midi.channel, Some(10));
    assert_eq!(midi.midi_unpitched, Some(76));
}

#[test]
fn inline_midi_program_reconstructs_like_line_start() {
    // The inline `[I:MIDI=program N]` form projects identically to the line-start
    // directive; the reader inverts it the same way (closing the inline loop).
    let abc = "X:1\nT:Inl\nL:1/4\nK:C\n[I:MIDI=program 40]C\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<midi-program>41</midi-program>"),
        "precondition: inline program 40 emits 1-based 41"
    );
    let midi = first_midi(&assert_idempotent_s3(abc));
    assert_eq!(
        midi.program,
        Some(40),
        "inline program 40 inverts to 0-based 40"
    );
}

#[test]
fn no_midi_directive_leaves_instrument_none() {
    // A file with no %%MIDI must not fabricate a midi_instrument (the writer
    // emits no part-list instrument for it).
    let score = assert_idempotent_s3("X:1\nT:Plain\nL:1/4\nK:C\nC\n");
    assert_eq!(
        score.parts[0].voices[0].midi_instrument, None,
        "no %%MIDI -> no reconstructed instrument"
    );
}

#[test]
fn float_cc_round_trip_is_stable_for_every_value() {
    // Design ยง9 (REQUIRED): the writer formats <volume> as `{:.2}` of cc/1.27 and
    // <pan> as `{:.2}` of cc/127*180-90; the reader inverts with round(v*1.27)
    // and round((p+90)*127/180). Prove the round-trip recovers the EXACT integer
    // CC for every cc in 0..=127, for both volume and pan. This is what makes
    // <volume>/<pan> idempotent under the closed loop.
    for cc in 0u8..=127 {
        let v: f64 = format!("{:.2}", f64::from(cc) / 1.27)
            .parse()
            .expect("formatted volume must parse as f64");
        let back = (v * 1.27).round();
        assert_eq!(
            back,
            f64::from(cc),
            "volume CC {cc}: round({v} * 1.27) = {back}, expected {cc}"
        );

        let p: f64 = format!("{:.2}", f64::from(cc) / 127.0 * 180.0 - 90.0)
            .parse()
            .expect("formatted pan must parse as f64");
        let back = ((p + 90.0) * 127.0 / 180.0).round();
        assert_eq!(
            back,
            f64::from(cc),
            "pan CC {cc}: round(({p} + 90) * 127 / 180) = {back}, expected {cc}"
        );
    }
}

// --- Stage S4: <notations> + <time-modification> -----------------------------

/// Assert FULL-byte idempotence on an S4 single-voice fixture. By S4 the writer
/// emits `<tied>`/`<tie>`, `<slur>`, `<tuplet>`/`<time-modification>` and the
/// `<notations>` decoration groups; nothing in a single-voice notation fixture
/// is deferred, so the whole document must be byte-identical. Returns the
/// reconstructed score for direct attachment-field assertions.
fn assert_idempotent_s4(abc: &str) -> Score {
    let (x1, x2, score) = round_trip(abc);
    assert_eq!(
        x1, x2,
        "write(read(write(score))) must equal write(score) byte-for-byte (S4 notations)"
    );
    score
}

/// The `EventAttachments` of the first part's first voice's event at `index`.
fn attachments_at(score: &Score, index: usize) -> &crate::model::EventAttachments {
    &score.parts[0].voices[0].events[index].attachments
}

#[test]
fn tie_round_trips_and_reconstructs_attachment() {
    // C2-C2 ties two quarters: the first note carries a TieRole::Start, the
    // second a TieRole::Stop. Both <tie> (pre-<voice>) and <tied> (in
    // <notations>) re-emit from the single reconstructed `ties` list.
    use crate::model::TieRole;
    let abc = "X:1\nT:Tie\nM:4/4\nL:1/4\nK:C\nC2- C2 z4 |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<tie type=\"start\"/>") && x1.contains("<tied type=\"start\" number=\"1\"/>"),
        "precondition: a tie emits both <tie> and <tied>"
    );
    let score = assert_idempotent_s4(abc);
    let start = &attachments_at(&score, 0).ties;
    assert_eq!(start.len(), 1, "tie start note has one TieAttachment");
    assert_eq!(start[0].role, TieRole::Start);
    assert!(!start[0].dotted);
    let stop = &attachments_at(&score, 1).ties;
    assert_eq!(stop.len(), 1);
    assert_eq!(stop[0].role, TieRole::Stop);
}

#[test]
fn dotted_tie_reconstructs_line_type() {
    // `.-` is a dotted tie -> <tied ... line-type="dotted"/>; the reader must
    // recover `dotted = true` so the attribute re-emits.
    let abc = "X:1\nT:DotTie\nM:4/4\nL:1/4\nK:C\nC.-C z2 |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("line-type=\"dotted\""),
        "precondition: dotted tie emits line-type=\"dotted\""
    );
    let score = assert_idempotent_s4(abc);
    assert!(
        attachments_at(&score, 0).ties[0].dotted,
        "a dotted tie reconstructs dotted = true"
    );
}

#[test]
fn slur_round_trips_and_reconstructs_attachment() {
    use crate::model::SlurRole;
    let abc = "X:1\nT:Slur\nM:4/4\nL:1/4\nK:C\n(C D) z2 |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<slur type=\"start\" number=\"1\"/>"),
        "precondition: a slur emits number=1"
    );
    let score = assert_idempotent_s4(abc);
    let start = &attachments_at(&score, 0).slurs;
    assert_eq!(start.len(), 1);
    assert_eq!(start[0].role, SlurRole::Start);
    let stop = &attachments_at(&score, 1).slurs;
    assert_eq!(stop[0].role, SlurRole::Stop);
    // pair_id is chosen so the writer's SlurNumbers re-derives number=1.
    assert_eq!(
        start[0].pair_id, stop[0].pair_id,
        "a slur pair shares pair_id"
    );
}

#[test]
fn nested_slurs_reconstruct_distinct_numbers() {
    // (C (D E) F): outer slur is number 1, inner is number 2. The reader must
    // assign distinct pair_ids so the writer re-derives 1 (outer) and 2 (inner).
    let abc = "X:1\nT:Nest\nM:4/4\nL:1/4\nK:C\n(C (D E) F) |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<slur type=\"start\" number=\"1\"/>")
            && x1.contains("<slur type=\"start\" number=\"2\"/>"),
        "precondition: nested slurs emit numbers 1 and 2"
    );
    let score = assert_idempotent_s4(abc);
    // The outer start (note 0) and inner start (note 1) must have different
    // pair_ids, else they would collide on re-emission.
    let outer = attachments_at(&score, 0).slurs[0].pair_id;
    let inner = attachments_at(&score, 1).slurs[0].pair_id;
    assert_ne!(
        outer, inner,
        "overlapping slurs must reconstruct distinct pair_ids"
    );
}

#[test]
fn dotted_slur_reconstructs_line_type() {
    let abc = "X:1\nT:DotSlur\nM:4/4\nL:1/4\nK:C\n.(C D.) z2 |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<slur type=\"start\" number=\"1\" line-type=\"dotted\"/>"),
        "precondition: dotted slur emits line-type=\"dotted\""
    );
    let score = assert_idempotent_s4(abc);
    assert!(attachments_at(&score, 0).slurs[0].dotted);
}

#[test]
fn triplet_round_trips_and_reconstructs_tuplet() {
    // (3CDE is a 3:2 triplet of eighths under L:1/8: the first note carries a
    // TupletRole::Start, the middle a Continue (only <time-modification>, no
    // <tuplet>), the last a Stop. Every member emits <time-modification>.
    use crate::model::TupletRole;
    let abc = "X:1\nT:Trip\nM:4/4\nL:1/8\nK:C\n(3CDE A2 z2 |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<tuplet type=\"start\" number=\"1\"/>")
            && x1.contains("<actual-notes>3</actual-notes>")
            && x1.contains("<normal-notes>2</normal-notes>"),
        "precondition: triplet emits start tuplet + 3:2 time-modification"
    );
    let score = assert_idempotent_s4(abc);
    let start = &attachments_at(&score, 0).tuplets;
    assert_eq!(start.len(), 1, "the first triplet note has one tuplet");
    assert_eq!(start[0].role, TupletRole::Start);
    assert_eq!(start[0].actual_notes, 3);
    assert_eq!(start[0].normal_notes, 2);
    // The middle note carries a Continue (time-modification only).
    assert_eq!(
        attachments_at(&score, 1).tuplets[0].role,
        TupletRole::Continue
    );
    assert_eq!(attachments_at(&score, 2).tuplets[0].role, TupletRole::Stop);
}

#[test]
fn quintuplet_reconstructs_ratio() {
    // (5 under 4/4, L:1/8: a 5:2 tuplet (abc2xml's default q for 5 in simple
    // time). The exact ratio must reconstruct from <time-modification>.
    let abc = "X:1\nT:Quint\nM:4/4\nL:1/8\nK:C\n(5CDEFG z3 |\n";
    let x1 = export(abc);
    let score = assert_idempotent_s4(abc);
    let start = &attachments_at(&score, 0).tuplets[0];
    // Whatever ratio the writer chose, the reconstruction reproduces it.
    let actual = start.actual_notes;
    let normal = start.normal_notes;
    assert!(
        x1.contains(&format!("<actual-notes>{actual}</actual-notes>"))
            && x1.contains(&format!("<normal-notes>{normal}</normal-notes>")),
        "reconstructed tuplet ratio {actual}:{normal} must match the emitted time-modification"
    );
}

#[test]
fn two_separate_tuplets_in_a_measure_round_trip() {
    // Two consecutive triplets: both re-emit as number=1 (the second reuses the
    // freed number after the first stops). The reader must give them distinct
    // pair_ids so the active-set re-derivation reproduces number=1 each.
    let abc = "X:1\nT:TwoTrip\nM:4/4\nL:1/8\nK:C\n(3CDE (3FGA z2 |\n";
    let score = assert_idempotent_s4(abc);
    let first = attachments_at(&score, 0).tuplets[0].pair_id;
    let second = attachments_at(&score, 3).tuplets[0].pair_id;
    assert_ne!(first, second, "separate tuplets get distinct pair_ids");
}

#[test]
fn staccato_articulation_round_trips() {
    use crate::model::DecorationSourceKind;
    let abc = "X:1\nT:Stac\nM:4/4\nL:1/4\nK:C\n.C D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<articulations>") && x1.contains("<staccato/>"),
        "precondition: . emits <staccato/>"
    );
    let score = assert_idempotent_s4(abc);
    let decos = &attachments_at(&score, 0).decorations;
    assert_eq!(decos.len(), 1, "one decoration on the first note");
    // The reconstructed name must re-map to <staccato/> via decoration_notation.
    assert_eq!(decos[0].name, "staccato");
    assert_eq!(decos[0].source_kind, DecorationSourceKind::Named);
}

#[test]
fn accent_articulation_round_trips() {
    let abc = "X:1\nT:Acc\nM:4/4\nL:1/4\nK:C\n!>!C D E F |\n";
    let score = assert_idempotent_s4(abc);
    assert_eq!(attachments_at(&score, 0).decorations[0].name, "accent");
}

#[test]
fn foreign_extended_articulations_survive_abc_projection() {
    let xml = r#"<?xml version="1.0"?>
<score-partwise version="3.1">
  <part-list>
    <score-part id="P1">
      <part-name>Part</part-name>
    </score-part>
  </part-list>
  <part id="P1">
    <measure number="1">
      <attributes>
        <divisions>4</divisions>
        <key><fifths>0</fifths></key>
        <time><beats>4</beats><beat-type>4</beat-type></time>
        <clef><sign>G</sign><line>2</line></clef>
      </attributes>
      <note>
        <rest/>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><articulations><caesura/></articulations></notations>
      </note>
      <note>
        <pitch><step>D</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><articulations><detached-legato/></articulations></notations>
      </note>
      <note>
        <pitch><step>E</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><articulations><falloff/></articulations></notations>
      </note>
      <note>
        <pitch><step>F</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><articulations><doit/></articulations></notations>
      </note>
    </measure>
  </part>
</score-partwise>"#;
    let report = read_musicxml(xml);
    assert!(
        !report
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.code == "musicxml.read.unsupported_notation"),
        "extended articulations must read without unsupported-notation diagnostics: {:?}",
        report.diagnostics
    );
    let score = report.value;
    let expected = ["caesura", "detached-legato", "falloff", "doit"];
    for (index, name) in expected.iter().enumerate() {
        assert!(
            attachments_at(&score, index)
                .decorations
                .iter()
                .any(|decoration| decoration.name == *name),
            "{name} should survive in the reconstructed model"
        );
    }

    let direct_xml = write_score_partwise(&score).value;
    for tag in expected {
        assert!(
            direct_xml.contains(&format!("<{tag}/>")),
            "{tag} should re-emit directly after MusicXML read:\n{direct_xml}"
        );
    }

    let abc = write_abc(&score, AbcWriteOptions::default());
    for name in expected {
        assert!(
            abc.contains(&format!("!{name}!")),
            "{name} should survive in the ABC projection:\n{abc}"
        );
    }
    let roundtrip = export_musicxml(&abc)
        .expect("ABC projection of extended articulations should export")
        .musicxml;
    for tag in expected {
        assert!(
            roundtrip.contains(&format!("<{tag}/>")),
            "{tag} should survive MusicXML -> ABC -> MusicXML:\n{roundtrip}"
        );
    }
}

#[test]
fn foreign_cross_voice_slur_round_trips_through_xvoice_carrier() {
    // A slur whose start is in voice 1 and stop is in voice 2 (across a
    // `<backup>`) cannot be spelled with ABC `(`/`)`, which pair within one
    // `V:` stream. croma carries each end on `[I:croma-xvoice-slur]` so the
    // cross-voice `<slur>` survives MusicXML -> ABC -> MusicXML. (pdmx_0998.)
    let xml = r#"<?xml version="1.0"?>
<score-partwise version="3.1">
  <part-list>
    <score-part id="P1"><part-name>Part</part-name></score-part>
  </part-list>
  <part id="P1">
    <measure number="1">
      <attributes>
        <divisions>1</divisions>
        <key><fifths>0</fifths></key>
        <time><beats>2</beats><beat-type>4</beat-type></time>
      </attributes>
      <note>
        <pitch><step>C</step><octave>5</octave></pitch>
        <duration>1</duration><voice>1</voice><type>quarter</type>
        <notations><slur type="start" number="1"/></notations>
      </note>
      <note>
        <pitch><step>D</step><octave>5</octave></pitch>
        <duration>1</duration><voice>1</voice><type>quarter</type>
      </note>
      <backup><duration>2</duration></backup>
      <note>
        <pitch><step>E</step><octave>4</octave></pitch>
        <duration>1</duration><voice>2</voice><type>quarter</type>
      </note>
      <note>
        <pitch><step>F</step><octave>4</octave></pitch>
        <duration>1</duration><voice>2</voice><type>quarter</type>
        <notations><slur type="stop" number="1"/></notations>
      </note>
    </measure>
  </part>
</score-partwise>
"#;

    // Reader reads the cross-voice slur into the model (both ends).
    let score = read_musicxml(xml).value;

    // ABC projection carries each end as `[I:croma-xvoice-slur]` instead of a
    // `(`/`)` that would mis-pair within a single voice.
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert_eq!(
        abc.matches("[I:croma-xvoice-slur").count(),
        2,
        "both cross-voice slur ends must ride a carrier:\n{abc}"
    );
    assert!(abc.contains("role=start"), "start carrier missing:\n{abc}");
    assert!(abc.contains("role=stop"), "stop carrier missing:\n{abc}");

    // ABC -> MusicXML re-export reconstructs the cross-voice `<slur>`.
    let roundtrip = export_musicxml(&abc)
        .expect("cross-voice slur ABC should export")
        .musicxml;
    assert_eq!(count(&roundtrip, "<slur type=\"start\""), 1);
    assert_eq!(count(&roundtrip, "<slur type=\"stop\""), 1);
    let c = note_with_step(&roundtrip, "C");
    let f = note_with_step(&roundtrip, "F");
    assert!(
        c.contains("<slur type=\"start\"") && c.contains("<voice>1</voice>"),
        "slur start must re-emit on C in voice 1:\n{c}"
    );
    assert!(
        f.contains("<slur type=\"stop\"") && f.contains("<voice>2</voice>"),
        "slur stop must re-emit on F in voice 2:\n{f}"
    );
}

/// Count of `needle` in `haystack`.
fn count(haystack: &str, needle: &str) -> usize {
    haystack.matches(needle).count()
}

/// The `<note>...</note>` block whose pitch carries `<step>{step}</step>`.
fn note_with_step<'a>(xml: &'a str, step: &str) -> &'a str {
    let needle = format!("<step>{step}</step>");
    let at = xml
        .find(&needle)
        .unwrap_or_else(|| panic!("no note with step {step}"));
    let start = xml[..at].rfind("<note").expect("step inside a note");
    let end = xml[at..].find("</note>").expect("note closes") + at + "</note>".len();
    &xml[start..end]
}

#[test]
fn foreign_tremolos_survive_abc_projection() {
    let xml = r#"<?xml version="1.0"?>
<score-partwise version="3.1">
  <part-list>
    <score-part id="P1">
      <part-name>Part</part-name>
    </score-part>
  </part-list>
  <part id="P1">
    <measure number="1">
      <attributes>
        <divisions>4</divisions>
        <key><fifths>0</fifths></key>
        <time><beats>4</beats><beat-type>4</beat-type></time>
        <clef><sign>G</sign><line>2</line></clef>
      </attributes>
      <note>
        <pitch><step>C</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><ornaments><tremolo type="single">2</tremolo></ornaments></notations>
      </note>
      <note>
        <pitch><step>D</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><ornaments><tremolo type="start">3</tremolo></ornaments></notations>
      </note>
      <note>
        <pitch><step>E</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><ornaments><tremolo type="stop">3</tremolo></ornaments></notations>
      </note>
      <note>
        <pitch><step>F</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><ornaments><tremolo type="single">1</tremolo></ornaments></notations>
      </note>
    </measure>
  </part>
</score-partwise>"#;
    let report = read_musicxml(xml);
    assert!(
        !report
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.code == "musicxml.read.unsupported_notation"),
        "tremolos must read without unsupported-notation diagnostics: {:?}",
        report.diagnostics
    );
    let score = report.value;
    let expected = [
        ("musicxml-tremolo-single-2", "single", "2"),
        ("musicxml-tremolo-start-3", "start", "3"),
        ("musicxml-tremolo-stop-3", "stop", "3"),
        ("musicxml-tremolo-single-1", "single", "1"),
    ];
    for (index, (name, _, _)) in expected.iter().enumerate() {
        assert!(
            attachments_at(&score, index)
                .decorations
                .iter()
                .any(|decoration| decoration.name == *name),
            "{name} should survive in the reconstructed model"
        );
    }

    let direct_xml = write_score_partwise(&score).value;
    for (_, tremolo_type, marks) in expected.iter() {
        assert!(
            direct_xml.contains(&format!(
                "<tremolo type=\"{tremolo_type}\">{marks}</tremolo>"
            )),
            "{tremolo_type} tremolo with {marks} marks should re-emit directly after MusicXML read:\n{direct_xml}"
        );
    }

    let abc = write_abc(&score, AbcWriteOptions::default());
    for (name, _, _) in expected.iter() {
        assert!(
            abc.contains(&format!("!{name}!")),
            "{name} should survive in the ABC projection:\n{abc}"
        );
    }
    let roundtrip = export_musicxml(&abc)
        .expect("ABC projection of tremolo carriers should export")
        .musicxml;
    for (_, tremolo_type, marks) in expected.iter() {
        assert!(
            roundtrip.contains(&format!(
                "<tremolo type=\"{tremolo_type}\">{marks}</tremolo>"
            )),
            "{tremolo_type} tremolo with {marks} marks should survive MusicXML -> ABC -> MusicXML:\n{roundtrip}"
        );
    }
}

#[test]
fn foreign_measured_tremolo_time_modification_survives_abc_projection() {
    // A two-note (measured) tremolo carries a bare `<time-modification>` on each
    // note (the written value is double the sounding) with NO `<tuplet>`. The
    // ratio is not derivable from the tremolo marks alone, so the reader carries
    // it alongside the tremolo decoration and the writer re-emits it (PDMX 0677 /
    // 0761 / 1561).
    let xml = r#"<?xml version="1.0"?>
<score-partwise version="3.1">
  <part-list><score-part id="P1"><part-name>P</part-name></score-part></part-list>
  <part id="P1">
    <measure number="1">
      <attributes><divisions>4</divisions><time><beats>2</beats><beat-type>4</beat-type></time></attributes>
      <note>
        <pitch><step>C</step><octave>4</octave></pitch>
        <duration>4</duration><voice>1</voice><type>half</type>
        <time-modification><actual-notes>2</actual-notes><normal-notes>1</normal-notes></time-modification>
        <notations><ornaments><tremolo type="start">2</tremolo></ornaments></notations>
      </note>
      <note>
        <pitch><step>E</step><octave>4</octave></pitch>
        <duration>4</duration><voice>1</voice><type>half</type>
        <time-modification><actual-notes>2</actual-notes><normal-notes>1</normal-notes></time-modification>
        <notations><ornaments><tremolo type="stop">2</tremolo></ornaments></notations>
      </note>
    </measure>
  </part>
</score-partwise>"#;
    let score = read_musicxml(xml).value;
    let abc = write_abc(&score, AbcWriteOptions::default());
    let roundtrip = export_musicxml(&abc)
        .expect("measured-tremolo ABC should export")
        .musicxml;
    assert_eq!(
        roundtrip
            .matches("<tremolo type=\"start\">2</tremolo>")
            .count()
            + roundtrip
                .matches("<tremolo type=\"stop\">2</tremolo>")
                .count(),
        2,
        "both tremolo brackets must survive:\n{roundtrip}"
    );
    assert_eq!(
        roundtrip.matches("<actual-notes>2</actual-notes>").count(),
        2,
        "both tremolo notes must keep their 2:1 time-modification:\n{roundtrip}"
    );
    assert_eq!(
        roundtrip.matches("<normal-notes>1</normal-notes>").count(),
        2,
        "both tremolo notes must keep their 2:1 time-modification:\n{roundtrip}"
    );
}

#[test]
fn foreign_technical_values_survive_abc_projection() {
    let xml = r#"<?xml version="1.0"?>
<score-partwise version="3.1">
  <part-list>
    <score-part id="P1">
      <part-name>Part</part-name>
    </score-part>
  </part-list>
  <part id="P1">
    <measure number="1">
      <attributes>
        <divisions>4</divisions>
        <key><fifths>0</fifths></key>
        <time><beats>4</beats><beat-type>4</beat-type></time>
        <clef><sign>G</sign><line>2</line></clef>
      </attributes>
      <note>
        <pitch><step>C</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><technical><string>4</string><fret>11</fret></technical></notations>
      </note>
      <note>
        <pitch><step>D</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><technical><fingering>E</fingering></technical></notations>
      </note>
      <note>
        <pitch><step>E</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><technical><fingering>1
2
-</fingering></technical></notations>
      </note>
      <note>
        <pitch><step>F</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><technical><string>1</string></technical></notations>
      </note>
    </measure>
  </part>
</score-partwise>"#;
    let report = read_musicxml(xml);
    assert!(
        !report.diagnostics.iter().any(|diagnostic| {
            diagnostic.code == "musicxml.read.unsupported_notation"
                || diagnostic.code == "musicxml.read.unsupported_fingering"
        }),
        "technical values must read without unsupported-notation diagnostics: {:?}",
        report.diagnostics
    );
    let score = report.value;
    let expected = [
        (0, "musicxml-tech-string-4"),
        (0, "musicxml-tech-fret-11"),
        (1, "musicxml-tech-fingering-hex-45"),
        (2, "musicxml-tech-fingering-hex-310a320a2d"),
        (3, "musicxml-tech-string-1"),
    ];
    for (index, name) in expected {
        assert!(
            attachments_at(&score, index)
                .decorations
                .iter()
                .any(|decoration| decoration.name == name),
            "{name} should survive in the reconstructed model"
        );
    }

    let direct_xml = write_score_partwise(&score).value;
    for tag in [
        "<string>4</string>",
        "<fret>11</fret>",
        "<fingering>E</fingering>",
        "<fingering>1\n2\n-</fingering>",
        "<string>1</string>",
    ] {
        assert!(
            direct_xml.contains(tag),
            "{tag} should re-emit directly after MusicXML read:\n{direct_xml}"
        );
    }

    let abc = write_abc(&score, AbcWriteOptions::default());
    for (_, name) in expected {
        assert!(
            abc.contains(&format!("!{name}!")),
            "{name} should survive in the ABC projection:\n{abc}"
        );
    }
    let roundtrip = export_musicxml(&abc)
        .expect("ABC projection of technical carriers should export")
        .musicxml;
    for tag in [
        "<string>4</string>",
        "<fret>11</fret>",
        "<fingering>E</fingering>",
        "<fingering>1\n2\n-</fingering>",
        "<string>1</string>",
    ] {
        assert!(
            roundtrip.contains(tag),
            "{tag} should survive MusicXML -> ABC -> MusicXML:\n{roundtrip}"
        );
    }
}

#[test]
fn foreign_spanner_notations_survive_abc_projection() {
    let xml = r#"<?xml version="1.0"?>
<score-partwise version="3.1">
  <part-list>
    <score-part id="P1">
      <part-name>Part</part-name>
    </score-part>
  </part-list>
  <part id="P1">
    <measure number="1">
      <attributes>
        <divisions>4</divisions>
        <key><fifths>0</fifths></key>
        <time><beats>6</beats><beat-type>4</beat-type></time>
        <clef><sign>G</sign><line>2</line></clef>
      </attributes>
      <note>
        <pitch><step>C</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><glissando line-type="wavy" number="1" type="start">gliss.</glissando></notations>
      </note>
      <note>
        <pitch><step>D</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><glissando line-type="wavy" number="1" type="stop"/></notations>
      </note>
      <note>
        <pitch><step>E</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><slide line-type="solid" number="1" type="start">gliss.</slide></notations>
      </note>
      <note>
        <pitch><step>F</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><slide line-type="solid" number="1" type="stop"/></notations>
      </note>
      <note>
        <pitch><step>G</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
        <notations><ornaments><wavy-line type="start" number="1"/><wavy-line type="stop" number="1"/></ornaments></notations>
      </note>
      <note>
        <pitch><step>A</step><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>quarter</type>
      </note>
    </measure>
  </part>
</score-partwise>"#;
    let report = read_musicxml(xml);
    assert!(
        !report
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.code == "musicxml.read.unsupported_notation"),
        "spanner notations must read without unsupported-notation diagnostics: {:?}",
        report.diagnostics
    );
    let score = report.value;
    let expected = [
        (
            0,
            "musicxml-glissando-start-wavy-1-hex-676c6973732e",
            "<glissando type=\"start\" number=\"1\" line-type=\"wavy\">gliss.</glissando>",
        ),
        (
            1,
            "musicxml-glissando-stop-wavy-1",
            "<glissando type=\"stop\" number=\"1\" line-type=\"wavy\"/>",
        ),
        (
            2,
            "musicxml-slide-start-solid-1-hex-676c6973732e",
            "<slide type=\"start\" number=\"1\" line-type=\"solid\">gliss.</slide>",
        ),
        (
            3,
            "musicxml-slide-stop-solid-1",
            "<slide type=\"stop\" number=\"1\" line-type=\"solid\"/>",
        ),
        (
            4,
            "musicxml-wavy-line-start-1",
            "<wavy-line type=\"start\" number=\"1\"/>",
        ),
        (
            4,
            "musicxml-wavy-line-stop-1",
            "<wavy-line type=\"stop\" number=\"1\"/>",
        ),
    ];
    for (index, name, _) in expected {
        assert!(
            attachments_at(&score, index)
                .decorations
                .iter()
                .any(|decoration| decoration.name == name),
            "{name} should survive in the reconstructed model"
        );
    }

    let direct_xml = write_score_partwise(&score).value;
    for (_, _, tag) in expected {
        assert!(
            direct_xml.contains(tag),
            "{tag} should re-emit directly after MusicXML read:\n{direct_xml}"
        );
    }

    let abc = write_abc(&score, AbcWriteOptions::default());
    for (_, name, _) in expected {
        assert!(
            abc.contains(&format!("!{name}!")),
            "{name} should survive in the ABC projection:\n{abc}"
        );
    }
    let roundtrip = export_musicxml(&abc)
        .expect("ABC projection of spanner carriers should export")
        .musicxml;
    for (_, _, tag) in expected {
        assert!(
            roundtrip.contains(tag),
            "{tag} should survive MusicXML -> ABC -> MusicXML:\n{roundtrip}"
        );
    }
}

#[test]
fn foreign_tuplet_display_survives_abc_projection() {
    let xml = r#"<?xml version="1.0"?>
<score-partwise version="3.1">
  <part-list>
    <score-part id="P1">
      <part-name>Part</part-name>
    </score-part>
  </part-list>
  <part id="P1">
    <measure number="1">
      <attributes>
        <divisions>4</divisions>
        <key><fifths>0</fifths></key>
        <time><beats>4</beats><beat-type>4</beat-type></time>
        <clef><sign>G</sign><line>2</line></clef>
      </attributes>
      <note>
        <pitch><step>D</step><alter>-1</alter><octave>4</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>half</type>
        <time-modification>
          <actual-notes>4</actual-notes>
          <normal-notes>2</normal-notes>
        </time-modification>
        <notations>
          <tuplet type="start" bracket="yes">
            <tuplet-actual>
              <tuplet-number>2</tuplet-number>
              <tuplet-type>quarter</tuplet-type>
            </tuplet-actual>
            <tuplet-normal>
              <tuplet-number>2</tuplet-number>
              <tuplet-type>quarter</tuplet-type>
            </tuplet-normal>
          </tuplet>
        </notations>
      </note>
      <note>
        <pitch><step>A</step><alter>-1</alter><octave>3</octave></pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>half</type>
        <time-modification>
          <actual-notes>4</actual-notes>
          <normal-notes>2</normal-notes>
        </time-modification>
        <notations><tuplet type="stop"/></notations>
      </note>
    </measure>
  </part>
</score-partwise>"#;
    let report = read_musicxml(xml);
    let score = report.value;
    let carrier = "musicxml-tuplet-detail-v1-byes-a2-quarter-0-n2-quarter-0";
    assert!(
        attachments_at(&score, 0)
            .decorations
            .iter()
            .any(|decoration| decoration.name == carrier),
        "tuplet display carrier should survive in the reconstructed model"
    );

    let expected = [
        "<tuplet type=\"start\" bracket=\"yes\">",
        "<tuplet-actual>",
        "<tuplet-number>2</tuplet-number>",
        "<tuplet-type>quarter</tuplet-type>",
        "<tuplet-normal>",
    ];
    let direct_xml = write_score_partwise(&score).value;
    for tag in expected {
        assert!(
            direct_xml.contains(tag),
            "{tag} should re-emit directly after MusicXML read:\n{direct_xml}"
        );
    }

    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains(&format!("!{carrier}!")),
        "carrier should survive in the ABC projection:\n{abc}"
    );
    let roundtrip = export_musicxml(&abc)
        .expect("ABC projection of tuplet display carrier should export")
        .musicxml;
    for tag in expected {
        assert!(
            roundtrip.contains(tag),
            "{tag} should survive MusicXML -> ABC -> MusicXML:\n{roundtrip}"
        );
    }
}

#[test]
fn foreign_display_tuplet_without_time_modification_emits_no_ratio() {
    // A `<tuplet>` bracket with NO `<time-modification>` is a display-only group:
    // the notes already fill their nominal duration (no time compression). The
    // reader must not fabricate a ratio (it formerly assumed 3:2), so the round
    // trip keeps the bracket but emits no `<time-modification>` (PDMX 0998 / 1479).
    let xml = r#"<?xml version="1.0"?>
<score-partwise>
  <part-list><score-part id="P1"><part-name>P</part-name></score-part></part-list>
  <part id="P1">
    <measure number="1">
      <attributes><divisions>4</divisions><time><beats>1</beats><beat-type>4</beat-type></time></attributes>
      <note><pitch><step>C</step><octave>5</octave></pitch><duration>1</duration><voice>1</voice><type>16th</type>
        <notations><tuplet type="start" bracket="no"/></notations></note>
      <note><pitch><step>D</step><octave>5</octave></pitch><duration>1</duration><voice>1</voice><type>16th</type></note>
      <note><pitch><step>E</step><octave>5</octave></pitch><duration>1</duration><voice>1</voice><type>16th</type></note>
      <note><pitch><step>F</step><octave>5</octave></pitch><duration>1</duration><voice>1</voice><type>16th</type>
        <notations><tuplet type="stop"/></notations></note>
    </measure>
  </part>
</score-partwise>"#;
    let score = read_musicxml(xml).value;
    let abc = write_abc(&score, AbcWriteOptions::default());
    let roundtrip = export_musicxml(&abc)
        .expect("display-tuplet ABC should export")
        .musicxml;
    assert!(
        !roundtrip.contains("<time-modification>"),
        "a display-only tuplet must not fabricate a <time-modification>:\n{roundtrip}"
    );
    assert!(
        roundtrip.contains("<tuplet type=\"start\"") && roundtrip.contains("<tuplet type=\"stop\""),
        "the display tuplet bracket must survive:\n{roundtrip}"
    );
    assert_eq!(
        roundtrip.matches("<type>16th</type>").count(),
        4,
        "all four 16th notes must keep their literal value:\n{roundtrip}"
    );
}

#[test]
fn trill_ornament_round_trips() {
    let abc = "X:1\nT:Tr\nM:4/4\nL:1/4\nK:C\n!trill!C D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<ornaments>") && x1.contains("<trill-mark/>"),
        "precondition: !trill! emits <trill-mark/>"
    );
    let score = assert_idempotent_s4(abc);
    assert_eq!(attachments_at(&score, 0).decorations[0].name, "trill");
}

#[test]
fn mordent_ornament_round_trips() {
    let abc = "X:1\nT:Mord\nM:4/4\nL:1/4\nK:C\n!mordent!C D E F |\n";
    let score = assert_idempotent_s4(abc);
    // `mordent` and `lowermordent` both emit <mordent/>; the canonical inverse
    // is the name that re-emits identically.
    assert_eq!(attachments_at(&score, 0).decorations[0].name, "mordent");
}

#[test]
fn fermata_round_trips() {
    let abc = "X:1\nT:Ferm\nM:4/4\nL:1/4\nK:C\n!fermata!C D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<fermata type=\"upright\"/>"),
        "precondition: !fermata! emits <fermata type=\"upright\"/>"
    );
    let score = assert_idempotent_s4(abc);
    assert_eq!(attachments_at(&score, 0).decorations[0].name, "fermata");
}

#[test]
fn inverted_fermata_round_trips() {
    let abc = "X:1\nT:IFerm\nM:4/4\nL:1/4\nK:C\n!invertedfermata!C D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<fermata type=\"inverted\"/>"),
        "precondition: inverted fermata emits type=\"inverted\""
    );
    let score = assert_idempotent_s4(abc);
    assert_eq!(
        attachments_at(&score, 0).decorations[0].name,
        "invertedfermata"
    );
}

#[test]
fn upbow_technical_round_trips() {
    let abc = "X:1\nT:Up\nM:4/4\nL:1/4\nK:C\n!upbow!C D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<technical>") && x1.contains("<up-bow/>"),
        "precondition: !upbow! emits <up-bow/>"
    );
    let score = assert_idempotent_s4(abc);
    assert_eq!(attachments_at(&score, 0).decorations[0].name, "upbow");
}

#[test]
fn fingering_technical_text_round_trips() {
    // !1! is a fingering -> <technical><fingering>1</fingering></technical>; the
    // reader must reconstruct the decoration whose name re-emits the text element.
    let abc = "X:1\nT:Fing\nM:4/4\nL:1/4\nK:C\n!1!C D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<fingering>1</fingering>"),
        "precondition: !1! emits <fingering>1</fingering>"
    );
    let score = assert_idempotent_s4(abc);
    assert_eq!(attachments_at(&score, 0).decorations[0].name, "1");
}

#[test]
fn arpeggio_round_trips() {
    let abc = "X:1\nT:Arp\nM:4/4\nL:1/4\nK:C\n!arpeggio![CEG] z2 z |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<arpeggiate/>"),
        "precondition: !arpeggio! emits <arpeggiate/>"
    );
    let score = assert_idempotent_s4(abc);
    // The arpeggiate decoration attaches to the chord's first member (event 0).
    assert_eq!(attachments_at(&score, 0).decorations[0].name, "arpeggio");
}

#[test]
fn multiple_decorations_on_one_note_round_trip() {
    // A note can carry an ornament AND an articulation AND a fermata; the writer
    // groups them per category in schema order, and the reader must reconstruct
    // every one so the whole grouped block re-emits identically.
    let abc = "X:1\nT:Multi\nM:4/4\nL:1/4\nK:C\n!trill!.!fermata!C D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<trill-mark/>")
            && x1.contains("<staccato/>")
            && x1.contains("<fermata type=\"upright\"/>"),
        "precondition: all three notations are emitted"
    );
    let score = assert_idempotent_s4(abc);
    let names: Vec<&str> = attachments_at(&score, 0)
        .decorations
        .iter()
        .map(|d| d.name.as_str())
        .collect();
    assert!(names.contains(&"trill"));
    assert!(names.contains(&"staccato"));
    assert!(names.contains(&"fermata"));
}

#[test]
fn beams_are_derived_not_stored_and_round_trip() {
    // The model has NO beam field; the writer derives beaming purely from note
    // durations/positions (in fact croma's writer emits no <beam> element at
    // all โ€” beaming is left implicit). Reading the S1 notes correctly therefore
    // makes any beam behaviour round-trip with ZERO beam-specific reader code.
    // This test pins that: consecutive eighths (which are beamed when rendered)
    // round-trip byte-for-byte, and the writer emits no <beam> we failed to read.
    let abc = "X:1\nT:Beam\nM:4/4\nL:1/8\nK:C\nCDEF GABc |\n";
    let x1 = export(abc);
    assert!(
        !x1.contains("<beam"),
        "precondition: croma's writer derives beams and emits no <beam> element"
    );
    assert_idempotent_s4(abc);
}

#[test]
fn derived_time_modification_creates_no_tuplet_attachment() {
    // `C2/3` is a 1/6-of-a-beat note: the writer SYNTHESISES a 3:2
    // <time-modification> from the odd duration alone (no <tuplet>, no
    // <notations>), exactly like a derived beam. The reader must NOT fabricate a
    // tuplet attachment here โ€” S1's duration reconstruction already re-emits the
    // identical <time-modification>. Proves the open-tuplet logic ignores
    // tuplet-less time-modifications.
    let abc = "X:1\nT:Odd\nM:4/4\nL:1/4\nK:C\nC2/3 D2/3 E2/3 z |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<time-modification>") && !x1.contains("<tuplet"),
        "precondition: an odd duration emits a derived time-modification with no <tuplet>"
    );
    let score = assert_idempotent_s4(abc);
    assert!(
        attachments_at(&score, 0).tuplets.is_empty(),
        "a derived time-modification must NOT reconstruct a tuplet attachment"
    );
}

#[test]
fn notation_and_tuplet_combine_round_trip() {
    // A triplet whose first note also carries a slur start and a staccato: ties
    // the tuplet/time-modification path together with the decoration grouping in
    // one note, proving the combined <notations> block re-emits in order.
    let abc = "X:1\nT:Combo\nM:4/4\nL:1/8\nK:C\n(3.CDE (FG) z2 |\n";
    let score = assert_idempotent_s4(abc);
    // First note: a tuplet start AND a staccato decoration.
    assert_eq!(
        attachments_at(&score, 0).tuplets[0].role,
        crate::model::TupletRole::Start
    );
    assert!(
        attachments_at(&score, 0)
            .decorations
            .iter()
            .any(|d| d.name == "staccato"),
        "the first triplet note keeps its staccato"
    );
}

// --- Stage S4: nested-tuplet inverse (P2) ----------------------------------

#[test]
fn nested_tuplet_7_8_inner_3_2_round_trips_and_reconstructs_ratios() {
    // tune_003732 measure 5: outer (7:8:8) enclosing inner (3). The writer emits
    // the COMPOSITE 21/16 for the inner 3 notes and the OUTER 7:8 for the 5 tail
    // notes. The reader must decompose composite -> outer 7:8 + inner 3:2.
    use crate::model::TupletRole;
    // Minimal ABC that generates the same MusicXML structure as tune_003732's
    // nested-tuplet measure: outer 7:8, inner 3:2. [I:tuplets 2 0 2] forces
    // nested bracket display so the writer emits the composite 21/16.
    let abc = "X:1\nT:NestedTup\nM:4/4\nL:1/16\nK:C\n[I:tuplets 2 0 2](7:8:8(3AAA AAAAA|\n";
    let x1 = export(abc);
    // Precondition: the writer must emit the composite 21:16 for inner notes.
    assert!(
        x1.contains("<actual-notes>21</actual-notes>")
            && x1.contains("<normal-notes>16</normal-notes>"),
        "precondition: inner 3 notes carry composite 21:16 time-modification\ngot:\n{x1}"
    );
    // Precondition: the outer tail notes must carry 7:8.
    assert!(
        x1.contains("<actual-notes>7</actual-notes>")
            && x1.contains("<normal-notes>8</normal-notes>"),
        "precondition: outer 5 tail notes carry explicit 7:8 time-modification\ngot:\n{x1}"
    );
    // Full byte-identical idempotence: write(read(write(score))) == write(score).
    let score = assert_idempotent_s4(abc);
    // Direct ratio assertions on the reconstructed TupletAttachments.
    // Event 0 = first inner note: must carry BOTH outer (Start 7:8) and inner (Start 3:2).
    let ev0 = &attachments_at(&score, 0).tuplets;
    assert_eq!(ev0.len(), 2, "first inner note carries two tuplet starts");
    // Outer is the first (lower pair_id, opened first by writer).
    let outer_start = ev0
        .iter()
        .find(|t| t.role == TupletRole::Start && t.actual_notes == 7);
    let inner_start = ev0
        .iter()
        .find(|t| t.role == TupletRole::Start && t.actual_notes == 3);
    assert!(
        outer_start.is_some(),
        "outer tuplet start must have actual_notes=7; got: {ev0:?}"
    );
    assert!(
        inner_start.is_some(),
        "inner tuplet start must have actual_notes=3; got: {ev0:?}"
    );
    let outer_start = outer_start.expect("outer tuplet start present");
    let inner_start = inner_start.expect("inner tuplet start present");
    assert_eq!(outer_start.actual_notes, 7, "outer actual");
    assert_eq!(outer_start.normal_notes, 8, "outer normal");
    assert_eq!(inner_start.actual_notes, 3, "inner actual");
    assert_eq!(inner_start.normal_notes, 2, "inner normal");
    // Event 3 = first outer-tail note (after inner close): must carry exactly one
    // outer Continue with ratio 7:8.
    let ev3 = &attachments_at(&score, 3).tuplets;
    assert_eq!(ev3.len(), 1, "outer tail note has one tuplet continue");
    assert_eq!(ev3[0].role, TupletRole::Continue);
    assert_eq!(ev3[0].actual_notes, 7, "outer continue actual");
    assert_eq!(ev3[0].normal_notes, 8, "outer continue normal");
}

#[test]
fn single_tuplet_continue_does_not_panic() {
    // A plain (3 with no outer tuplet: exercises the normal Continue path
    // (middle notes with one open tuplet). Kept as a baseline sanity check
    // distinct from the nested-degenerate test below.
    let abc = "X:1\nT:SingleTup\nM:4/4\nL:1/8\nK:C\n(3ccc cccc z|\n";
    // Must not panic:
    let _score = assert_idempotent_s4(abc);
}

#[test]
fn nested_tuplet_zero_tail_notes_does_not_panic() {
    // Degenerate nested-tuplet path: an OUTER tuplet enclosing an INNER tuplet
    // that spans ALL of the outer's notes (zero outer-only tail notes after the
    // inner closes). The P2 recovery branch (which infers the outer ratio from a
    // tail note's `<time-modification>`) is unreachable because no continue note
    // with exactly one open tuplet ever exists. The reader must:
    //   - leave the composite ratio on every attachment (no recovery possible),
    //   - NOT panic.
    //
    // We use `[I:tuplets 2 0 2](3:2:3(3:2:3CCC` โ€” outer (3:2:3) immediately
    // wrapping inner (3:2:3). The writer emits composite 9/4 on all 3 notes;
    // note 3 carries both inner-stop (number 2) and outer-stop (number 1). No
    // continue note has `open.len()==1`, so the recovery block is never entered.
    //
    // NOTE: this case is deliberately NOT idempotent (the composite is left on
    // both levels since there is no tail note to recover the outer ratio from).
    // The contract here is only: no panic + the reader reads the composite as-is.
    use crate::model::TupletRole;
    let abc = "X:1\nT:ZeroTail\nM:4/4\nL:1/8\nK:C\n[I:tuplets 2 0 2](3:2:3(3:2:3CCC cccc z|\n";
    // Must not panic โ€” use round_trip directly, do NOT assert byte idempotence.
    let (_, _, score) = round_trip(abc);
    // The outer Start on note 0 carries the composite 9:4 (no recovery fired).
    let ev0 = &attachments_at(&score, 0).tuplets;
    let outer = ev0
        .iter()
        .find(|t| t.role == TupletRole::Start && t.actual_notes == 9);
    assert!(
        outer.is_some(),
        "outer start should carry composite 9:4 (no recovery); got: {ev0:?}"
    );
    // The inner Start on note 0 also carries 9:4 (composite, no recovery).
    let inner = ev0
        .iter()
        .find(|t| t.role == TupletRole::Start && t.normal_notes == 4);
    assert!(
        inner.is_some(),
        "inner start should carry composite 9:4 (no recovery); got: {ev0:?}"
    );
}

// --- Stage S5a: <direction> (tempo / dynamics / wedge / coda / segno / words) -

/// Assert FULL-byte idempotence on an S5a single-voice fixture. By S5a the writer
/// also emits the `<direction>` block (tempo `<metronome>`/`<words>`,
/// `<dynamics>`, `<wedge>`, `<coda>`/`<segno>`, and plain annotation `<words>`);
/// nothing in a single-voice direction fixture is deferred, so the whole document
/// must be byte-identical. Returns the reconstructed score for direct field
/// assertions.
fn assert_idempotent_s5(abc: &str) -> Score {
    let (x1, x2, score) = round_trip(abc);
    assert_eq!(
        x1, x2,
        "write(read(write(score))) must equal write(score) byte-for-byte (S5a directions)"
    );
    score
}

#[test]
fn header_tempo_numeric_reconstructs_tempo_model() {
    use crate::model::TempoBeat;
    // Q:1/4=90 -> a header <metronome> (quarter / 90) before the first note; the
    // reader must reconstruct metadata.tempo_model so write_initial_directions
    // re-emits the identical direction.
    let abc = "X:1\nT:Tempo\nQ:1/4=90\nM:4/4\nL:1/4\nK:C\nC D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<beat-unit>quarter</beat-unit>") && x1.contains("<per-minute>90</per-minute>"),
        "precondition: Q:1/4=90 emits a quarter metronome at 90"
    );
    let score = assert_idempotent_s5(abc);
    let tempo = score
        .metadata
        .tempo_model
        .as_ref()
        .expect("S5a must reconstruct the header <metronome> into metadata.tempo_model");
    assert_eq!(tempo.text, None, "a bare numeric tempo carries no words");
    assert_eq!(tempo.beat_role, TempoBeatRole::PrintedMetronome);
    assert_eq!(
        tempo.beat,
        Some(TempoBeat {
            beat_numerator: 1,
            beat_denominator: 4,
            bpm: 90,
        }),
        "the reconstructed beat must drive the same <beat-unit>/<per-minute>"
    );
}

#[test]
fn header_tempo_dotted_beat_unit_reconstructs() {
    use crate::model::TempoBeat;
    // Q:3/8=60 -> a DOTTED quarter metronome (<beat-unit>quarter</beat-unit>
    // <beat-unit-dot/>); the 3/(2^k) inverse must recover beat 3/8.
    let abc = "X:1\nT:Dotted\nQ:3/8=60\nM:6/8\nL:1/8\nK:C\nC2C2C2 |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<beat-unit-dot/>"),
        "precondition: Q:3/8=60 emits a dotted beat unit"
    );
    let score = assert_idempotent_s5(abc);
    assert_eq!(
        score.metadata.tempo_model.as_ref().and_then(|t| t.beat),
        Some(TempoBeat {
            beat_numerator: 3,
            beat_denominator: 8,
            bpm: 60,
        })
    );
    assert_eq!(
        score.metadata.tempo_model.as_ref().map(|t| t.beat_role),
        Some(TempoBeatRole::PrintedMetronome)
    );
}

#[test]
fn header_tempo_with_text_reconstructs_words_and_beat() {
    // Q:"Allegro" 1/4=120 -> a <words>Allegro</words> direction-type plus the
    // <metronome>; the reader must reconstruct BOTH tempo.text and tempo.beat so
    // the words and metronome direction-types re-emit in order.
    let abc = "X:1\nT:WithText\nQ:\"Allegro\" 1/4=120\nM:4/4\nL:1/4\nK:C\nC D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<words>Allegro</words>") && x1.contains("<per-minute>120</per-minute>"),
        "precondition: text+numeric tempo emits words AND metronome"
    );
    let score = assert_idempotent_s5(abc);
    let tempo = score.metadata.tempo_model.as_ref().expect("tempo_model");
    assert_eq!(tempo.text.as_deref(), Some("Allegro"));
    assert_eq!(tempo.beat.map(|b| b.bpm), Some(120));
    assert_eq!(tempo.beat_role, TempoBeatRole::PrintedMetronome);
}

#[test]
fn header_text_only_tempo_reconstructs_words_no_beat() {
    // Q:"Andante" with NO numeric tempo -> a voice-less <words> header
    // direction (no <metronome>). The reader must reconstruct a tempo_model with
    // text and beat=None so write_tempo_direction re-emits the words without a
    // synthetic default <sound tempo="120.00"/>, NOT a voice-bearing annotation
    // direction.
    let abc = "X:1\nT:TextTempo\nQ:\"Andante\"\nM:4/4\nL:1/4\nK:C\nC D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<words>Andante</words>")
            && !x1.contains("<sound tempo=\"120.00\"/>")
            && !x1.contains("<metronome>"),
        "precondition: a text-only tempo emits words only, no sound/metronome"
    );
    let score = assert_idempotent_s5(abc);
    let tempo = score
        .metadata
        .tempo_model
        .as_ref()
        .expect("a text-only tempo must reconstruct metadata.tempo_model");
    assert_eq!(tempo.text.as_deref(), Some("Andante"));
    assert_eq!(
        tempo.beat, None,
        "a text-only tempo carries no numeric beat"
    );
}

#[test]
fn mid_tune_tempo_change_reconstructs_event() {
    use crate::model::TimedEventKind;
    // A mid-tune [Q:1/4=160] becomes a TempoChange event emitted as a voice-less
    // tempo <direction> BETWEEN notes; the reader must reconstruct a
    // TimedEventKind::TempoChange at that onset (NOT the header tempo_model) so it
    // re-emits in the same inter-note position.
    let abc = "X:1\nT:MidTempo\nM:4/4\nL:1/4\nK:C\nC D [Q:1/4=160] E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<per-minute>160</per-minute>"),
        "precondition: the inline [Q:] emits a 160 metronome"
    );
    let score = assert_idempotent_s5(abc);
    assert!(
        score.metadata.tempo_model.is_none(),
        "no header Q: -> tempo_model stays None; the inline tempo is an event"
    );
    let tempo_changes: Vec<_> = score.parts[0].voices[0]
        .events
        .iter()
        .filter(|e| matches!(e.kind, TimedEventKind::TempoChange(_)))
        .collect();
    assert_eq!(
        tempo_changes.len(),
        1,
        "the inline [Q:] reconstructs exactly one TempoChange event"
    );
    let bpm = match &tempo_changes[0].kind {
        TimedEventKind::TempoChange(model) => model.beat.map(|b| b.bpm),
        _ => None,
    };
    assert_eq!(bpm, Some(160), "the TempoChange carries the 160 bpm");
}

#[test]
fn header_and_mid_tune_tempo_both_round_trip() {
    use crate::model::TimedEventKind;
    // Header Q: AND an inline [Q:] coexist: the leading metronome (before the
    // first note) is the header tempo_model; the inter-note one is a TempoChange.
    // Both must reconstruct so the two metronome directions re-emit in place.
    let abc = "X:1\nT:Both\nQ:1/4=90\nM:4/4\nL:1/4\nK:C\nC D [Q:1/4=160] E F |\n";
    let score = assert_idempotent_s5(abc);
    assert_eq!(
        score
            .metadata
            .tempo_model
            .as_ref()
            .and_then(|t| t.beat)
            .map(|b| b.bpm),
        Some(90),
        "the leading tempo is the header tempo_model (90)"
    );
    let mid: Vec<_> = score.parts[0].voices[0]
        .events
        .iter()
        .filter(|e| matches!(e.kind, TimedEventKind::TempoChange(_)))
        .collect();
    assert_eq!(mid.len(), 1, "exactly one inline TempoChange (160)");
}

#[test]
fn dynamic_forte_reconstructs_decoration() {
    use crate::model::DecorationSourceKind;
    // !f! -> a <direction placement="below"><dynamics><f/></dynamics> direction
    // (NOT a <notations> element); the reader must reconstruct a "f" decoration on
    // the following note so the dynamics direction re-emits.
    let abc = "X:1\nT:Forte\nM:4/4\nL:1/4\nK:C\n!f!C D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<dynamics>") && x1.contains("<f/>"),
        "precondition: !f! emits a <dynamics><f/> direction"
    );
    let score = assert_idempotent_s5(abc);
    let decos = &attachments_at(&score, 0).decorations;
    assert_eq!(decos.len(), 1, "one dynamic decoration on the first note");
    assert_eq!(decos[0].name, "f", "the reconstructed name re-emits <f/>");
    assert_eq!(decos[0].source_kind, DecorationSourceKind::Named);
}

#[test]
fn dynamic_pianissimo_reconstructs() {
    let abc = "X:1\nT:PP\nM:4/4\nL:1/4\nK:C\n!pp!C D E F |\n";
    let score = assert_idempotent_s5(abc);
    assert_eq!(attachments_at(&score, 0).decorations[0].name, "pp");
}

#[test]
fn dynamic_sforzando_reconstructs() {
    // !sfz! is the one dynamic whose ABC name differs from its <sfz/> element by
    // case only; ensure the inverse maps the element back to "sfz".
    let abc = "X:1\nT:SF\nM:4/4\nL:1/4\nK:C\n!sfz!C D E F |\n";
    let x1 = export(abc);
    assert!(x1.contains("<sfz/>"), "precondition: !sfz! emits <sfz/>");
    let score = assert_idempotent_s5(abc);
    assert_eq!(attachments_at(&score, 0).decorations[0].name, "sfz");
}

#[test]
fn extended_dynamics_reconstruct() {
    let abc = "X:1\nT:ExtendedDyn\nM:4/4\nL:1/4\nK:C\n!pppp!C !ffffff!D !fp!E !rf!F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<pppp/>")
            && x1.contains("<ffffff/>")
            && x1.contains("<fp/>")
            && x1.contains("<rf/>"),
        "precondition: extended ABC dynamics emit matching MusicXML dynamics"
    );
    let score = assert_idempotent_s5(abc);
    assert_eq!(attachments_at(&score, 0).decorations[0].name, "pppp");
    assert_eq!(attachments_at(&score, 1).decorations[0].name, "ffffff");
    assert_eq!(attachments_at(&score, 2).decorations[0].name, "fp");
    assert_eq!(attachments_at(&score, 3).decorations[0].name, "rf");
}

#[test]
fn crescendo_wedge_reconstructs_open_and_close() {
    // !<(! opens a crescendo wedge, !<)! closes it: two voice-bearing
    // <direction><wedge> elements. The reader must reconstruct a "crescendo("
    // decoration on the open note and a "crescendo)" on the close note so both
    // <wedge type="crescendo"/> and <wedge type="stop"/> re-emit.
    let abc = "X:1\nT:Cresc\nM:4/4\nL:1/4\nK:C\n!<(!C D!<)! E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<wedge type=\"crescendo\"/>") && x1.contains("<wedge type=\"stop\"/>"),
        "precondition: a crescendo hairpin emits crescendo + stop wedges"
    );
    let score = assert_idempotent_s5(abc);
    // The open wedge attaches to the first note. In ABC a decoration binds to the
    // FOLLOWING note, so `D!<)! E` places the close wedge before E (event 2): the
    // writer emits its <wedge type="stop"/> direction just before E's <note>.
    let open = &attachments_at(&score, 0).decorations;
    assert!(
        open.iter().any(|d| d.name == "crescendo("),
        "the open note carries a crescendo( decoration, got {:?}",
        open.iter().map(|d| &d.name).collect::<Vec<_>>()
    );
    let close = &attachments_at(&score, 2).decorations;
    assert!(
        close.iter().any(|d| d.name == "crescendo)"),
        "the note after the close marker carries a crescendo) decoration"
    );
}

#[test]
fn diminuendo_wedge_reconstructs() {
    let abc = "X:1\nT:Dim\nM:4/4\nL:1/4\nK:C\n!>(!C D!>)! E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<wedge type=\"diminuendo\"/>"),
        "precondition: !>(! emits a diminuendo wedge"
    );
    let score = assert_idempotent_s5(abc);
    assert!(
        attachments_at(&score, 0)
            .decorations
            .iter()
            .any(|d| d.name == "diminuendo(")
    );
}

#[test]
fn coda_reconstructs_decoration() {
    // !coda! -> a <direction placement="above"><coda/> (voice-bearing); the reader
    // reconstructs a "coda" decoration so write_direction_type re-emits <coda/>.
    let abc = "X:1\nT:Coda\nM:4/4\nL:1/4\nK:C\n!coda!C D E F |\n";
    let x1 = export(abc);
    assert!(x1.contains("<coda/>"), "precondition: !coda! emits <coda/>");
    let score = assert_idempotent_s5(abc);
    assert_eq!(attachments_at(&score, 0).decorations[0].name, "coda");
}

#[test]
fn segno_reconstructs_decoration() {
    let abc = "X:1\nT:Segno\nM:4/4\nL:1/4\nK:C\n!segno!C D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<segno/>"),
        "precondition: !segno! emits <segno/>"
    );
    let score = assert_idempotent_s5(abc);
    assert_eq!(attachments_at(&score, 0).decorations[0].name, "segno");
}

#[test]
fn pre_barline_segno_reconstructs_on_trailing_spacer() {
    use crate::model::TimedEventKind;
    // `d4 !segno!|` puts the !segno! before the barline with NO following note:
    // the writer flushes it onto a zero-duration Spacer event whose directions
    // emit after the last note. The reader must reconstruct that Spacer so the
    // trailing <segno/> direction re-emits at the end of the measure.
    let abc = "X:1\nT:Trail\nM:4/4\nL:1/4\nK:C\nC D E F !segno!|\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<segno/>"),
        "precondition: a pre-barline !segno! still emits <segno/>"
    );
    let score = assert_idempotent_s5(abc);
    // The last reconstructed event is a zero-duration Spacer carrying the segno.
    let events = &score.parts[0].voices[0].events;
    let last = events.last().expect("at least one event");
    assert!(
        matches!(last.kind, TimedEventKind::Spacer),
        "the trailing segno reconstructs on a Spacer event, got {:?}",
        last.kind
    );
    assert_eq!(
        last.duration,
        Fraction::zero(),
        "the Spacer is zero-duration"
    );
    assert!(
        last.attachments
            .decorations
            .iter()
            .any(|d| d.name == "segno"),
        "the trailing Spacer carries the segno decoration"
    );
}

#[test]
fn annotation_above_reconstructs_text_and_placement() {
    use crate::model::AnnotationPlacementModel;
    // "^Andante" is an above-placed annotation -> a <direction placement="above">
    // <words>Andante</words> (the writer strips the ^ prefix). The reader must
    // reconstruct a TextAttachment whose (text, placement) re-emits BOTH the
    // stripped words and the placement attribute.
    let abc = "X:1\nT:Anno\nM:4/4\nL:1/4\nK:C\n\"^Andante\"C D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("placement=\"above\"") && x1.contains("<words>Andante</words>"),
        "precondition: ^Andante emits an above words direction"
    );
    let score = assert_idempotent_s5(abc);
    let annotations = &attachments_at(&score, 0).annotations;
    assert_eq!(annotations.len(), 1, "one annotation on the first note");
    assert_eq!(
        annotations[0].placement,
        Some(AnnotationPlacementModel::Above),
        "the above placement must reconstruct"
    );
    // The reconstructed text re-emits the stripped <words>Andante</words> via the
    // writer's annotation_text (which strips the canonical ^ prefix again).
    assert!(
        annotations[0].text.ends_with("Andante"),
        "reconstructed annotation text re-emits Andante, got {:?}",
        annotations[0].text
    );
}

#[test]
fn annotation_below_reconstructs_placement() {
    use crate::model::AnnotationPlacementModel;
    let abc = "X:1\nT:Below\nM:4/4\nL:1/4\nK:C\n\"_sotto\"C D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("placement=\"below\"") && x1.contains("<words>sotto</words>"),
        "precondition: _sotto emits a below words direction"
    );
    let score = assert_idempotent_s5(abc);
    assert_eq!(
        attachments_at(&score, 0).annotations[0].placement,
        Some(AnnotationPlacementModel::Below)
    );
}

#[test]
fn dynamic_and_annotation_on_same_note_round_trip() {
    // A note can carry BOTH a dynamic and an annotation: the writer emits the
    // annotation <words> direction THEN the <dynamics> direction (annotations
    // before decorations in write_harmony_and_directions). The reader must
    // reconstruct both, on the right channels, so the two directions re-emit in
    // order before the note.
    let abc = "X:1\nT:Mix\nM:4/4\nL:1/4\nK:C\n\"^cresc.\"!f!C D E F |\n";
    let score = assert_idempotent_s5(abc);
    assert_eq!(
        attachments_at(&score, 0).annotations.len(),
        1,
        "the annotation reconstructs"
    );
    assert!(
        attachments_at(&score, 0)
            .decorations
            .iter()
            .any(|d| d.name == "f"),
        "the dynamic reconstructs"
    );
}

#[test]
fn no_direction_leaves_attachments_empty() {
    // A plain note with no directions must not fabricate annotations/decorations
    // or a tempo_model (the writer emits no <direction> for it).
    let score = assert_idempotent_s5("X:1\nT:Plain\nM:4/4\nL:1/4\nK:C\nC D E F |\n");
    assert!(score.metadata.tempo_model.is_none());
    assert!(attachments_at(&score, 0).annotations.is_empty());
    assert!(attachments_at(&score, 0).decorations.is_empty());
}

// --- Stage S5b: <harmony> + <lyric> ------------------------------------------

/// Assert FULL-byte idempotence on an S5b single-voice fixture. By S5b the writer
/// also emits `<harmony>` (chord symbols) and the per-`<note>` `<lyric>` block;
/// nothing in a single-voice harmony/lyric fixture is deferred, so the whole
/// document must be byte-identical. Returns the reconstructed score for direct
/// attachment-field assertions.
fn assert_idempotent_s5b(abc: &str) -> Score {
    let (x1, x2, score) = round_trip(abc);
    assert_eq!(
        x1, x2,
        "write(read(write(score))) must equal write(score) byte-for-byte (S5b harmony + lyrics)"
    );
    score
}

#[test]
fn harmony_major_reconstructs_chord_symbol_text() {
    // A bare "C" major triad emits <harmony><root><root-step>C</root-step></root>
    // <kind text="C">major</kind>. The reader must reconstruct a chord_symbols
    // TextAttachment whose text re-emits the identical <harmony>.
    let abc = "X:1\nT:H\nM:4/4\nL:1/4\nK:C\n\"C\"C D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<kind text=\"C\">major</kind>"),
        "precondition: a bare C chord emits a major <harmony>"
    );
    let score = assert_idempotent_s5b(abc);
    let symbols = &attachments_at(&score, 0).chord_symbols;
    assert_eq!(symbols.len(), 1, "one chord symbol on the first note");
    assert_eq!(
        symbols[0].text, "C",
        "the reconstructed chord text is the <kind text=...> attribute"
    );
}

#[test]
fn harmony_minor_reconstructs() {
    let abc = "X:1\nT:H\nM:4/4\nL:1/4\nK:C\n\"Dm\"C D E F |\n";
    let x1 = export(abc);
    assert!(x1.contains("<kind text=\"Dm\">minor</kind>"));
    let score = assert_idempotent_s5b(abc);
    assert_eq!(attachments_at(&score, 0).chord_symbols[0].text, "Dm");
}

#[test]
fn harmony_seventh_reconstructs() {
    // A maj7 exercises the longest-token quality match; the text attribute (not
    // the inverted kind value) is what the reader recovers, so round-trip is direct.
    let abc = "X:1\nT:H\nM:4/4\nL:1/4\nK:C\n\"Cmaj7\"C D E F |\n";
    let x1 = export(abc);
    assert!(x1.contains("<kind text=\"Cmaj7\">major-seventh</kind>"));
    let score = assert_idempotent_s5b(abc);
    assert_eq!(attachments_at(&score, 0).chord_symbols[0].text, "Cmaj7");
}

#[test]
fn harmony_slash_bass_reconstructs() {
    // "G7/B" emits a <bass><bass-step>B</bass-step></bass> in addition to the
    // dominant <kind>. The text attribute still carries the whole "G7/B" string.
    let abc = "X:1\nT:H\nM:4/4\nL:1/4\nK:C\n\"G7/B\"C D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<kind text=\"G7/B\">dominant</kind>")
            && x1.contains("<bass-step>B</bass-step>"),
        "precondition: a slash chord emits a <bass> and preserves the text"
    );
    let score = assert_idempotent_s5b(abc);
    assert_eq!(attachments_at(&score, 0).chord_symbols[0].text, "G7/B");
}

#[test]
fn harmony_altered_root_reconstructs() {
    // "F#m7b5" exercises a sharp root (<root-alter>1) plus a half-diminished kind
    // plus a flatted-fifth degree; the text attribute carries it all verbatim.
    let abc = "X:1\nT:H\nM:4/4\nL:1/4\nK:C\n\"F#m7b5\"C D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<root-alter>1</root-alter>")
            && x1.contains("<kind text=\"F#m7b5\">half-diminished</kind>"),
        "precondition: a sharp-root altered chord emits root-alter and the text"
    );
    let score = assert_idempotent_s5b(abc);
    assert_eq!(attachments_at(&score, 0).chord_symbols[0].text, "F#m7b5");
}

#[test]
fn harmony_with_added_degree_reconstructs() {
    // "C7b9" emits a <degree> block; the reader recovers only the text, and the
    // writer re-derives the identical <degree> on re-emission.
    let abc = "X:1\nT:H\nM:4/4\nL:1/4\nK:C\n\"C7b9\"C D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<degree-value>9</degree-value>"),
        "precondition: C7b9 emits an added 9th degree"
    );
    let score = assert_idempotent_s5b(abc);
    assert_eq!(attachments_at(&score, 0).chord_symbols[0].text, "C7b9");
}

#[test]
fn harmony_then_annotation_round_trip_in_order() {
    // The writer emits <harmony> BEFORE annotation <words> for the same event.
    // A chord plus an above-annotation on the same note must reconstruct both
    // (chord_symbols then annotations) so they re-emit in the same order.
    let abc = "X:1\nT:H\nM:4/4\nL:1/4\nK:C\n\"C\"\"^Slow\"C D E F |\n";
    let score = assert_idempotent_s5b(abc);
    assert_eq!(
        attachments_at(&score, 0).chord_symbols.len(),
        1,
        "the chord reconstructs into chord_symbols"
    );
    assert_eq!(
        attachments_at(&score, 0).annotations.len(),
        1,
        "the annotation reconstructs into annotations"
    );
}

#[test]
fn two_chords_before_one_note_round_trip_in_order() {
    // `"C""Am"D` puts two chord symbols on the same note: the writer emits two
    // <harmony> blocks in order. The reader must buffer and flush them in the same
    // order so both re-emit (C then Am).
    let abc = "X:1\nT:H\nM:4/4\nL:1/4\nK:C\n\"C\"\"Am\"D E F G |\n";
    let x1 = export(abc);
    assert_eq!(
        x1.matches("<harmony>").count(),
        2,
        "precondition: two chords emit two <harmony> blocks"
    );
    let score = assert_idempotent_s5b(abc);
    let symbols = &attachments_at(&score, 0).chord_symbols;
    assert_eq!(
        symbols.len(),
        2,
        "both chords reconstruct on the first note"
    );
    assert_eq!(symbols[0].text, "C", "first chord stays first");
    assert_eq!(symbols[1].text, "Am", "second chord stays second");
}

#[test]
fn harmony_before_rest_reconstructs_on_rest_event() {
    use crate::model::TimedEventKind;
    // A chord symbol binds to the FOLLOWING event even when that event is a rest
    // (a rest is still a `<note>` element, so the writer emits the `<harmony>`
    // before it). The reader must flush the buffered chord onto the rest event so
    // the `<harmony>` re-emits in place. (A chord with no following note at all,
    // e.g. before a barline, is dropped on the forward path โ€” there is no
    // `<harmony>` to read back, so it is not a round-trip case.)
    let abc = "X:1\nT:Trail\nM:4/4\nL:1/4\nK:C\nC D E F | \"C\" z4 |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<harmony>"),
        "precondition: a chord before a rest emits <harmony>"
    );
    let score = assert_idempotent_s5b(abc);
    // The chord attaches to the first event of the second measure (the rest).
    let rest_event = score.parts[0].voices[0]
        .events
        .iter()
        .find(|e| matches!(e.kind, TimedEventKind::Rest(_)))
        .expect("a rest event");
    assert_eq!(
        rest_event.attachments.chord_symbols.len(),
        1,
        "the chord reconstructs onto the following rest event"
    );
    assert_eq!(rest_event.attachments.chord_symbols[0].text, "C");
}

// --- Stage R2c: textless functional <harmony> synthesis ----------------------
//
// abc2xml / music21 emit FUNCTIONAL harmony โ€” `<kind>` carries no `text=`
// attribute โ€” so croma's S5b `text=`-only reader dropped all foreign chord
// symbols. These cases feed a raw, hand-authored foreign-dialect `<harmony>`
// (no `text=`) directly to `read_musicxml` and assert the chord-symbol string is
// SYNTHESISED from the tree into the same `chord_symbols` `TextAttachment`.

/// A one-measure foreign score whose single quarter note carries `harmony_xml`
/// (a `<harmony>...</harmony>` block authored WITHOUT a `<kind text=...>`).
fn foreign_harmony_score(harmony_xml: &str) -> Score {
    let xml = format!(
        r#"<?xml version="1.0"?>
<score-partwise>
  <part-list><score-part id="P1"><part-name>P</part-name></score-part></part-list>
  <part id="P1">
    <measure number="1">
      <attributes><divisions>8</divisions></attributes>
      {harmony_xml}
      <note>
        <pitch><step>C</step><octave>5</octave></pitch>
        <duration>8</duration>
        <voice>1</voice>
        <type>quarter</type>
      </note>
    </measure>
  </part>
</score-partwise>"#
    );
    read_musicxml(&xml).value
}

/// The synthesised chord-symbol text of the first event's first chord symbol.
fn foreign_chord_text(harmony_xml: &str) -> String {
    let score = foreign_harmony_score(harmony_xml);
    let symbols = &attachments_at(&score, 0).chord_symbols;
    assert_eq!(
        symbols.len(),
        1,
        "exactly one chord symbol synthesised from the textless <harmony>"
    );
    symbols[0].text.clone()
}

#[test]
fn textless_harmony_major_synthesises_root() {
    // <root-step>C</root-step><kind>major</kind> with NO text= -> "C".
    let text = foreign_chord_text(
        "<harmony><root><root-step>C</root-step></root><kind>major</kind></harmony>",
    );
    assert_eq!(text, "C", "C major synthesises to a bare root");
}

#[test]
fn textless_harmony_minor_synthesises_m_suffix() {
    let text = foreign_chord_text(
        "<harmony><root><root-step>D</root-step></root><kind>minor</kind></harmony>",
    );
    assert_eq!(text, "Dm", "D minor synthesises to Dm");
}

#[test]
fn textless_harmony_dominant_synthesises_7() {
    let text = foreign_chord_text(
        "<harmony><root><root-step>G</root-step></root><kind>dominant</kind></harmony>",
    );
    assert_eq!(text, "G7", "G dominant synthesises to G7");
}

#[test]
fn foreign_harmony_suffix_text_recombines_with_root() {
    for (harmony_xml, expected) in [
        (
            "<harmony><root><root-step>B</root-step></root><kind text=\"dim\">diminished</kind></harmony>",
            "Bdim",
        ),
        (
            "<harmony><root><root-step>D</root-step><root-alter>-1</root-alter></root><kind text=\"7\">dominant</kind></harmony>",
            "Db7",
        ),
        (
            "<harmony><root><root-step>F</root-step></root><kind text=\"m\">minor</kind></harmony>",
            "Fm",
        ),
        (
            "<harmony><root><root-step>C</root-step></root><kind text=\"m7\">minor-seventh</kind><bass><bass-step>E</bass-step><bass-alter>-1</bass-alter></bass></harmony>",
            "Cm7/Eb",
        ),
    ] {
        let text = foreign_chord_text(harmony_xml);
        assert_eq!(
            text, expected,
            "foreign kind@text can be a quality suffix, not a complete chord symbol"
        );
    }
}

#[test]
fn foreign_harmony_unknown_kind_emits_bare_root_not_enum() {
    // `<kind text="1">none</kind>`: the `<kind>` ELEMENT content is a MusicXML enum
    // value (`none`/`other`/...), never human text โ€” the display label lives in the
    // `text=` attribute, preserved separately as `musicxml_harmony_text`. Appending
    // the raw enum (`none` -> "Cnone") yields an unparseable chord that demotes to a
    // `<direction>` on re-export, LOSING the `<harmony>` (PDMX element_kind cluster).
    // The reader must emit the bare parseable root instead.
    for (harmony_xml, expected) in [
        (
            "<harmony><root><root-step>C</root-step></root><kind text=\"1\">none</kind></harmony>",
            "C",
        ),
        (
            "<harmony><root><root-step>G</root-step><root-alter>-1</root-alter></root><kind text=\"ยฐ\">other</kind></harmony>",
            "Gb",
        ),
    ] {
        let text = foreign_chord_text(harmony_xml);
        assert_eq!(
            text, expected,
            "an unmodellable kind enum must not be appended verbatim"
        );
    }
}

#[test]
fn foreign_harmony_unknown_kind_round_trips_via_carrier() {
    // End-to-end: the bare-root chord plus the `[I:cr ht]` carrier
    // restores the original `<kind text="1">` on re-export โ€” lossless despite ABC
    // having no native Roman-numeral/functional `<harmony>` form.
    let xml =
        "<harmony><root><root-step>C</root-step></root><kind text=\"1\">none</kind></harmony>";
    let mut score = foreign_harmony_score(xml);
    crate::musicxml::read::complete_score_for_abc(&mut score);
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("[I:cr ht text=\"1\"]\"C\""),
        "ABC projection must carry text=\"1\" beside a bare-root chord:\n{abc}"
    );
    let roundtrip = export_musicxml(&abc).expect("projected harmony ABC should export");
    assert!(
        roundtrip.musicxml.contains("<kind text=\"1\">"),
        "round-trip MusicXML must restore the original kind@text:\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn foreign_harmony_suffix_text_survives_abc_projection() {
    let xml = "<harmony><root><root-step>B</root-step></root><kind text=\"dim\">diminished</kind></harmony>";
    let mut score = foreign_harmony_score(xml);
    crate::musicxml::read::complete_score_for_abc(&mut score);
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("[I:cr ht text=\"dim\"]\"Bdim\""),
        "ABC projection must carry the source MusicXML kind@text suffix:\n{abc}"
    );

    let roundtrip = export_musicxml(&abc).expect("projected harmony ABC should export");
    assert!(
        roundtrip
            .musicxml
            .contains("<kind text=\"dim\">diminished</kind>"),
        "round-trip MusicXML must keep suffix-only kind@text:\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn foreign_harmony_hex_text_survives_abc_projection() {
    // `<kind text="]bad">` contains a `]` โ€” writing it as `[I:cr ht text="..."]`
    // verbatim would break the ABC line at the `]` before the tokenizer ever
    // sees the closing bracket of the carrier itself, so the writer must fall
    // back to the hex-escaped spelling (`cr ht text-hex=<hex>`), and the
    // reader must have a matching `text-hex=` arm to decode it back. Without
    // that arm, `parse_harmony_text_instruction` fails to parse the carrier,
    // `HarmonyKindText` falls back to `AbcNative`, and the original text is
    // silently lost (the bug this test pins).
    let xml =
        "<harmony><root><root-step>C</root-step></root><kind text=\"]bad\">other</kind></harmony>";
    let mut score = foreign_harmony_score(xml);
    crate::musicxml::read::complete_score_for_abc(&mut score);
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("[I:cr ht text-hex=5d626164]"),
        "ABC projection must carry hostile kind@text through the hex carrier:\n{abc}"
    );
    let roundtrip = export_musicxml(&abc).expect("hex-carried harmony ABC should export");
    assert!(
        roundtrip.musicxml.contains("<kind text=\"]bad\">"),
        "round-trip MusicXML must restore the original kind@text containing ']':\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn textless_harmony_stays_textless_through_abc_projection() {
    let xml = "<harmony><root><root-step>C</root-step></root><kind>major</kind></harmony>";
    let mut score = foreign_harmony_score(xml);
    crate::musicxml::read::complete_score_for_abc(&mut score);
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("[I:cr htx]\"C\""),
        "ABC projection must carry the absent source kind@text:\n{abc}"
    );

    let roundtrip = export_musicxml(&abc).expect("projected textless harmony ABC should export");
    assert!(
        roundtrip.musicxml.contains("<kind>major</kind>")
            && !roundtrip.musicxml.contains("<kind text=\"C\">major</kind>"),
        "round-trip MusicXML must not invent kind@text for textless harmony:\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn foreign_harmony_empty_kind_text_survives_abc_projection() {
    // `<kind text="">none</kind>`: an EXPLICIT empty `text=` attribute is distinct
    // from a textless `<kind>` (no attr at all). Both synthesise a bare-root chord,
    // but the empty attribute must round-trip back as `text=""`, NOT collapse to a
    // textless bare `<kind>` (PDMX 1191).
    let xml = "<harmony><root><root-step>C</root-step></root><kind text=\"\">none</kind></harmony>";
    let mut score = foreign_harmony_score(xml);
    crate::musicxml::read::complete_score_for_abc(&mut score);
    let abc = write_abc(&score, AbcWriteOptions::default());
    let roundtrip = export_musicxml(&abc).expect("projected harmony ABC should export");
    assert!(
        roundtrip.musicxml.contains("<kind text=\"\">"),
        "round-trip MusicXML must restore the explicit empty kind@text:\n{}",
        roundtrip.musicxml
    );
    assert!(
        !roundtrip.musicxml.contains("<kind>"),
        "an explicit empty `text=` must not degrade to a textless bare <kind>:\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn textless_harmony_before_zero_duration_directions_survives_abc_projection() {
    let xml = r#"<?xml version="1.0"?>
<score-partwise>
  <part-list><score-part id="P1"><part-name>P</part-name></score-part></part-list>
  <part id="P1">
    <measure number="1">
      <attributes><divisions>8</divisions></attributes>
      <harmony>
        <root><root-step>B</root-step><root-alter>-1</root-alter></root>
        <kind>major</kind>
      </harmony>
      <direction placement="above">
        <direction-type><rehearsal font-weight="bold">A</rehearsal></direction-type>
      </direction>
      <direction placement="above">
        <direction-type><words>Verse</words></direction-type>
      </direction>
      <note>
        <pitch><step>D</step><alter>-1</alter><octave>5</octave></pitch>
        <duration>8</duration>
        <voice>1</voice>
        <type>quarter</type>
      </note>
    </measure>
  </part>
</score-partwise>"#;
    let mut score = read_musicxml(xml).value;
    let direct_xml = write_score_partwise(&score).value;
    let direct_harmony = direct_xml
        .find("<harmony>")
        .expect("direct XML inverse must keep the harmony");
    let direct_rehearsal = direct_xml
        .find("<rehearsal")
        .expect("direct XML inverse must keep the rehearsal");
    assert!(
        direct_harmony < direct_rehearsal,
        "direct MusicXML inverse must keep harmony before the rehearsal:\n{direct_xml}"
    );

    crate::musicxml::read::complete_score_for_abc(&mut score);
    let abc = write_abc(&score, AbcWriteOptions::default());

    assert!(
        abc.contains("[P:A]"),
        "ABC projection must keep the intervening rehearsal direction:\n{abc}"
    );
    assert!(
        abc.contains("[Q:"),
        "ABC projection must keep the intervening tempo-like words direction:\n{abc}"
    );
    assert!(
        abc.contains("[I:cr htx]\"Bb\""),
        "ABC projection must not drop harmony buffered before zero-duration directions:\n{abc}"
    );

    let roundtrip =
        export_musicxml(&abc).expect("projected harmony with intervening directions should export");
    assert!(
        roundtrip.musicxml.contains("<harmony>")
            && roundtrip.musicxml.contains("<kind>major</kind>"),
        "round-trip MusicXML must keep the textless harmony:\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn textless_harmony_before_mid_tune_tempo_survives_abc_projection() {
    let xml = r#"<?xml version="1.0"?>
<score-partwise>
  <part-list><score-part id="P1"><part-name>P</part-name></score-part></part-list>
  <part id="P1">
    <measure number="1">
      <attributes><divisions>8</divisions></attributes>
      <note>
        <pitch><step>C</step><octave>5</octave></pitch>
        <duration>8</duration>
        <voice>1</voice>
        <type>quarter</type>
      </note>
      <harmony>
        <root><root-step>B</root-step><root-alter>-1</root-alter></root>
        <kind>major</kind>
      </harmony>
      <direction placement="above">
        <direction-type><words>Verse</words></direction-type>
      </direction>
      <note>
        <pitch><step>D</step><alter>-1</alter><octave>5</octave></pitch>
        <duration>8</duration>
        <voice>1</voice>
        <type>quarter</type>
      </note>
    </measure>
  </part>
</score-partwise>"#;
    let mut score = read_musicxml(xml).value;
    let direct_xml = write_score_partwise(&score).value;
    let direct_harmony = direct_xml
        .find("<harmony>")
        .expect("direct XML inverse must keep the harmony");
    let direct_words = direct_xml
        .find("<words>Verse</words>")
        .expect("direct XML inverse must keep the words tempo");
    assert!(
        direct_harmony < direct_words,
        "direct MusicXML inverse must keep harmony before the tempo words:\n{direct_xml}"
    );

    crate::musicxml::read::complete_score_for_abc(&mut score);
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("[Q:\"Verse\"] [I:cr htx]\"Bb\""),
        "ABC projection must not drop harmony buffered before a mid-tune tempo:\n{abc}"
    );

    let roundtrip =
        export_musicxml(&abc).expect("projected harmony before mid-tune tempo should export");
    assert!(
        roundtrip.musicxml.contains("<harmony>")
            && roundtrip.musicxml.contains("<kind>major</kind>")
            && roundtrip.musicxml.contains("<words>Verse</words>"),
        "round-trip MusicXML must keep both the textless harmony and tempo words:\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn textless_harmony_major_seventh_synthesises_maj7() {
    let text = foreign_chord_text(
        "<harmony><root><root-step>C</root-step></root><kind>major-seventh</kind></harmony>",
    );
    assert_eq!(text, "Cmaj7", "C major-seventh synthesises to Cmaj7");
}

#[test]
fn textless_harmony_sharp_root_minor_seventh_synthesises() {
    // <root-alter>1 -> '#'; minor-seventh -> "m7".
    let text = foreign_chord_text(
        "<harmony><root><root-step>F</root-step><root-alter>1</root-alter></root><kind>minor-seventh</kind></harmony>",
    );
    assert_eq!(text, "F#m7", "F#-rooted minor-seventh synthesises to F#m7");
}

#[test]
fn textless_harmony_float_root_alter_synthesises_sharp_root() {
    // R2d: abc2xml/music21 emit `<root-alter>1.0</root-alter>` (decimal). A bare-i8
    // parse drops it, demoting the sharp root to a natural; the decimal parse must
    // recover the '#'.
    let text = foreign_chord_text(
        "<harmony><root><root-step>F</root-step><root-alter>1.0</root-alter></root><kind>minor-seventh</kind></harmony>",
    );
    assert_eq!(
        text, "F#m7",
        "a float <root-alter>1.0</root-alter> must synthesise a sharp root"
    );
}

#[test]
fn textless_harmony_float_bass_alter_synthesises_sharp_bass() {
    // R2d: a decimal `<bass-alter>` on the slash bass must also be recovered.
    let text = foreign_chord_text(
        "<harmony><root><root-step>G</root-step></root><kind>dominant</kind><bass><bass-step>F</bass-step><bass-alter>1.0</bass-alter></bass></harmony>",
    );
    assert_eq!(
        text, "G7/F#",
        "a float <bass-alter>1.0</bass-alter> must synthesise a sharp slash bass"
    );
}

#[test]
fn textless_harmony_with_bass_synthesises_slash() {
    // <bass><bass-step>B</bass-step></bass> -> "/B".
    let text = foreign_chord_text(
        "<harmony><root><root-step>G</root-step></root><kind>dominant</kind><bass><bass-step>B</bass-step></bass></harmony>",
    );
    assert_eq!(
        text, "G7/B",
        "a dominant chord with a B bass synthesises to G7/B"
    );
}

#[test]
fn textless_harmony_unmodellable_kind_emits_bare_root() {
    // A `<kind>` croma's writer never emits AND that is not in the General-MusicXML
    // fallback map. The `<kind>` ELEMENT content is always a MusicXML enum value
    // (`other`/`none`/...), never human text โ€” so it is NEVER appended. Appending it
    // produced an unparseable chord (e.g. "Cother") that `write_harmony` demoted to a
    // `<direction>`, losing the `<harmony>`. The bare playable root is emitted instead;
    // a real foreign non-standard chord carries its display label in the `text=`
    // attribute, which the kind@text carrier preserves separately.
    let text = foreign_chord_text(
        "<harmony><root><root-step>C</root-step></root><kind>other</kind></harmony>",
    );
    assert_eq!(
        text, "C",
        "an unmodellable kind enum is dropped, leaving the bare playable root"
    );
}

#[test]
fn textless_harmony_empty_kind_emits_bare_root() {
    // An empty `<kind/>` with a valid `<root>` is a root with unspecified quality โ€”
    // a playable bare-root chord, NOT unmodellable. Emit the bare root rather than
    // dropping it (dropping lost real foreign harmony, e.g. PDMX pdmx_1716's 14
    // `<kind></kind>` chords). The root is preserved, not fabricated.
    let xml = r#"<?xml version="1.0"?>
<score-partwise>
  <part-list><score-part id="P1"><part-name>P</part-name></score-part></part-list>
  <part id="P1">
    <measure number="1">
      <attributes><divisions>8</divisions></attributes>
      <harmony><root><root-step>C</root-step></root><kind/></harmony>
      <note>
        <pitch><step>C</step><octave>5</octave></pitch>
        <duration>8</duration>
        <voice>1</voice>
        <type>quarter</type>
      </note>
    </measure>
  </part>
</score-partwise>"#;
    let report = read_musicxml(xml);
    let symbols = &attachments_at(&report.value, 0).chord_symbols;
    assert_eq!(symbols.len(), 1, "the bare-root chord is reconstructed");
    assert_eq!(
        symbols[0].text, "C",
        "empty kind yields the bare playable root"
    );
}

#[test]
fn textless_harmony_synthesised_string_round_trips_stable() {
    // Round-trip stability: the synthesised string, re-emitted by the writer and
    // re-read, must reproduce the SAME chord (croma's re-export is stable). This
    // proves the synthesis lands on a string `parse_chord_symbol` round-trips.
    for harmony_xml in [
        "<harmony><root><root-step>C</root-step></root><kind>major</kind></harmony>",
        "<harmony><root><root-step>D</root-step></root><kind>minor</kind></harmony>",
        "<harmony><root><root-step>G</root-step></root><kind>dominant</kind></harmony>",
        "<harmony><root><root-step>C</root-step></root><kind>major-seventh</kind></harmony>",
        "<harmony><root><root-step>F</root-step><root-alter>1</root-alter></root><kind>minor-seventh</kind></harmony>",
        "<harmony><root><root-step>G</root-step></root><kind>dominant</kind><bass><bass-step>B</bass-step></bass></harmony>",
        "<harmony><root><root-step>B</root-step><root-alter>-1</root-alter></root><kind>diminished-seventh</kind></harmony>",
    ] {
        let score = foreign_harmony_score(harmony_xml);
        let synthesised = attachments_at(&score, 0).chord_symbols[0].text.clone();
        // Writer preserves the source textless `<kind>` while the ABC-facing
        // synthesised string still re-reads to the same chord-symbol text.
        let x2 = write_score_partwise(&score).value;
        assert!(
            x2.contains("<harmony>") && !x2.contains("<kind text="),
            "the writer re-emits the synthesised string `{synthesised}` as textless <harmony>"
        );
        let reread = read_musicxml(&x2).value;
        assert_eq!(
            attachments_at(&reread, 0).chord_symbols[0].text,
            synthesised,
            "re-reading croma's own output reproduces the synthesised chord `{synthesised}`"
        );
    }
}

#[test]
fn every_synthesised_kind_suffix_round_trips_stable() {
    // EXHAUSTIVE guard over EVERY `<kind>` value the synthesis maps to a suffix
    // (including the General-MusicXML kinds croma's writer never emits). Each
    // synthesised string MUST parse as a chord on re-export โ€” a suffix that
    // `parse_chord_symbol` rejects would demote the symbol to a `<words>` direction
    // on re-write, breaking re-export stability. This catches a mismapped suffix
    // (e.g. an exotic kind whose ABC spelling croma's grammar can't re-parse) at
    // its source rather than in the corpus. The root is the fixed "C".
    let kinds = [
        "major",
        "minor",
        "augmented",
        "diminished",
        "dominant",
        "dominant-seventh",
        "major-seventh",
        "minor-seventh",
        "diminished-seventh",
        "augmented-seventh",
        "half-diminished",
        "half-diminished-seventh",
        "major-sixth",
        "minor-sixth",
        "dominant-ninth",
        "major-ninth",
        "minor-ninth",
        "dominant-11th",
        "major-11th",
        "minor-11th",
        "dominant-13th",
        "major-13th",
        "minor-13th",
        "suspended-fourth",
        "suspended-second",
        "power",
    ];
    for kind in kinds {
        let harmony_xml =
            format!("<harmony><root><root-step>C</root-step></root><kind>{kind}</kind></harmony>");
        let score = foreign_harmony_score(&harmony_xml);
        let symbols = &attachments_at(&score, 0).chord_symbols;
        assert_eq!(
            symbols.len(),
            1,
            "kind `{kind}` must synthesise exactly one chord symbol"
        );
        let synthesised = symbols[0].text.clone();
        let x2 = write_score_partwise(&score).value;
        // Re-export stability: the synthesised string must survive as textless
        // `<harmony>` (NOT degrade to a `<direction><words>` because it failed
        // to re-parse).
        assert!(
            x2.contains("<harmony>") && !x2.contains("<kind text="),
            "kind `{kind}` -> `{synthesised}` must re-parse as a chord on re-export, \
             not demote to <words>"
        );
        let reread = read_musicxml(&x2).value;
        assert_eq!(
            attachments_at(&reread, 0).chord_symbols[0].text,
            synthesised,
            "kind `{kind}` -> `{synthesised}` must reproduce itself on re-read"
        );
    }
}

#[test]
fn lyric_single_syllable_reconstructs() {
    use crate::model::LyricControl;
    // A one-syllable lyric "la" on a note emits <lyric number="1"><syllabic>single
    // </syllabic><text>la</text></lyric>. The reader reconstructs a Syllable.
    let abc = "X:1\nT:L\nM:4/4\nL:1/4\nK:C\nC D E F |\nw: la la la la\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<syllabic>single</syllabic>") && x1.contains("<text>la</text>"),
        "precondition: a stand-alone syllable emits single"
    );
    let score = assert_idempotent_s5b(abc);
    let lyrics = &attachments_at(&score, 0).lyrics;
    assert_eq!(lyrics.len(), 1, "one lyric on the first note");
    assert_eq!(lyrics[0].verse, 1);
    assert_eq!(lyrics[0].text, "la");
    assert_eq!(lyrics[0].control, LyricControl::Syllable);
}

#[test]
fn lyric_hyphenated_word_reconstructs_begin_end() {
    use crate::model::LyricControl;
    // "Twin-kle" splits across two notes: the writer emits begin/Twin then
    // end/kle. The reader must reconstruct [Syllable, Hyphen] on the first note
    // and [Syllable] on the second so the syllabic state machine re-derives
    // begin/end exactly.
    let abc = "X:1\nT:L\nM:4/4\nL:1/4\nK:C\nC D E F |\nw: Twin-kle star light\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<syllabic>begin</syllabic>") && x1.contains("<syllabic>end</syllabic>"),
        "precondition: a two-syllable word emits begin then end"
    );
    let score = assert_idempotent_s5b(abc);
    let first = &attachments_at(&score, 0).lyrics;
    assert_eq!(
        first.len(),
        2,
        "the begin syllable note carries a Syllable AND a trailing Hyphen"
    );
    assert_eq!(first[0].control, LyricControl::Syllable);
    assert_eq!(first[0].text, "Twin");
    assert_eq!(
        first[1].control,
        LyricControl::Hyphen,
        "a begin syllabic reconstructs a following Hyphen on the same note"
    );
    let second = &attachments_at(&score, 1).lyrics;
    assert_eq!(
        second.len(),
        1,
        "the end syllable note carries only a Syllable"
    );
    assert_eq!(second[0].control, LyricControl::Syllable);
    assert_eq!(second[0].text, "kle");
}

#[test]
fn lyric_three_syllable_word_reconstructs_middle() {
    use crate::model::LyricControl;
    // "ho-li-day" exercises the middle syllabic: begin/ho, middle/li, end/day.
    // The middle note must also reconstruct [Syllable, Hyphen] so it re-emits
    // middle (it both follows an open hyphen and opens another).
    let abc = "X:1\nT:L\nM:4/4\nL:1/4\nK:C\nC D E F |\nw: ho-li-day now\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<syllabic>middle</syllabic>"),
        "precondition: a three-syllable word emits a middle syllabic"
    );
    let score = assert_idempotent_s5b(abc);
    let middle = &attachments_at(&score, 1).lyrics;
    assert_eq!(
        middle.len(),
        2,
        "the middle syllable carries Syllable + Hyphen"
    );
    assert_eq!(middle[0].text, "li");
    assert_eq!(middle[1].control, LyricControl::Hyphen);
}

#[test]
fn lyric_melisma_extender_reconstructs() {
    use crate::model::LyricControl;
    // "yes_" extends "yes" over the next note via <extend/> on that next note.
    // The reader reconstructs an Extender (empty text) on the following note.
    let abc = "X:1\nT:L\nM:4/4\nL:1/4\nK:C\nC D E F |\nw: yes_ no end\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<extend/>"),
        "precondition: a melisma emits <extend/>"
    );
    let score = assert_idempotent_s5b(abc);
    // Event 0 is "yes" (single); event 1 carries the extender.
    assert_eq!(attachments_at(&score, 0).lyrics[0].text, "yes");
    let extend = &attachments_at(&score, 1).lyrics;
    assert_eq!(
        extend.len(),
        1,
        "the extended note carries one Extender lyric"
    );
    assert_eq!(extend[0].control, LyricControl::Extender);
    assert!(extend[0].text.is_empty(), "an extender carries no text");
}

#[test]
fn lyric_multiple_verses_reconstruct_numbers() {
    use crate::model::LyricControl;
    // Two w: lines -> two verses; each note carries number="1" then number="2".
    // The reader must reconstruct both verses in order on every note.
    let abc = "X:1\nT:L\nM:4/4\nL:1/4\nK:C\nC D E F |\nw: one two three four\nw: ay bee cee dee\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<lyric number=\"1\">") && x1.contains("<lyric number=\"2\">"),
        "precondition: two w: lines emit two numbered verses"
    );
    let score = assert_idempotent_s5b(abc);
    let lyrics = &attachments_at(&score, 0).lyrics;
    assert_eq!(lyrics.len(), 2, "the first note carries both verses");
    assert_eq!(lyrics[0].verse, 1);
    assert_eq!(lyrics[0].text, "one");
    assert_eq!(lyrics[0].control, LyricControl::Syllable);
    assert_eq!(lyrics[1].verse, 2);
    assert_eq!(lyrics[1].text, "ay");
    assert_eq!(lyrics[1].control, LyricControl::Syllable);
}

#[test]
fn lyric_text_with_trailing_space_round_trips_verbatim() {
    // The writer emits `lyric.text` verbatim, so a syllable that carries a
    // trailing space (the corpus produces these, e.g. via the `~` lyric space)
    // must round-trip byte-for-byte. The reader must NOT trim the <text> content.
    // `la~` is a syllable whose `~` lowers to a trailing space -> `<text>la </text>`.
    let abc = "X:1\nT:L\nM:4/4\nL:1/4\nK:C\nC D E F |\nw: la~ lo me fa\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<text>la </text>"),
        "precondition: a `la~` syllable keeps its trailing space in the <text>, got:\n{x1}"
    );
    let score = assert_idempotent_s5b(abc);
    assert_eq!(
        attachments_at(&score, 0).lyrics[0].text,
        "la ",
        "the reconstructed lyric text preserves the trailing space verbatim"
    );
}

#[test]
fn harmony_and_lyric_on_same_note_round_trip() {
    // A note can carry a chord symbol (emitted before the note) AND a lyric
    // (emitted inside the note). Both must reconstruct so the whole event
    // re-emits byte-identically.
    let abc = "X:1\nT:Both\nM:4/4\nL:1/4\nK:C\n\"C\"C D E F |\nw: la la la la\n";
    let score = assert_idempotent_s5b(abc);
    assert_eq!(attachments_at(&score, 0).chord_symbols.len(), 1);
    assert_eq!(attachments_at(&score, 0).lyrics.len(), 1);
}

// --- Stage R3: demoted chord-symbol vs annotation channel ordering -----------
//
// A quoted string with no placement prefix (e.g. "tr") is an ABC *chord symbol*
// that `write_chord_symbol` DEMOTES to a `<direction><words>` when
// `parse_chord_symbol` rejects it โ€” emitted via the SAME `chord_symbols` channel
// as a real `<harmony>`, hence preserving their document order. When such a
// demoted symbol precedes a real chord on the same event ("tr""G7"note), the
// writer emits `<direction>tr` BEFORE `<harmony>G7`. The reader must read the
// placement-less `<direction><words>` back into `chord_symbols` (not
// `annotations`, which the writer always emits AFTER every chord symbol) so the
// re-emission keeps that order. (This was the 19-file self-loop residual.)

#[test]
fn demoted_chord_symbol_before_harmony_preserves_order() {
    // "tr" is not a parseable chord, so it demotes to a <direction><words>tr;
    // "G7" is a real <harmony>. In document order the direction precedes the
    // harmony, both before the note.
    let abc = "X:1\nT:R3\nM:4/4\nL:1/4\nK:C\n\"tr\"\"G7\"C D E F |\n";
    let x1 = export(abc);
    let dir = x1
        .find("<words>tr</words>")
        .expect("a demoted tr direction");
    let harm = x1.find("<kind text=\"G7\">").expect("a G7 harmony");
    assert!(
        dir < harm,
        "precondition: the writer emits <direction>tr BEFORE <harmony>G7"
    );
    // Full-byte idempotence is the real assertion (X1 == X2).
    let score = assert_idempotent_s5b(abc);
    // The demoted symbol rides the chord_symbols channel, ahead of the real
    // chord, so order is preserved on re-write.
    let symbols = &attachments_at(&score, 0).chord_symbols;
    assert_eq!(
        symbols.iter().map(|s| s.text.as_str()).collect::<Vec<_>>(),
        vec!["tr", "G7"],
        "the placement-less direction reconstructs as a chord_symbols entry, in order"
    );
    assert!(
        attachments_at(&score, 0).annotations.is_empty(),
        "a placement-less demoted symbol is NOT a (placement-bearing) annotation"
    );
}

#[test]
fn harmony_before_demoted_chord_symbol_preserves_order() {
    // The reverse order ("G7""tr"): the real harmony precedes the demoted symbol.
    // This already round-tripped (harmony-then-direction is the canonical writer
    // order); the fix must NOT regress it.
    let abc = "X:1\nT:R3\nM:4/4\nL:1/4\nK:C\n\"G7\"\"tr\"C D E F |\n";
    let x1 = export(abc);
    let harm = x1.find("<kind text=\"G7\">").expect("a G7 harmony");
    let dir = x1
        .find("<words>tr</words>")
        .expect("a demoted tr direction");
    assert!(harm < dir, "precondition: <harmony>G7 BEFORE <direction>tr");
    let score = assert_idempotent_s5b(abc);
    assert_eq!(
        attachments_at(&score, 0)
            .chord_symbols
            .iter()
            .map(|s| s.text.as_str())
            .collect::<Vec<_>>(),
        vec!["G7", "tr"],
        "order is preserved with the real chord first"
    );
}

#[test]
fn placement_annotation_before_harmony_stays_annotation() {
    // A placement-BEARING annotation ("^hi") is a genuine annotation (the writer's
    // annotation channel, emitted AFTER every chord symbol), NOT a demoted chord
    // symbol โ€” even when it appears before the chord in the ABC. The writer emits
    // <harmony>G7 first, then <direction placement="above">hi, and that order is
    // the canonical one, so it round-trips with the annotation on its own channel.
    let abc = "X:1\nT:R3\nM:4/4\nL:1/4\nK:C\n\"^hi\"\"G7\"C D E F |\n";
    let x1 = export(abc);
    let harm = x1.find("<kind text=\"G7\">").expect("a G7 harmony");
    let dir = x1.find("<words>hi</words>").expect("an above hi direction");
    assert!(
        harm < dir && x1.contains("placement=\"above\""),
        "precondition: the writer emits <harmony>G7 before the placed <direction>hi"
    );
    let score = assert_idempotent_s5b(abc);
    assert_eq!(
        attachments_at(&score, 0).chord_symbols.len(),
        1,
        "only the real chord is on the chord_symbols channel"
    );
    assert_eq!(
        attachments_at(&score, 0).annotations.len(),
        1,
        "the placed annotation stays on the annotations channel"
    );
}

#[test]
fn demoted_chord_symbol_before_harmony_in_note_less_measure_round_trips() {
    // The note-LESS variant: a measure whose only content is a demoted symbol then
    // a real chord ("tr""G7" with no following note), flushed by the writer onto a
    // zero-duration Spacer. The Spacer emits its whole chord_symbols vec in order,
    // so the demoted symbol must again ride the chord_symbols channel for the
    // <direction>tr-then-<harmony>G7 order to survive.
    let abc = "X:1\nT:R3\nM:4/4\nL:1/4\nK:C\nC D E F |\n\"tr\"\"G7\"|\n";
    let x1 = export(abc);
    let dir = x1
        .find("<words>tr</words>")
        .expect("a demoted tr direction");
    let harm = x1.find("<kind text=\"G7\">").expect("a G7 harmony");
    assert!(
        dir < harm,
        "precondition: <direction>tr BEFORE <harmony>G7 on the note-less measure"
    );
    // Full-byte idempotence across the whole document, Spacer included.
    assert_idempotent_s5b(abc);
}

// --- Stage S6a: <barline> + <repeat> + <ending> ------------------------------

/// Assert FULL-byte idempotence on an S6a single-voice fixture. By S6a the writer
/// also emits the `<barline>` block (`<bar-style>`, `<repeat>`, `<ending>`) on the
/// left/right of measures; nothing in a single-voice barline/repeat/ending fixture
/// is deferred, so the whole document must be byte-identical. Returns the
/// reconstructed score for direct model-field assertions.
fn assert_idempotent_s6a(abc: &str) -> Score {
    let (x1, x2, score) = round_trip(abc);
    assert_eq!(
        x1, x2,
        "write(read(write(score))) must equal write(score) byte-for-byte (S6a barlines)"
    );
    score
}

/// The `Measure` at `index` of the first part's first voice.
fn measure_at(score: &Score, index: usize) -> &crate::model::Measure {
    &score.parts[0].voices[0].measures[index]
}

#[test]
fn final_barline_reconstructs_kind() {
    use crate::model::BarlineKind;
    // `|]` -> <barline location="right"><bar-style>light-heavy</bar-style></barline>
    // with NO <repeat>; the reader must reconstruct a trailing Final barline.
    let abc = "X:1\nT:F\nM:4/4\nL:1/4\nK:C\nC D E F |]\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<bar-style>light-heavy</bar-style>") && !x1.contains("<repeat"),
        "precondition: |] emits light-heavy with no repeat"
    );
    let score = assert_idempotent_s6a(abc);
    let barlines = &measure_at(&score, 0).barlines;
    assert_eq!(barlines.len(), 1, "one reconstructed right barline");
    assert_eq!(barlines[0].kind, BarlineKind::Final);
}

#[test]
fn double_barline_reconstructs_kind() {
    use crate::model::BarlineKind;
    // `||` -> <bar-style>light-light</bar-style> on the right of the first measure.
    let abc = "X:1\nT:D\nM:4/4\nL:1/4\nK:C\nC D E F || G A B c |\n";
    let x1 = export(abc);
    assert!(x1.contains("<bar-style>light-light</bar-style>"));
    let score = assert_idempotent_s6a(abc);
    assert_eq!(measure_at(&score, 0).barlines[0].kind, BarlineKind::Double);
}

#[test]
fn dotted_barline_reconstructs_kind() {
    use crate::model::BarlineKind;
    let abc = "X:1\nT:Dt\nM:4/4\nL:1/4\nK:C\nC D E F .| G A B c |\n";
    let x1 = export(abc);
    assert!(x1.contains("<bar-style>dotted</bar-style>"));
    let score = assert_idempotent_s6a(abc);
    assert_eq!(measure_at(&score, 0).barlines[0].kind, BarlineKind::Dotted);
}

#[test]
fn invisible_barline_reconstructs_kind() {
    use crate::model::BarlineKind;
    // `[|]` -> <bar-style>none</bar-style> (an invisible barline).
    let abc = "X:1\nT:Inv\nM:4/4\nL:1/4\nK:C\nC D E F [|] G A B c |\n";
    let x1 = export(abc);
    assert!(x1.contains("<bar-style>none</bar-style>"));
    let score = assert_idempotent_s6a(abc);
    assert_eq!(
        measure_at(&score, 0).barlines[0].kind,
        BarlineKind::Invisible
    );
}

#[test]
fn initial_thick_thin_barline_reconstructs_kind() {
    use crate::model::BarlineKind;
    // A mid-tune `[|` (thick-thin) emits <bar-style>heavy-light</bar-style> on the
    // RIGHT with NO <repeat>; this is the Initial kind (distinct from a left
    // RepeatStart, which is heavy-light + <repeat direction="forward">).
    let abc = "X:1\nT:I\nM:4/4\nL:1/4\nK:C\nC D E F [| G A B c |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<bar-style>heavy-light</bar-style>") && !x1.contains("<repeat"),
        "precondition: a mid-tune [| emits heavy-light with no repeat"
    );
    let score = assert_idempotent_s6a(abc);
    assert_eq!(measure_at(&score, 0).barlines[0].kind, BarlineKind::Initial);
}

#[test]
fn repeat_start_reconstructs_leading_barline() {
    use crate::model::BarlineKind;
    // `|:` -> <barline location="left"><bar-style>heavy-light</bar-style>
    // <repeat direction="forward"/></barline>. The reader must reconstruct a
    // LEADING RepeatStart (span.start == measure.source_span.start) so the writer
    // re-emits it on the left.
    let abc = "X:1\nT:R\nM:4/4\nL:1/4\nK:C\n|: C D E F :|\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<repeat direction=\"forward\"/>")
            && x1.contains("<repeat direction=\"backward\"/>"),
        "precondition: |: ... :| emits a forward and a backward repeat"
    );
    let score = assert_idempotent_s6a(abc);
    let barlines = &measure_at(&score, 0).barlines;
    assert!(
        barlines.iter().any(|b| b.kind == BarlineKind::RepeatStart),
        "the first measure carries a leading RepeatStart"
    );
    // The closing `:|` is a RepeatEnd on the (single) measure's right.
    assert!(
        barlines.iter().any(|b| b.kind == BarlineKind::RepeatEnd),
        "the measure also carries the closing RepeatEnd"
    );
}

#[test]
fn repeat_start_end_across_measures_reconstructs() {
    use crate::model::BarlineKind;
    // |: in measure 1, body across two bars, :| at the end of measure 2.
    let abc = "X:1\nT:R2\nM:4/4\nL:1/4\nK:C\n|: C D E F | G A B c :|\n";
    let score = assert_idempotent_s6a(abc);
    assert!(
        measure_at(&score, 0)
            .barlines
            .iter()
            .any(|b| b.kind == BarlineKind::RepeatStart),
        "measure 1 opens the repeat"
    );
    assert!(
        measure_at(&score, 1)
            .barlines
            .iter()
            .any(|b| b.kind == BarlineKind::RepeatEnd),
        "measure 2 closes the repeat"
    );
}

#[test]
fn repeat_both_decomposes_and_round_trips() {
    use crate::model::BarlineKind;
    // `::` (a combined back-then-forward repeat) emits the SAME XML as a
    // RepeatEnd immediately followed by a leading RepeatStart: measure 2's right
    // is light-heavy + repeat-backward, measure 3's left is heavy-light +
    // repeat-forward. The reader decomposes it into RepeatEnd + RepeatStart (it
    // never needs to materialise a RepeatBoth), which re-emits byte-identically.
    let abc = "X:1\nT:RB\nM:4/4\nL:1/4\nK:C\n|: C D E F :: G A B c :|\n";
    let score = assert_idempotent_s6a(abc);
    // Two measures. The `::` seam sits between them: measure 0's RIGHT is the
    // RepeatEnd (the `::` back half), measure 1's LEFT is the leading RepeatStart
    // (the `::` forward half). Measure 0 also opens with `|:` (RepeatStart) and
    // measure 1 closes with `:|` (RepeatEnd), so both measures carry one of each.
    assert!(
        measure_at(&score, 0)
            .barlines
            .iter()
            .any(|b| b.kind == BarlineKind::RepeatEnd),
        "the `::` seam's back half is a RepeatEnd on measure 0's right"
    );
    assert!(
        measure_at(&score, 1)
            .barlines
            .iter()
            .any(|b| b.kind == BarlineKind::RepeatStart),
        "the `::` seam's forward half is a leading RepeatStart on measure 1"
    );
    // No RepeatBoth is ever reconstructed.
    assert!(
        score.parts[0].voices[0]
            .measures
            .iter()
            .all(|m| m.barlines.iter().all(|b| b.kind != BarlineKind::RepeatBoth)),
        "the reader decomposes `::` rather than materialising RepeatBoth"
    );
}

#[test]
fn first_and_second_endings_reconstruct() {
    use crate::model::{BarlineKind, RepeatEndingPartModel};
    // |: ... |1 ... :|2 ... |] : the 1st ending opens on the left of one measure
    // and the 2nd ending opens on the left of the next; the reader reconstructs a
    // RepeatEndingModel { Single(1) } / { Single(2) } at each OPEN measure. The
    // <ending type="stop"> closers are regenerated by the writer's schedule from
    // the open positions + barline kinds, so they are not stored.
    let abc = "X:1\nT:E\nM:4/4\nL:1/4\nK:C\n|: C D E F |1 G A B c :|2 c B A G |]\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<ending number=\"1\" type=\"start\"/>")
            && x1.contains("<ending number=\"2\" type=\"start\"/>"),
        "precondition: 1st/2nd endings emit numbered starts"
    );
    let score = assert_idempotent_s6a(abc);
    let first = score.parts[0].voices[0]
        .measures
        .iter()
        .find_map(|m| m.repeat_endings.first())
        .expect("a 1st-ending RepeatEndingModel is reconstructed");
    assert_eq!(first.endings, vec![RepeatEndingPartModel::Single(1)]);
    let second_count: usize = score.parts[0].voices[0]
        .measures
        .iter()
        .map(|m| m.repeat_endings.len())
        .sum();
    assert_eq!(second_count, 2, "exactly two ending brackets open");
    // The 2nd ending's bracket closes on the |] (Final) of the last measure.
    assert!(
        score.parts[0].voices[0]
            .measures
            .iter()
            .any(|m| m.barlines.iter().any(|b| b.kind == BarlineKind::Final)),
        "the final |] is reconstructed (it closes the 2nd ending via the schedule)"
    );
}

#[test]
fn ending_range_reconstructs_parts() {
    use crate::model::RepeatEndingPartModel;
    // `|1,2` (or `[1,2`) is a single bracket covering passes 1 and 2 -> the writer
    // emits <ending number="1,2" type="start">; the reader splits the comma list
    // back into two Single parts.
    let abc = "X:1\nT:Rng\nM:4/4\nL:1/4\nK:C\n|: C D E F |1,2 G A B c :|\n";
    let x1 = export(abc);
    assert!(
        x1.contains("type=\"start\""),
        "precondition: the combined ending emits a start, got:\n{x1}"
    );
    let score = assert_idempotent_s6a(abc);
    let ending = score.parts[0].voices[0]
        .measures
        .iter()
        .find_map(|m| m.repeat_endings.first())
        .expect("a combined-ending RepeatEndingModel is reconstructed");
    assert_eq!(
        ending.endings,
        vec![
            RepeatEndingPartModel::Single(1),
            RepeatEndingPartModel::Single(2)
        ],
        "the `1,2` number list reconstructs two Single parts"
    );
}

#[test]
fn no_barline_directives_leave_measure_lists_empty() {
    // A plain two-bar tune with only ordinary `|` measure boundaries emits NO
    // <barline> blocks (Regular barlines are implicit). The reader must not
    // fabricate any MeasureBarline or RepeatEndingModel.
    let score = assert_idempotent_s6a("X:1\nT:Plain\nM:4/4\nL:1/4\nK:C\nC D E F | G A B c |\n");
    assert!(
        score.parts[0].voices[0]
            .measures
            .iter()
            .all(|m| m.barlines.is_empty() && m.repeat_endings.is_empty()),
        "plain `|` boundaries reconstruct no barline/ending model entries"
    );
}

// --- Stage S6b: mid-measure <attributes> (key / meter / clef changes) --------

/// Assert FULL-byte idempotence on an S6b single-voice fixture. A mid-measure
/// `<attributes>` block (a SECOND `<attributes>` following notes within a
/// measure, or the first `<attributes>` of a non-leading measure) carries a
/// `KeyChange`/`MeterChange`/`ClefChange`; in a single-voice fixture nothing is
/// deferred, so the whole document must round-trip byte-for-byte. Returns the
/// reconstructed score for direct model-field assertions.
fn assert_idempotent_s6b(abc: &str) -> Score {
    let (x1, x2, score) = round_trip(abc);
    assert_eq!(
        x1, x2,
        "write(read(write(score))) must equal write(score) byte-for-byte (S6b mid-measure attrs)"
    );
    score
}

/// All `TimedEventKind::KeyChange` models in the first part's first voice.
fn key_changes(score: &Score) -> Vec<&crate::model::KeySignatureModel> {
    score.parts[0].voices[0]
        .events
        .iter()
        .filter_map(|event| match &event.kind {
            TimedEventKind::KeyChange(key) => Some(key),
            _ => None,
        })
        .collect()
}

/// All `TimedEventKind::MeterChange` models in the first part's first voice.
fn meter_changes(score: &Score) -> Vec<&crate::model::MeterModel> {
    score.parts[0].voices[0]
        .events
        .iter()
        .filter_map(|event| match &event.kind {
            TimedEventKind::MeterChange(meter) => Some(meter),
            _ => None,
        })
        .collect()
}

/// All `TimedEventKind::ClefChange` models in the first part's first voice.
fn clef_changes(score: &Score) -> Vec<&crate::model::ClefChangeModel> {
    score.parts[0].voices[0]
        .events
        .iter()
        .filter_map(|event| match &event.kind {
            TimedEventKind::ClefChange(clef) => Some(clef),
            _ => None,
        })
        .collect()
}

#[test]
fn inline_key_change_reconstructs_event() {
    // A mid-tune [K:G] becomes a SECOND <attributes> with only a <key> block,
    // emitted between notes. The reader must reconstruct a KeyChange event at the
    // current onset (NOT touch the header metadata.key) so it re-emits in place.
    let abc = "X:1\nT:K\nM:4/4\nL:1/4\nK:C\nC D [K:G] E F |\n";
    let x1 = export(abc);
    assert!(
        x1.matches("<attributes>").count() == 2,
        "precondition: an inline [K:] emits a SECOND mid-measure <attributes>"
    );
    let score = assert_idempotent_s6b(abc);
    // The header key is unchanged (C major, fifths 0).
    assert_eq!(
        header_key(&score).fifths,
        0,
        "the inline key change must not overwrite the header key"
    );
    let changes = key_changes(&score);
    assert_eq!(changes.len(), 1, "exactly one KeyChange event");
    assert_eq!(
        changes[0].fifths, 1,
        "the KeyChange carries G major (fifths 1)"
    );
    // The change sits at onset 2/4 (after two quarter notes), as a zero-duration
    // event in the same measure as the notes.
    let event = score.parts[0].voices[0]
        .events
        .iter()
        .find(|event| matches!(event.kind, TimedEventKind::KeyChange(_)))
        .expect("a KeyChange event");
    assert_eq!(
        event.onset,
        Fraction::new(2, 4),
        "KeyChange onset is after C D"
    );
    assert_eq!(
        event.duration,
        Fraction::zero(),
        "KeyChange is zero-duration"
    );
}

#[test]
fn body_key_change_at_measure_start_reconstructs_event() {
    // A body-field `K:G` between two measures emits a <attributes> with only a
    // <key> as the FIRST child of the next measure (onset 0). That first-child
    // <attributes> in a NON-leading measure is a mid-tune KeyChange, not a header
    // block (the header attributes only appear in the part's first measure).
    let abc = "X:1\nT:K\nM:2/4\nL:1/4\nK:C\nC D |\nK:G\nE F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<measure number=\"2\">") && x1.matches("<attributes>").count() == 2,
        "precondition: the body K: emits a leading <attributes> in measure 2"
    );
    let score = assert_idempotent_s6b(abc);
    let changes = key_changes(&score);
    assert_eq!(changes.len(), 1, "one KeyChange for the body K:");
    assert_eq!(changes[0].fifths, 1, "G major (fifths 1)");
    // It lives in measure 2 (index 1) at onset 0.
    let event = score.parts[0].voices[0]
        .events
        .iter()
        .find(|event| matches!(event.kind, TimedEventKind::KeyChange(_)))
        .expect("a KeyChange event");
    assert_eq!(
        event.measure.index, 1,
        "the KeyChange is in the second measure"
    );
    assert_eq!(
        event.onset,
        Fraction::zero(),
        "at the measure start (onset 0)"
    );
}

#[test]
fn inline_meter_change_reconstructs_event() {
    // A mid-tune [M:2/4] emits a SECOND <attributes> with only a <time> block.
    let abc = "X:1\nT:M\nM:4/4\nL:1/4\nK:C\nC D [M:2/4] E F |\n";
    let x1 = export(abc);
    assert!(
        x1.matches("<attributes>").count() == 2 && x1.contains("<beats>2</beats>"),
        "precondition: inline [M:] emits a mid-measure <time>"
    );
    let score = assert_idempotent_s6b(abc);
    let changes = meter_changes(&score);
    assert_eq!(changes.len(), 1, "exactly one MeterChange event");
    assert_eq!(
        changes[0].display, "2/4",
        "the MeterChange display re-emits the 2/4 <time>"
    );
}

#[test]
fn inline_clef_change_reconstructs_event() {
    // A mid-tune [K:clef=bass] emits a SECOND <attributes> with only a <clef>.
    let abc = "X:1\nT:Cl\nM:4/4\nL:1/4\nK:C\nC D [K:clef=bass] E F |\n";
    let x1 = export(abc);
    assert!(
        x1.matches("<attributes>").count() == 2 && x1.contains("<sign>F</sign>"),
        "precondition: inline clef change emits a mid-measure <clef> (bass = F/4)"
    );
    let score = assert_idempotent_s6b(abc);
    let changes = clef_changes(&score);
    assert_eq!(changes.len(), 1, "exactly one ClefChange event");
    assert_eq!(
        changes[0].clef.text, "bass",
        "the ClefChange reconstructs the canonical bass clef text"
    );
}

#[test]
fn inline_key_and_meter_change_in_one_measure_round_trip() {
    // `[K:G][M:2/4]` are two SEPARATE zero-duration events at the same onset; the
    // writer emits each as its own mid-measure <attributes> (key first, then
    // time), so two events must reconstruct in that order.
    let abc = "X:1\nT:KM\nM:4/4\nL:1/4\nK:C\nC D [K:G][M:2/4] E F |\n";
    let x1 = export(abc);
    assert!(
        x1.matches("<attributes>").count() == 3,
        "precondition: header + key + meter = three <attributes> blocks"
    );
    let score = assert_idempotent_s6b(abc);
    assert_eq!(key_changes(&score).len(), 1, "one KeyChange");
    assert_eq!(meter_changes(&score).len(), 1, "one MeterChange");
    // The KeyChange must be ordered before the MeterChange (writer emits key
    // first), both at the same onset, both before the following E note.
    let kinds: Vec<&str> = score.parts[0].voices[0]
        .events
        .iter()
        .filter_map(|event| match &event.kind {
            TimedEventKind::KeyChange(_) => Some("key"),
            TimedEventKind::MeterChange(_) => Some("meter"),
            TimedEventKind::Note(_) => Some("note"),
            _ => None,
        })
        .collect();
    assert_eq!(
        kinds,
        vec!["note", "note", "key", "meter", "note", "note"],
        "key change precedes meter change, both between the note pairs"
    );
}

#[test]
fn header_attributes_in_first_measure_are_not_an_event() {
    // The leading <attributes> (write_attributes) in the part's FIRST measure is
    // the header key/time/clef, NOT a mid-tune change. A plain tune with no inline
    // attribute change must reconstruct ZERO change events.
    let score = assert_idempotent_s6b("X:1\nT:Plain\nM:4/4\nL:1/4\nK:C\nC D E F |\n");
    assert!(
        key_changes(&score).is_empty()
            && meter_changes(&score).is_empty()
            && clef_changes(&score).is_empty(),
        "the header <attributes> must not be reconstructed as change events"
    );
}

#[test]
fn key_change_then_more_notes_in_later_measure_round_trip() {
    // A body K: in measure 2 followed by more music, plus a header in measure 1:
    // confirms the first-measure header is skipped while the measure-2 leading
    // <attributes> is a KeyChange, and that following notes keep correct onsets.
    let abc = "X:1\nT:Multi\nM:4/4\nL:1/4\nK:C\nC D E F |\nK:Am\nG A B c | d e f g |\n";
    let score = assert_idempotent_s6b(abc);
    let changes = key_changes(&score);
    assert_eq!(changes.len(), 1, "one body KeyChange");
    // A minor has no sharps/flats (fifths 0); the round-trip is what proves the
    // <key> re-emits, the count proves it is an event not a header rewrite.
    assert_eq!(changes[0].fifths, 0, "A minor is fifths 0");
}

#[test]
fn annotation_before_inline_key_change_round_trips() {
    // An annotation immediately before an inline [K:G]: the writer emits the
    // KeyChange <attributes> FIRST (it sorts before the following note at the same
    // onset), THEN the <direction> annotation (attached to the next note), THEN
    // the note. The reader must reconstruct the KeyChange as an event AND keep the
    // annotation buffered onto the following note so the order re-emits.
    let abc = "X:1\nT:E\nM:4/4\nL:1/4\nK:C\nC D \"^hi\"[K:G] E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<words>hi</words>") && x1.matches("<attributes>").count() == 2,
        "precondition: annotation + inline key change both present"
    );
    let score = assert_idempotent_s6b(abc);
    assert_eq!(key_changes(&score).len(), 1, "one KeyChange event");
    // The annotation lands on a NOTE event (the one after the key change), never
    // on the zero-duration KeyChange event itself.
    let total_annotations: usize = score.parts[0].voices[0]
        .events
        .iter()
        .map(|event| event.attachments.annotations.len())
        .sum();
    assert_eq!(total_annotations, 1, "exactly one annotation reconstructed");
    let annotated_is_note = score.parts[0].voices[0].events.iter().any(|event| {
        !event.attachments.annotations.is_empty() && matches!(event.kind, TimedEventKind::Note(_))
    });
    assert!(
        annotated_is_note,
        "the annotation attaches to a note (the one after the key change)"
    );
}

#[test]
fn chord_symbol_before_inline_key_change_round_trips() {
    // A chord symbol "Am" before [K:G]: writer emits the KeyChange <attributes>,
    // then the <harmony>, then the note. The reader keeps the harmony buffered
    // onto the following note while reconstructing the KeyChange event.
    let abc = "X:1\nT:E3\nM:4/4\nL:1/4\nK:C\nC D \"Am\"[K:G] E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<harmony>") && x1.matches("<attributes>").count() == 2,
        "precondition: chord symbol + inline key change both present"
    );
    let score = assert_idempotent_s6b(abc);
    assert_eq!(key_changes(&score).len(), 1, "one KeyChange event");
    let total_chord_symbols: usize = score.parts[0].voices[0]
        .events
        .iter()
        .map(|event| event.attachments.chord_symbols.len())
        .sum();
    assert_eq!(
        total_chord_symbols, 1,
        "exactly one chord symbol reconstructed"
    );
    let on_note = score.parts[0].voices[0].events.iter().any(|event| {
        !event.attachments.chord_symbols.is_empty() && matches!(event.kind, TimedEventKind::Note(_))
    });
    assert!(
        on_note,
        "the chord symbol attaches to the note after the key change"
    );
}

#[test]
fn mid_tune_key_change_with_explicit_accidentals_round_trips() {
    // A mid-tune key with explicit accidentals exercises read_key's
    // <key-step>/<key-alter>/<key-accidental> path inside a mid-measure block.
    let abc = "X:1\nT:Exp\nM:4/4\nL:1/4\nK:C\nC D [K:D exp _b ^f] E F |\n";
    let x1 = export(abc);
    assert!(
        x1.matches("<attributes>").count() == 2 && x1.contains("<key-accidental>"),
        "precondition: the inline key change emits explicit <key-accidental>s"
    );
    let score = assert_idempotent_s6b(abc);
    let changes = key_changes(&score);
    assert_eq!(changes.len(), 1, "one KeyChange event");
    assert!(
        !changes[0].explicit_accidentals.is_empty(),
        "the KeyChange reconstructs its explicit accidentals"
    );
}

#[test]
fn mid_tune_treble_clef_change_round_trips() {
    // A mid-tune clef change BACK to treble still emits a <clef> (G/2) the writer
    // produces unconditionally for a ClefChange. The reader must reconstruct a
    // ClefChange with the canonical "treble" text (NOT None), so the G/2 <clef>
    // re-emits in place rather than being dropped.
    let abc = "X:1\nT:Tr\nM:4/4\nL:1/4\nK:C clef=bass\nC D [K:clef=treble] E F |\n";
    let x1 = export(abc);
    // The header is bass (F/4); the mid-tune change is treble (G/2).
    assert!(
        x1.matches("<attributes>").count() == 2 && x1.matches("<sign>G</sign>").count() == 1,
        "precondition: header bass + a mid-tune treble clef change"
    );
    let score = assert_idempotent_s6b(abc);
    let changes = clef_changes(&score);
    assert_eq!(changes.len(), 1, "one ClefChange event");
    assert_eq!(
        changes[0].clef.text, "treble",
        "a mid-tune treble clef reconstructs the explicit canonical text"
    );
}

#[test]
fn mid_measure_meter_change_before_body_tempo_round_trips() {
    // tune_005141 shape: a header with NO meter (K: only), then a body M:C and a
    // body Q: before the first note. The writer emits the header <attributes>,
    // then the meter-change <attributes> (a MeterChange at onset 0), THEN the
    // body tempo <direction> (a TempoChange, sorted after the meter change). The
    // reader must NOT promote that post-change tempo to the header tempo_model โ€”
    // it follows a mid-measure attributes block, so it is a body TempoChange.
    let abc = "X:1\nT:NoHdrMeter\nK:C\nM:C\nQ:1/8=120\nC D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<time symbol=\"common\">") && x1.contains("<metronome>"),
        "precondition: a body meter AND a body tempo are both present"
    );
    // The meter-change <attributes> must precede the tempo <direction> in X1.
    let meter_pos = x1
        .find("<time symbol=\"common\">")
        .expect("the meter change is present");
    let tempo_pos = x1.find("<metronome>").expect("the body tempo is present");
    assert!(
        meter_pos < tempo_pos,
        "precondition: the writer emits the meter change before the body tempo"
    );
    let score = assert_idempotent_s6b(abc);
    assert_eq!(meter_changes(&score).len(), 1, "one MeterChange event");
    assert!(
        score.metadata.tempo_model.is_none(),
        "a tempo after a mid-measure attributes change is a body TempoChange, \
         not the header tempo_model"
    );
    let tempo_changes = score.parts[0].voices[0]
        .events
        .iter()
        .filter(|event| matches!(event.kind, TimedEventKind::TempoChange(_)))
        .count();
    assert_eq!(
        tempo_changes, 1,
        "the body tempo reconstructs one TempoChange"
    );
}

#[test]
fn annotation_then_inline_change_in_noteless_measure_round_trips() {
    // S6e ordering edge (the documented 22-file residual). A standalone chord
    // symbol/annotation immediately followed by an inline key change in a measure
    // with NO following note: `"Trio"[K:F]` alone in its bar, the next note past a
    // `|:` in the following bar. The writer emits the `<direction>` (the buffered
    // attachment) BEFORE the change's `<attributes>` โ€” its Spacer's source predates
    // the change's, so the stable (onset, source.start) sort orders it first. With
    // no following note to host the annotation, the reader builds a trailing Spacer;
    // it must insert that Spacer BEFORE the same-onset KeyChange so the re-emission
    // keeps `<direction>` ahead of `<attributes>`.
    let abc = "X:1\nT:Trio test\nM:4/4\nL:1/8\nK:C\nA2 B2 c2 d2 |\"Trio\"[K:F]|: A2 B2 c2 d2 |\n";
    let x1 = export(abc);
    // Precondition: the writer emits the direction before the key-change attributes
    // inside the note-less measure.
    let dir_pos = x1.find("<words>Trio</words>").expect("the Trio direction");
    let key_pos = x1
        .find("<fifths>-1</fifths>")
        .expect("the inline key change");
    assert!(
        dir_pos < key_pos,
        "precondition: writer emits the <direction> before the key-change <attributes>"
    );
    // The fix: full-byte idempotence (the order is preserved on re-write).
    let score = assert_idempotent_s6b(abc);
    assert_eq!(key_changes(&score).len(), 1, "one KeyChange event");
    // The note-less measure has both a KeyChange and a Spacer at onset 0, and the
    // Spacer (carrying the Trio chord symbol) precedes the KeyChange in the event
    // stream so the stable sort emits them in writer order.
    let measure2: Vec<_> = score.parts[0].voices[0]
        .events
        .iter()
        .filter(|event| event.measure.index == 1)
        .collect();
    let spacer_idx = measure2
        .iter()
        .position(|event| matches!(event.kind, TimedEventKind::Spacer));
    let key_idx = measure2
        .iter()
        .position(|event| matches!(event.kind, TimedEventKind::KeyChange(_)));
    assert!(
        matches!((spacer_idx, key_idx), (Some(s), Some(k)) if s < k),
        "the trailing Spacer must precede the same-onset KeyChange (got spacer={spacer_idx:?}, key={key_idx:?})"
    );
}

#[test]
fn trailing_decoration_after_notes_still_appends_after_them() {
    // Guard the OTHER branch of the S6e Spacer insertion: a trailing decoration
    // with notes BEFORE it and NO mid-tune change at its onset must still append
    // after the notes (the pre-existing pre-barline `!segno!` case), not jump
    // ahead of anything. `A2 B2 c2 d2 !segno!|` puts the segno after the 4 notes.
    let abc = "X:1\nT:Seg\nM:4/4\nL:1/8\nK:C\nA2 B2 c2 d2 !segno!|\n";
    let score = assert_idempotent_s6b(abc);
    // The last event is the Spacer carrying the segno decoration, after the notes.
    let events = &score.parts[0].voices[0].events;
    let last = events.last().expect("at least one event");
    assert!(
        matches!(last.kind, TimedEventKind::Spacer),
        "the trailing decoration lands on a Spacer appended after the notes"
    );
    assert_eq!(
        last.attachments.decorations.len(),
        1,
        "the Spacer carries the segno decoration"
    );
}

// --- Stage S6c: grace notes (<grace>) + chords (<chord/>) --------------------

/// Assert FULL-byte idempotence on an S6c single-voice fixture. By S6c the writer
/// emits `<grace>` notes (slash/before/after-grace, grace chords, grace slurs) and
/// `<chord/>` members; in a single-voice grace/chord fixture nothing is deferred,
/// so the whole document must round-trip byte-for-byte. Returns the reconstructed
/// score for direct model-field assertions.
fn assert_idempotent_s6c(abc: &str) -> Score {
    let (x1, x2, score) = round_trip(abc);
    assert_eq!(
        x1, x2,
        "write(read(write(score))) must equal write(score) byte-for-byte (S6c grace+chord)"
    );
    score
}

/// The first event's `grace_groups` in the first part's first voice.
fn grace_groups_at(score: &Score, index: usize) -> &[crate::model::GraceGroupAttachment] {
    &score.parts[0].voices[0].events[index]
        .attachments
        .grace_groups
}

fn grace_note_decoration_names(
    group: &crate::model::GraceGroupAttachment,
    event_index: usize,
) -> Vec<&str> {
    use crate::model::GraceEventKind;
    match &group.events[event_index].kind {
        GraceEventKind::Note(note) => note
            .decorations
            .iter()
            .map(|decoration| decoration.name.as_str())
            .collect(),
        other => panic!("expected a grace Note, got {other:?}"),
    }
}

fn grace_chord_member_decoration_names(
    group: &crate::model::GraceGroupAttachment,
    event_index: usize,
    member_index: usize,
) -> Vec<&str> {
    use crate::model::GraceEventKind;
    match &group.events[event_index].kind {
        GraceEventKind::Chord(members) => members[member_index]
            .decorations
            .iter()
            .map(|decoration| decoration.name.as_str())
            .collect(),
        other => panic!("expected a grace Chord, got {other:?}"),
    }
}

#[test]
fn single_grace_round_trips_and_reconstructs_group() {
    use crate::model::GraceEventKind;
    // {a}G : one grace note (<type>eighth</type>, base unit 1/8, count 1) before G.
    let abc = "X:1\nT:G\nL:1/4\nK:C\n{a}G\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<grace/>") && !x1.contains("slash"),
        "precondition: a plain {{a}} emits an unslashed <grace/>"
    );
    let score = assert_idempotent_s6c(abc);
    // The grace group attaches to the FOLLOWING main note (event 0 = G).
    let groups = grace_groups_at(&score, 0);
    assert_eq!(groups.len(), 1, "one grace group on the following note");
    assert_eq!(groups[0].note_count, 1, "one grace element");
    assert!(groups[0].slash.is_none(), "an unslashed grace");
    assert_eq!(groups[0].events.len(), 1);
    match &groups[0].events[0].kind {
        GraceEventKind::Note(note) => {
            assert_eq!(note.pitch.step, 'A');
            assert_eq!(note.pitch.octave, 5);
            assert_eq!(
                note.length_multiplier,
                Fraction::one(),
                "a plain grace note has length multiplier 1"
            );
        }
        other => panic!("expected a grace Note, got {other:?}"),
    }
}

#[test]
fn grace_note_decorations_round_trip() {
    // Decorations inside the grace braces bind to the grace note itself, not the
    // following main note. This covers the PDMX residuals where grace-note
    // fermata/staccato/fingering notations were silently dropped.
    let abc = "X:1\nT:GDeco\nL:1/4\nK:C\n{!staccato!!4!a}!fermata!G\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<staccato/>") && x1.contains("<fingering>4</fingering>"),
        "precondition: grace-note decorations emit MusicXML notations on the grace note:\n{x1}"
    );
    let score = assert_idempotent_s6c(abc);
    let names = grace_note_decoration_names(&grace_groups_at(&score, 0)[0], 0);
    assert!(
        names.contains(&"staccato") && names.contains(&"4"),
        "the grace note keeps its own decorations, got {names:?}"
    );
    assert!(
        attachments_at(&score, 0)
            .decorations
            .iter()
            .any(|decoration| decoration.name == "fermata"),
        "the following main note keeps its separate fermata"
    );
}

#[test]
fn grace_dynamic_decoration_round_trip() {
    // Dynamics are MusicXML directions, not note-local notations. When the ABC
    // dynamic is inside the grace braces, it belongs to the grace note; when it
    // precedes the grace group, it still belongs to the following principal note.
    let abc = "X:1\nT:GDyn\nL:1/4\nK:C\n{!p!a}!f!G\n";
    let score = assert_idempotent_s6c(abc);
    let names = grace_note_decoration_names(&grace_groups_at(&score, 0)[0], 0);
    assert_eq!(
        names,
        vec!["p"],
        "the grace note keeps its own dynamic decoration"
    );
    let principal = &attachments_at(&score, 0).decorations;
    assert_eq!(principal.len(), 1, "one decoration on the principal note");
    assert_eq!(
        principal[0].name, "f",
        "the principal note keeps the dynamic outside the grace braces"
    );
}

#[test]
fn multi_note_grace_group_round_trips() {
    // {abc}G : three grace notes (each <type>16th</type>, base unit 1/16, count 3).
    let abc = "X:1\nT:G\nL:1/4\nK:C\n{abc}G\n";
    let x1 = export(abc);
    assert_eq!(
        x1.matches("<grace/>").count(),
        3,
        "precondition: three <grace/> notes"
    );
    let score = assert_idempotent_s6c(abc);
    let groups = grace_groups_at(&score, 0);
    assert_eq!(groups.len(), 1, "one grace group");
    assert_eq!(groups[0].note_count, 3, "three grace elements");
    assert_eq!(groups[0].events.len(), 3, "three grace events");
}

#[test]
fn slashed_grace_round_trips_and_reconstructs_slash() {
    // {/a}G : an acciaccatura -> <grace slash="yes"/>.
    let abc = "X:1\nT:G\nL:1/4\nK:C\n{/a}G\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<grace slash=\"yes\"/>"),
        "precondition: {{/a}} emits slash=\"yes\""
    );
    let score = assert_idempotent_s6c(abc);
    let groups = grace_groups_at(&score, 0);
    assert_eq!(groups.len(), 1);
    assert!(
        groups[0].slash.is_some(),
        "the reconstructed group records the slash"
    );
}

#[test]
fn grace_length_multiplier_round_trips() {
    use crate::model::GraceEventKind;
    // {a2}G : a single grace note with written length 2 -> 1/8 * 2 = 1/4 ->
    // <type>quarter</type>. The reader must recover length_multiplier = 2.
    let abc = "X:1\nT:G\nL:1/4\nK:C\n{a2}G\n";
    let score = assert_idempotent_s6c(abc);
    let groups = grace_groups_at(&score, 0);
    match &groups[0].events[0].kind {
        GraceEventKind::Note(note) => assert_eq!(
            note.length_multiplier,
            Fraction::new(2, 1),
            "{{a2}} reconstructs a length multiplier of 2"
        ),
        other => panic!("expected a grace Note, got {other:?}"),
    }
}

#[test]
fn grace_half_length_multiplier_round_trips() {
    use crate::model::GraceEventKind;
    // {a/}G : a single grace note with written length 1/2 -> 1/8 * 1/2 = 1/16 ->
    // <type>16th</type>. The reader must recover length_multiplier = 1/2.
    let abc = "X:1\nT:G\nL:1/4\nK:C\n{a/}G\n";
    let score = assert_idempotent_s6c(abc);
    let groups = grace_groups_at(&score, 0);
    match &groups[0].events[0].kind {
        GraceEventKind::Note(note) => assert_eq!(
            note.length_multiplier,
            Fraction::new(1, 2),
            "{{a/}} reconstructs a length multiplier of 1/2"
        ),
        other => panic!("expected a grace Note, got {other:?}"),
    }
}

#[test]
fn grace_with_slur_round_trips() {
    use crate::model::SlurRole;
    // {(ab)}G : a slur opens and closes INSIDE the grace braces, binding the two
    // grace notes. The writer emits <slur type="start"> on the first grace note
    // and <slur type="stop"> on the second (both in <notations>).
    let abc = "X:1\nT:G\nL:1/4\nK:C\n{(ab)}G\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<slur type=\"start\" number=\"1\"/>")
            && x1.contains("<slur type=\"stop\" number=\"1\"/>"),
        "precondition: a grace slur emits start+stop slurs"
    );
    let score = assert_idempotent_s6c(abc);
    let groups = grace_groups_at(&score, 0);
    assert_eq!(groups.len(), 1);
    assert_eq!(groups[0].events.len(), 2, "two grace notes");
    let start = &groups[0].events[0].slurs;
    assert_eq!(start.len(), 1, "first grace note opens a slur");
    assert_eq!(start[0].role, SlurRole::Start);
    let stop = &groups[0].events[1].slurs;
    assert_eq!(stop.len(), 1, "second grace note closes the slur");
    assert_eq!(stop[0].role, SlurRole::Stop);
}

#[test]
fn slur_opening_before_grace_binds_first_grace_note() {
    use crate::model::SlurRole;
    // ({a}G)A : the slur opens BEFORE the grace brace, so its start binds to the
    // first grace note and its stop to the main note G. Re-emission must place the
    // start slur on the grace note again.
    let abc = "X:1\nT:G\nL:1/4\nK:C\n({a}G)A\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<slur type=\"start\" number=\"1\"/>"),
        "precondition: the slur start lands on the grace note"
    );
    let score = assert_idempotent_s6c(abc);
    let groups = grace_groups_at(&score, 0);
    let start = &groups[0].events[0].slurs;
    assert_eq!(start.len(), 1, "the grace note carries the slur start");
    assert_eq!(start[0].role, SlurRole::Start);
}

#[test]
fn grace_chord_round_trips_and_reconstructs_members() {
    use crate::model::GraceEventKind;
    // {[ac]}G : a grace CHORD (one grace element, count 1) whose second member
    // carries <chord/>. The reader must reconstruct a GraceEventKind::Chord with
    // two members, not two separate grace notes.
    let abc = "X:1\nT:G\nL:1/4\nK:C\n{[ac]}G\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<chord/>") && x1.matches("<grace/>").count() == 2,
        "precondition: a grace chord emits two <grace/> with one <chord/>"
    );
    let score = assert_idempotent_s6c(abc);
    let groups = grace_groups_at(&score, 0);
    assert_eq!(groups.len(), 1);
    assert_eq!(
        groups[0].note_count, 1,
        "a grace chord is ONE grace element (base unit 1/8)"
    );
    assert_eq!(groups[0].events.len(), 1, "one grace event (the chord)");
    match &groups[0].events[0].kind {
        GraceEventKind::Chord(members) => {
            assert_eq!(members.len(), 2, "the grace chord has two members");
            assert_eq!(members[0].pitch.step, 'A');
            assert_eq!(members[1].pitch.step, 'C');
        }
        other => panic!("expected a grace Chord, got {other:?}"),
    }
}

#[test]
fn grace_chord_member_decorations_round_trip() {
    let abc = "X:1\nT:GChordDeco\nM:4/4\nL:1/4\nK:C\n{[C!trill!EG]}A B C D|\n";
    let score = assert_idempotent_s6c(abc);
    let group = &grace_groups_at(&score, 0)[0];
    assert_eq!(
        grace_chord_member_decoration_names(group, 0, 0),
        Vec::<&str>::new(),
        "the first grace chord member has no decoration"
    );
    assert_eq!(
        grace_chord_member_decoration_names(group, 0, 1),
        vec!["trill"],
        "the second grace chord member keeps its trill"
    );
    assert_eq!(
        grace_chord_member_decoration_names(group, 0, 2),
        Vec::<&str>::new(),
        "the third grace chord member has no decoration"
    );
}

#[test]
fn grace_rest_round_trips() {
    use crate::model::{GraceEventKind, RestVisibility};
    // {x}G : a grace REST (invisible x rest) -> <note print-object="no"><grace/>
    // <rest/>. The reader must reconstruct a GraceEventKind::Rest.
    let abc = "X:1\nT:G\nL:1/4\nK:C\n{x}G\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<grace/>") && x1.contains("<rest/>"),
        "precondition: a grace rest emits <grace/> with <rest/>"
    );
    let score = assert_idempotent_s6c(abc);
    let groups = grace_groups_at(&score, 0);
    assert_eq!(groups[0].events.len(), 1);
    match &groups[0].events[0].kind {
        GraceEventKind::Rest(rest) => {
            assert_eq!(
                rest.visibility,
                RestVisibility::Invisible,
                "an x grace rest is invisible (print-object=no)"
            );
        }
        other => panic!("expected a grace Rest, got {other:?}"),
    }
}

#[test]
fn after_grace_at_measure_end_binds_to_preceding_note() {
    // Te6{de}|... : a trailing grace group with NO following note in measure 1
    // binds as an AFTER-grace on the preceding (decorated) note. The grace <note>s
    // are the last elements of measure 1; the reader must attach them to that
    // note's after_grace_groups so they re-emit after it.
    let abc = "X:1\nT:Trailing\nM:4/4\nL:1/8\nK:C\nTe6{de}|d2f f2f|\n";
    let score = assert_idempotent_s6c(abc);
    let after = &score.parts[0].voices[0].events[0]
        .attachments
        .after_grace_groups;
    assert_eq!(
        after.len(),
        1,
        "the preceding note carries one after-grace group"
    );
    assert_eq!(
        after[0].note_count, 2,
        "the after-grace group has two notes"
    );
    // And it is NOT a (before) grace group on that note.
    assert!(
        score.parts[0].voices[0].events[0]
            .attachments
            .grace_groups
            .is_empty(),
        "the trailing grace is an after-grace, not a before-grace"
    );
}

#[test]
fn after_grace_note_decorations_round_trip() {
    // Trailing grace groups use `after_grace_groups`, so guard that decorated
    // after-grace notes keep their notations too.
    let abc = "X:1\nT:TrailingDeco\nM:4/4\nL:1/8\nK:C\nTe6{!staccato!d!4!e}|d2f f2f|\n";
    let score = assert_idempotent_s6c(abc);
    let after = &score.parts[0].voices[0].events[0]
        .attachments
        .after_grace_groups;
    assert_eq!(
        after.len(),
        1,
        "one after-grace group on the principal note"
    );
    assert_eq!(
        grace_note_decoration_names(&after[0], 0),
        vec!["staccato"],
        "first after-grace note keeps staccato"
    );
    assert_eq!(
        grace_note_decoration_names(&after[0], 1),
        vec!["4"],
        "second after-grace note keeps fingering"
    );
}

/// Hand-crafted MusicXML the writer never emits: a `<grace>` note immediately
/// followed by a `<chord/>` member note (no plain main note between to drain the
/// open grace run). The chord member folds into the previous event and `continue`s
/// before the buffered before-grace groups flush, so `pending_graces` reaches the
/// measure-end finalisation non-empty. This is the path the removed `debug_assert!`
/// guarded; totality (design ยง2.2/ยง6) requires a graceful degrade, not a panic.
/// Here a preceding `G` note hosts the orphaned group as a before-grace group.
#[test]
fn grace_before_chord_member_degrades_without_panic() {
    use crate::model::TimedEventKind;
    // G (main) ; {a} (grace, opens the run) ; [chord member c] carrying <chord/>
    // with no plain note between. roxmltree DOM is fed directly โ€” there is no ABC
    // that lowers to this shape, so it must be authored by hand.
    let xml = r#"<?xml version="1.0"?>
<score-partwise>
  <part-list><score-part id="P1"><part-name>P</part-name></score-part></part-list>
  <part id="P1">
    <measure number="1">
      <attributes><divisions>8</divisions></attributes>
      <note>
        <pitch><step>G</step><octave>4</octave></pitch>
        <duration>8</duration>
        <voice>1</voice>
        <type>quarter</type>
      </note>
      <note>
        <grace/>
        <pitch><step>A</step><octave>5</octave></pitch>
        <voice>1</voice>
        <type>eighth</type>
      </note>
      <note>
        <chord/>
        <pitch><step>C</step><octave>5</octave></pitch>
        <duration>8</duration>
        <voice>1</voice>
        <type>quarter</type>
      </note>
    </measure>
  </part>
</score-partwise>"#;
    // Totality: must return, never panic.
    let report = read_musicxml(xml);
    let score = report.value;
    // The G note was promoted to a chord (the <chord/> member folded into it),
    // and the orphaned before-grace group was re-bound to that event rather than
    // dropped or panicking on.
    let event = &score.parts[0].voices[0].events[0];
    assert!(
        matches!(event.kind, TimedEventKind::Chord(_)),
        "the <chord/> member folds the leading G note into a chord"
    );
    assert_eq!(
        event.attachments.grace_groups.len(),
        1,
        "the orphaned before-grace group is re-bound to the hosting event, not lost"
    );
    // No panic occurred (we reached here); the degrade need not emit a diagnostic
    // on this arm because the group was preserved, not dropped.
}

/// The other fallback arm: a `<grace>` run followed by a `<chord/>` member note
/// with NO preceding main event at all. The grace run drains to `pending_graces`,
/// the chord member finds no head to fold onto (warned), and the orphaned before-
/// grace groups reach finalisation with `last_main_event == None`. The reader must
/// drop them with a diagnostic โ€” and, crucially, not panic.
#[test]
fn orphan_before_grace_with_no_host_is_dropped_with_diagnostic() {
    // {a} (grace) then [chord member c] as the very first elements of the measure.
    let xml = r#"<?xml version="1.0"?>
<score-partwise>
  <part-list><score-part id="P1"><part-name>P</part-name></score-part></part-list>
  <part id="P1">
    <measure number="1">
      <attributes><divisions>8</divisions></attributes>
      <note>
        <grace/>
        <pitch><step>A</step><octave>5</octave></pitch>
        <voice>1</voice>
        <type>eighth</type>
      </note>
      <note>
        <chord/>
        <pitch><step>C</step><octave>5</octave></pitch>
        <duration>8</duration>
        <voice>1</voice>
        <type>quarter</type>
      </note>
    </measure>
  </part>
</score-partwise>"#;
    // Totality: must return, never panic.
    let report = read_musicxml(xml);
    // The orphaned before-grace run was dropped with the documented diagnostic
    // (no host note existed); the chord member without a head also warns.
    assert!(
        report
            .diagnostics
            .iter()
            .any(|d| d.code == "musicxml.read.orphan_before_grace"),
        "the host-less before-grace run must be dropped with a diagnostic, not panic"
    );
}

/// The first `ChordEvent` in the first part's first voice, with its event index.
fn first_chord(score: &Score) -> &crate::model::ChordEvent {
    score.parts[0].voices[0]
        .events
        .iter()
        .find_map(|event| match &event.kind {
            TimedEventKind::Chord(chord) => Some(chord),
            _ => None,
        })
        .expect("expected a ChordEvent")
}

#[test]
fn plain_chord_round_trips_and_reconstructs_members() {
    // [CEG] : the first note starts the chord; E and G carry <chord/>. The reader
    // must reconstruct ONE TimedEventKind::Chord with three members at one onset.
    let abc = "X:1\nT:C\nL:1/4\nK:C\n[CEG]\n";
    let x1 = export(abc);
    assert_eq!(
        x1.matches("<chord/>").count(),
        2,
        "precondition: a 3-note chord emits two <chord/> marks"
    );
    let score = assert_idempotent_s6c(abc);
    // Exactly one timed event (the chord), not three separate notes.
    assert_eq!(
        score.parts[0].voices[0].events.len(),
        1,
        "a chord is one TimedEvent::Chord, not three notes"
    );
    let chord = first_chord(&score);
    assert_eq!(chord.members.len(), 3, "three chord members");
    assert_eq!(chord.members[0].pitch.step, 'C');
    assert_eq!(chord.members[1].pitch.step, 'E');
    assert_eq!(chord.members[2].pitch.step, 'G');
    assert_eq!(
        chord.members[0].duration,
        Fraction::new(1, 4),
        "each member is a quarter"
    );
}

#[test]
fn chord_then_note_round_trips() {
    // [CEG] D E F | : a chord followed by plain notes. The chord is one event; the
    // following notes advance the cursor from the chord's onset.
    let abc = "X:1\nT:C\nM:4/4\nL:1/4\nK:C\n[CEG] D E F|\n";
    let score = assert_idempotent_s6c(abc);
    let events = &score.parts[0].voices[0].events;
    assert!(
        matches!(events[0].kind, TimedEventKind::Chord(_)),
        "the first event is the chord"
    );
    assert_eq!(events.len(), 4, "chord + three notes = four events");
    // The note after the chord starts at the chord's onset + its duration (1/4).
    assert_eq!(
        events[1].onset,
        Fraction::new(1, 4),
        "the note after the chord is at onset 1/4"
    );
}

#[test]
fn chord_with_ties_round_trips_per_member() {
    use crate::model::TieRole;
    // [CEG]2-[CEG]2 : a tied chord. Each member gets its OWN tie pair (numbers
    // 1,2,3 across the members), so the reader must reconstruct per-member ties
    // whose pair_ids re-derive the same <tied number=...>.
    let abc = "X:1\nT:C\nM:4/4\nL:1/4\nK:C\n[CEG]2-[CEG]2 z4|\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<tied type=\"start\" number=\"1\"/>")
            && x1.contains("<tied type=\"start\" number=\"3\"/>"),
        "precondition: tied chord members get distinct tie numbers 1..3"
    );
    let score = assert_idempotent_s6c(abc);
    let chord = first_chord(&score);
    assert_eq!(chord.members.len(), 3);
    // Every member of the first chord carries a tie START.
    for (member_index, member) in chord.members.iter().enumerate() {
        assert_eq!(
            member.attachments.ties.len(),
            1,
            "member {member_index} carries one tie"
        );
        assert_eq!(member.attachments.ties[0].role, TieRole::Start);
    }
}

#[test]
fn chord_member_decoration_round_trips() {
    // [C!trill!EG] : a decoration (trill) on the SECOND chord member. The reader
    // must reconstruct it onto that member's attachments so the writer re-emits
    // the <ornaments><trill-mark/> on the same member.
    let abc = "X:1\nT:C\nM:4/4\nL:1/4\nK:C\n[C!trill!EG] D E F|\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<trill-mark/>"),
        "precondition: the chord member decoration emits a trill"
    );
    let score = assert_idempotent_s6c(abc);
    let chord = first_chord(&score);
    // The trill lands on the E member (index 1), per the ABC ordering.
    let decorated = chord
        .members
        .iter()
        .filter(|member| !member.attachments.decorations.is_empty())
        .count();
    assert_eq!(decorated, 1, "exactly one member carries a decoration");
}

#[test]
fn two_chords_in_a_measure_round_trip() {
    // [CE][GB] : two chords back to back. Each must reconstruct as its own
    // ChordEvent with the right first-member and per-member attachments.
    let abc = "X:1\nT:C\nM:4/4\nL:1/4\nK:C\n[CE]2 [GB]2 z4|\n";
    let score = assert_idempotent_s6c(abc);
    let chords = score.parts[0].voices[0]
        .events
        .iter()
        .filter(|event| matches!(event.kind, TimedEventKind::Chord(_)))
        .count();
    assert_eq!(chords, 2, "two distinct chord events");
}

// --- S6d: multi-voice (<backup>/<voice>) + multiple-rest --------------------

/// Full-byte idempotence helper for S6d. Nothing in a multi-voice or
/// multiple-rest fixture is deferred (key/time/clef/notations/directions are all
/// reconstructed), so the whole document must be byte-identical.
fn assert_idempotent_full(abc: &str) -> Score {
    let (x1, x2, score) = round_trip(abc);
    assert_eq!(
        x1, x2,
        "write(read(write(score))) must equal write(score) byte-for-byte (S6d)"
    );
    score
}

#[test]
fn multiple_rest_reconstructs_measure_field() {
    // `Z2` expands to a two-bar multi-rest; the writer marks the first bar with
    // <measure-style><multiple-rest>2</multiple-rest>. The reader must set
    // Measure.multiple_rest so the glyph re-emits.
    let abc = "X:1\nT:Multi Rest\nM:4/4\nL:1/4\nK:C\nC D E F | Z2 | G A B c |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<multiple-rest>2</multiple-rest>"),
        "precondition: Z2 emits a multiple-rest of 2"
    );
    let score = assert_idempotent_full(abc);
    // The first measure of the rest run (measure index 1, number 2) carries the
    // multiple_rest count; the rest of the run does not.
    let with_mr = score.parts[0].voices[0]
        .measures
        .iter()
        .filter(|m| m.multiple_rest == Some(2))
        .count();
    assert_eq!(
        with_mr, 1,
        "exactly one measure carries multiple_rest = Some(2)"
    );
}

#[test]
fn two_voice_overlay_reconstructs_second_voice() {
    // A `&` overlay inside one voice forces a <backup> and a <voice>2 block.
    // The reader reconstructs the second voice as an additional Part.voices
    // entry so the writer re-emits the identical <voice>1 .. <backup> .. <voice>2.
    let abc = "X:1\nT:Overlay\nM:4/4\nL:1/4\nK:C\nC2 D2 & E2 F2 |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<backup>") && x1.contains("<voice>2</voice>"),
        "precondition: the overlay emits a <backup> and a <voice>2 block"
    );
    let score = assert_idempotent_full(abc);
    assert_eq!(
        score.parts[0].voices.len(),
        2,
        "the overlay reconstructs a second voice in the part"
    );
    // Voice 2 carries the E/F notes at onsets 0 and 1/2.
    let v2 = &score.parts[0].voices[1];
    assert_eq!(v2.events.len(), 2, "voice 2 has two notes");
    assert_eq!(
        v2.events[0].onset,
        Fraction::zero(),
        "voice 2 restarts at onset 0"
    );
    assert_eq!(
        v2.events[1].onset,
        Fraction::new(1, 2),
        "second voice-2 note at 1/2"
    );
}

#[test]
fn three_voice_overlay_round_trips() {
    // Two `&` overlays produce <voice>1/2/3 separated by two <backup>s.
    let abc = "X:1\nT:Triple\nM:4/4\nL:1/4\nK:C\nC2 D2 & E2 F2 & G2 A2 |\n";
    let x1 = export(abc);
    assert_eq!(
        x1.matches("<backup>").count(),
        2,
        "precondition: two overlays emit two backups"
    );
    assert!(
        x1.contains("<voice>3</voice>"),
        "precondition: a third voice"
    );
    let score = assert_idempotent_full(abc);
    assert_eq!(score.parts[0].voices.len(), 3, "three reconstructed voices");
}

#[test]
fn unequal_voice_lengths_round_trip() {
    // Voice 1 is a full bar; the overlay (voice 2) is half a bar. The writer
    // emits a single <backup> of the full voice-1 duration before voice 2.
    let abc = "X:1\nT:Unequal\nM:4/4\nL:1/4\nK:C\nC2 D2 E2 F2 & G2 A2 |\n";
    let score = assert_idempotent_full(abc);
    assert_eq!(score.parts[0].voices.len(), 2);
    assert_eq!(
        score.parts[0].voices[0].events.len(),
        4,
        "voice 1: four notes"
    );
    assert_eq!(
        score.parts[0].voices[1].events.len(),
        2,
        "voice 2: two notes"
    );
}

#[test]
fn two_voice_with_direction_round_trips() {
    // A dynamic on the main voice plus an overlay: the voice-bearing direction
    // must attach to its own voice's note and re-emit with the correct <voice>.
    let abc = "X:1\nT:Dyn Overlay\nM:4/4\nL:1/4\nK:C\n!f!C2 D2 & E2 F2 |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<dynamics>") && x1.contains("<backup>"),
        "precondition: a dynamic and an overlay backup are both emitted"
    );
    assert_idempotent_full(abc);
}

#[test]
fn two_voice_overlay_with_measure_rest_round_trips() {
    // The overlay voice is a full-measure rest (z4); the writer emits
    // <rest measure="yes"> for voice 2. The reader must reconstruct the
    // overlay voice's measure expected/actual so the attribute re-emits.
    let abc = "X:1\nT:Rest Overlay\nM:4/4\nL:1/4\nK:C\nC2 D2 E2 F2 & z4 |\n";
    let x1 = export(abc);
    if x1.contains("<backup>") {
        assert_idempotent_full(abc);
    }
}

#[test]
fn grace_in_overlay_voice_round_trips() {
    // A grace group on the main voice plus an overlay. Grace notes carry their
    // own <voice>, so the per-voice grace run must finalise onto its own voice's
    // following main note (not leak across the backup into the overlay).
    let abc = "X:1\nT:Grace Overlay\nM:4/4\nL:1/4\nK:C\n{ag}C2 D2 & E2 F2 |\n";
    let x1 = export(abc);
    if x1.contains("<backup>") && x1.contains("<grace") {
        assert_idempotent_full(abc);
    }
}

#[test]
fn chord_in_overlay_round_trips() {
    // A chord on the main voice plus an overlay: the per-voice chord head /
    // <chord/> folding must stay scoped to its own voice.
    let abc = "X:1\nT:Chord Overlay\nM:4/4\nL:1/4\nK:C\n[CEG]2 D2 & E2 F2 |\n";
    let x1 = export(abc);
    if x1.contains("<backup>") && x1.contains("<chord/>") {
        assert_idempotent_full(abc);
    }
}

#[test]
fn multiple_rest_second_bar_is_plain_measure_rest() {
    // The Z2 run's SECOND bar is an ordinary <rest measure="yes"> with no
    // multiple-rest glyph; only the first bar carries the count.
    let abc = "X:1\nT:Multi Rest 2\nM:4/4\nL:1/4\nK:C\nC D E F | Z3 | G A B c |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<multiple-rest>3</multiple-rest>"),
        "precondition: Z3 emits a multiple-rest of 3"
    );
    let score = assert_idempotent_full(abc);
    let counts: Vec<_> = score.parts[0].voices[0]
        .measures
        .iter()
        .filter_map(|m| m.multiple_rest)
        .collect();
    assert_eq!(
        counts,
        vec![3],
        "exactly one measure carries multiple_rest = 3"
    );
}

// --- Corpus measurement (env-gated; mirrors croma-fmt::corpus_proof) --------

/// Collect every `*.abc` file directly under `dir`, sorted.
fn abc_files(dir: &Path) -> Vec<PathBuf> {
    let mut files: Vec<PathBuf> = match fs::read_dir(dir) {
        Ok(entries) => entries
            .filter_map(Result::ok)
            .map(|entry| entry.path())
            .filter(|path| path.extension().is_some_and(|ext| ext == "abc"))
            .collect(),
        Err(_) => Vec::new(),
    };
    files.sort();
    files
}

/// The first XML tag at which two documents diverge (line-oriented, since the
/// writer emits one element per line). `None` when the strings are equal.
fn first_diverging_tag(x1: &str, x2: &str) -> Option<String> {
    for (line1, line2) in x1.lines().zip(x2.lines()) {
        if line1 != line2 {
            return Some(tag_of(line1).unwrap_or_else(|| tag_of(line2).unwrap_or("?".to_owned())));
        }
    }
    // One is a prefix of the other: name the first extra line's tag.
    let (longer, shorter) = if x1.lines().count() >= x2.lines().count() {
        (x1, x2)
    } else {
        (x2, x1)
    };
    longer.lines().nth(shorter.lines().count()).and_then(tag_of)
}

/// Extract the element name from a writer-emitted line like `  <note>` or
/// `  </measure>` or `  <clef number="1">`.
fn tag_of(line: &str) -> Option<String> {
    let trimmed = line.trim();
    let rest = trimmed.strip_prefix('<')?;
    let rest = rest.strip_prefix('/').unwrap_or(rest);
    let name: String = rest
        .chars()
        .take_while(|c| !c.is_whitespace() && *c != '>' && *c != '/')
        .collect();
    (!name.is_empty()).then_some(name)
}

/// Strip the writer-emitted blocks for elements that belong to **later stages**
/// (S2 `<key>`/`<time>`, S3 `<score-instrument>`/`<midi-instrument>`), giving
/// the "S1-supported subset" view. A file that is byte-equal after this strip is
/// one S1 fully reconstructs modulo the deferred stages โ€” the honest secondary
/// metric alongside the strict full-byte count.
fn strip_deferred_blocks(xml: &str) -> String {
    let mut out = String::with_capacity(xml.len());
    let mut skip_until: Option<&'static str> = None;
    for line in xml.lines() {
        if let Some(close) = skip_until {
            if line.trim() == close {
                skip_until = None;
            }
            continue;
        }
        let trimmed = line.trim();
        if trimmed == "<key>" {
            skip_until = Some("</key>");
        } else if trimmed == "<time>" || trimmed.starts_with("<time ") {
            skip_until = Some("</time>");
        } else if trimmed.starts_with("<score-instrument") {
            skip_until = Some("</score-instrument>");
        } else if trimmed.starts_with("<midi-instrument") {
            skip_until = Some("</midi-instrument>");
        } else {
            out.push_str(line);
            out.push('\n');
        }
    }
    out
}

#[test]
fn corpus_idempotence_measurement() {
    let Ok(root) = std::env::var("ABC_ROOT") else {
        eprintln!("ABC_ROOT unset โ€” skipping S1 corpus idempotence measurement");
        return;
    };
    let files = abc_files(&PathBuf::from(&root));
    if files.is_empty() {
        eprintln!("no .abc files under {root} โ€” skipping");
        return;
    }

    let mut total = 0usize;
    let mut exported = 0usize;
    let mut idempotent = 0usize;
    let mut idempotent_supported = 0usize;
    let mut divergences: BTreeMap<String, usize> = BTreeMap::new();
    // When `READER_IDEMPOTENT_LIST` names a path, the sorted list of strictly
    // idempotent files is written there. Two runs (baseline vs a change) can then
    // be set-diffed to prove "0 regressions" for a fix โ€” exactly the gate the S6e
    // ordering edge required.
    let mut idempotent_names: Vec<String> = Vec::new();

    for path in &files {
        let Ok(bytes) = fs::read(path) else { continue };
        let source = String::from_utf8_lossy(&bytes);
        total += 1;

        // Only files that export cleanly have an X1 to invert.
        let Ok(export) = export_musicxml(&source) else {
            continue;
        };
        exported += 1;
        let x1 = export.musicxml;

        let report = read_musicxml(&x1);
        let x2 = write_musicxml(&report.value).musicxml;

        if x1 == x2 {
            idempotent += 1;
            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                idempotent_names.push(name.to_owned());
            }
        } else if let Some(tag) = first_diverging_tag(&x1, &x2) {
            *divergences.entry(tag).or_default() += 1;
        } else {
            *divergences
                .entry("<equal-lines-unequal-bytes>".to_owned())
                .or_default() += 1;
        }

        // Secondary, honest "supported subset" metric: equal once the deferred
        // S2/S3 blocks are removed from both sides.
        if strip_deferred_blocks(&x1) == strip_deferred_blocks(&x2) {
            idempotent_supported += 1;
        }
    }

    if let Ok(list_path) = std::env::var("READER_IDEMPOTENT_LIST") {
        idempotent_names.sort();
        let _ = fs::write(&list_path, idempotent_names.join("\n"));
        eprintln!(
            "wrote {} idempotent file names to {list_path}",
            idempotent_names.len()
        );
    }

    let mut top: Vec<(String, usize)> = divergences.into_iter().collect();
    top.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));

    eprintln!(
        "reader corpus idempotence (strict, full bytes): {idempotent}/{exported} exported files round-trip ({total} total .abc)"
    );
    eprintln!(
        "reader corpus idempotence (supported subset, deferred S2/S3 blocks stripped): {idempotent_supported}/{exported}"
    );
    eprintln!("reader top first-diverging tags:");
    for (tag, count) in top.iter().take(10) {
        eprintln!("  {tag}: {count}");
    }

    // The loop must be total (no panic) over the whole corpus. The pass count
    // depends on the corpus, which lives in croma-test, so the floor comes from
    // there: `READER_SELFLOOP_MIN` (set by croma-test's bootstrap to the
    // recorded baseline) turns a drop below it into a failure.
    assert!(exported > 0, "expected at least one corpus file to export");
    if let Some(min) = std::env::var("READER_SELFLOOP_MIN")
        .ok()
        .and_then(|value| value.trim().parse::<usize>().ok())
    {
        assert!(
            idempotent >= min,
            "reader self-loop regressed: {idempotent}/{exported} round-trip, baseline {min}"
        );
    }
}

// --- Totality fuzz (design ยง6: read_musicxml must not panic on any file) -----

/// Collect every file with one of `exts` directly under `dir`, sorted. Used to
/// gather the abc2xml reference `.musicxml`/`.xml` set for the fuzz arm.
fn files_with_ext(dir: &Path, exts: &[&str]) -> Vec<PathBuf> {
    let mut files: Vec<PathBuf> = match fs::read_dir(dir) {
        Ok(entries) => entries
            .filter_map(Result::ok)
            .map(|entry| entry.path())
            .filter(|path| {
                path.extension()
                    .and_then(|e| e.to_str())
                    .is_some_and(|ext| exts.contains(&ext))
            })
            .collect(),
        Err(_) => Vec::new(),
    };
    files.sort();
    files
}

/// Run `read_musicxml(input)` under `catch_unwind` and return `true` when it
/// completed without panicking. Totality (design ยง2.2/ยง6) requires this to be
/// `true` for every input โ€” well-formed croma output, the abc2xml dialect, and
/// hand-crafted garbage alike.
fn reads_without_panic(input: &str) -> bool {
    // `&str` is unwind-safe; `AssertUnwindSafe` wraps the closure capturing it so
    // a panic anywhere in the reader becomes a caught error rather than aborting
    // the test binary. The reader holds no `&mut` across the boundary.
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let _ = read_musicxml(input);
    }))
    .is_ok()
}

/// Design ยง6 (REQUIRED): `read_musicxml` must not panic on any file in croma's
/// own 10k exports OR the abc2xml reference set, plus a handful of hand-crafted
/// malformed inputs. Each arm reports how many files it actually exercised; the
/// reference arm SAYS SO when `REF_ROOT`/the reference dir is absent. A panic in
/// any arm is collected (naming the file) and fails the test rather than aborting.
#[test]
fn totality_fuzz_read_musicxml_never_panics() {
    // Quiet the default panic hook so a *caught* panic does not spew a backtrace
    // for every offending file; we report offenders ourselves. Restored at the end.
    let previous_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(|_| {}));

    // --- Arm 1: croma's own exports (always available via ABC_ROOT). ----------
    let mut own_exercised = 0usize;
    let mut own_panics: Vec<String> = Vec::new();
    match std::env::var("ABC_ROOT") {
        Ok(root) => {
            for path in abc_files(&PathBuf::from(&root)) {
                let Ok(bytes) = fs::read(&path) else { continue };
                let source = String::from_utf8_lossy(&bytes);
                // Only files that export cleanly produce XML to feed back.
                let Ok(export) = export_musicxml(&source) else {
                    continue;
                };
                own_exercised += 1;
                if !reads_without_panic(&export.musicxml) {
                    own_panics.push(path.display().to_string());
                }
            }
        }
        Err(_) => {
            eprintln!("totality fuzz: ABC_ROOT unset โ€” own-exports arm skipped");
        }
    }

    // --- Arm 2: the abc2xml reference set (raw bytes; via REF_ROOT). ----------
    // These are the abc2xml/music21 dialect โ€” elements croma's writer never
    // emits โ€” so this arm exercises totality on foreign input, not idempotence.
    let mut ref_exercised = 0usize;
    let mut ref_panics: Vec<String> = Vec::new();
    let mut ref_available = false;
    if let Ok(ref_root) = std::env::var("REF_ROOT") {
        let dir = PathBuf::from(&ref_root);
        let files = files_with_ext(&dir, &["musicxml", "xml"]);
        if files.is_empty() {
            eprintln!(
                "totality fuzz: REF_ROOT={ref_root} has no .musicxml/.xml files โ€” reference arm skipped"
            );
        } else {
            ref_available = true;
            for path in files {
                let Ok(bytes) = fs::read(&path) else { continue };
                let source = String::from_utf8_lossy(&bytes);
                ref_exercised += 1;
                if !reads_without_panic(&source) {
                    ref_panics.push(path.display().to_string());
                }
            }
        }
    } else {
        eprintln!("totality fuzz: REF_ROOT unset โ€” abc2xml reference arm UNAVAILABLE (skipped)");
    }

    // --- Arm 3: hand-crafted malformed inputs (always run). -------------------
    // Two classes, both of which must NEVER panic:
    //
    // `must_diagnose` โ€” genuinely malformed / unsupported documents (un-parseable
    //   XML, a non-MusicXML or timewise root, out-of-spec numbers). These degrade
    //   to a minimal Score PLUS at least one reader diagnostic.
    //
    // `no_panic_only` โ€” well-formed-but-degenerate documents the reader is
    //   designed to accept silently: an empty-but-valid `<score-partwise>` and a
    //   tree sprinkled with unknown elements. Per design ยง2.2 unknown elements are
    //   "ignored (+ OPTIONAL diagnostic)", so these are asserted not to panic but
    //   are NOT required to warn.
    let must_diagnose: &[&str] = &[
        // Truncated / not well-formed XML (roxmltree parse error).
        "<score-partwise><part></broken>",
        "not xml at all <<< >>>",
        "<?xml version=\"1.0\"?>",
        // Well-formed XML whose root is not a partwise score.
        "<?xml version=\"1.0\"?><html><body>nope</body></html>",
        "<?xml version=\"1.0\"?><score-timewise></score-timewise>",
        // Bad numbers everywhere the reader parses an integer/float.
        "<score-partwise><part-list><score-part id=\"P1\"><midi-instrument id=\"x\">\
         <midi-channel>NaN</midi-channel><midi-program>-7</midi-program>\
         <volume>lots</volume><pan>left</pan></midi-instrument></score-part></part-list>\
         <part id=\"P1\"><measure number=\"one\">\
         <attributes><divisions>zero</divisions><key><fifths>sharp</fifths></key>\
         <time><beats>x</beats><beat-type>y</beat-type></time>\
         <transpose><chromatic>lots</chromatic></transpose></attributes>\
         <note><pitch><step>H</step><octave>nine</octave><alter>up</alter></pitch>\
         <duration>long</duration><voice>v</voice></note>\
         <forward><duration>bad</duration></forward>\
         <backup><duration>bad</duration></backup>\
         </measure></part></score-partwise>",
        // A grace run with no following note and no host (the S6e fallback arm).
        "<score-partwise><part id=\"P1\"><measure number=\"1\">\
         <note><grace/><pitch><step>A</step><octave>5</octave></pitch><voice>1</voice>\
         <notations><tuplet type=\"stop\" number=\"9\"/></notations></note>\
         <note><chord/><pitch><step>C</step><octave>5</octave></pitch>\
         <duration>8</duration><voice>1</voice></note>\
         </measure></part></score-partwise>",
    ];
    // Inputs that must merely NOT panic (silent acceptance is in spec).
    let no_panic_only: &[&str] = &[
        "",
        "   \n\t  ",
        // Empty but well-formed partwise score (no parts) โ€” legitimately empty.
        "<score-partwise></score-partwise>",
        // Unknown elements scattered through an otherwise-valid tree.
        "<score-partwise><part id=\"P1\"><measure number=\"1\">\
         <quux><frob/></quux><note><blarg/><pitch><step>C</step><octave>4</octave></pitch>\
         <duration>8</duration><voice>1</voice><notations><wibble/></notations></note>\
         </measure></part></score-partwise>",
    ];
    let mut malformed_panics: Vec<String> = Vec::new();
    let mut malformed_without_diagnostic: Vec<String> = Vec::new();
    for (i, input) in must_diagnose.iter().enumerate() {
        let caught =
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| read_musicxml(input)));
        match caught {
            Ok(report) => {
                if report.diagnostics.is_empty() {
                    malformed_without_diagnostic.push(format!("must_diagnose #{i}: {input:.60?}"));
                }
            }
            Err(_) => malformed_panics.push(format!("must_diagnose #{i}: {input:.60?}")),
        }
    }
    for (i, input) in no_panic_only.iter().enumerate() {
        if !reads_without_panic(input) {
            malformed_panics.push(format!("no_panic_only #{i}: {input:.60?}"));
        }
    }
    let malformed_total = must_diagnose.len() + no_panic_only.len();

    // Restore the panic hook before asserting (so a genuine test-framework panic
    // still prints normally).
    std::panic::set_hook(previous_hook);

    eprintln!(
        "totality fuzz: own-exports exercised {own_exercised} files ({} panicked); \
         abc2xml-reference {} ({ref_exercised} files, {} panicked); \
         malformed cases {} ({} panicked, {} missing diagnostic)",
        own_panics.len(),
        if ref_available {
            "available"
        } else {
            "UNAVAILABLE"
        },
        ref_panics.len(),
        malformed_total,
        malformed_panics.len(),
        malformed_without_diagnostic.len(),
    );

    // Totality assertions: ZERO panics anywhere, and every malformed input
    // produced a diagnostic.
    assert!(
        own_panics.is_empty(),
        "read_musicxml panicked on {} own-export file(s); first few: {:?}",
        own_panics.len(),
        own_panics.iter().take(5).collect::<Vec<_>>()
    );
    assert!(
        ref_panics.is_empty(),
        "read_musicxml panicked on {} abc2xml-reference file(s); first few: {:?}",
        ref_panics.len(),
        ref_panics.iter().take(5).collect::<Vec<_>>()
    );
    assert!(
        malformed_panics.is_empty(),
        "read_musicxml panicked on malformed input(s): {malformed_panics:?}"
    );
    assert!(
        malformed_without_diagnostic.is_empty(),
        "malformed input(s) produced NO diagnostic (must degrade with a warning): {malformed_without_diagnostic:?}"
    );
}

// --- R1b: complete_score_for_abc (the ABC-projection completion pass) ---------

#[cfg(feature = "musicxml-reader")]
mod abc_completion {
    use super::*;
    use crate::model::BarlineKind;
    use crate::musicxml::read::complete_score_for_abc;
    use crate::to_abc::{AbcWriteOptions, write_abc};
    use crate::{LowerOptions, ParseOptions, lower_score, parse_document};

    /// Reconstruct a Score from `abc`'s forward MusicXML and run the ABC
    /// completion pass โ€” exactly what `croma read --format abc` does.
    fn completed_from_abc(abc: &str) -> Score {
        let x1 = export(abc);
        let mut score = read_musicxml(&x1).value;
        complete_score_for_abc(&mut score);
        score
    }

    /// Reconstruct a Score from foreign MusicXML and run the ABC completion pass.
    fn completed_from_xml(xml: &str) -> Score {
        let mut score = read_musicxml(xml).value;
        complete_score_for_abc(&mut score);
        score
    }

    fn lyric_block<'a>(xml: &'a str, text: &str) -> &'a str {
        let text_pos = xml
            .find(&format!("<text>{text}</text>"))
            .unwrap_or_else(|| panic!("lyric text {text:?} not found in:\n{xml}"));
        let start = xml[..text_pos]
            .rfind("<lyric")
            .expect("lyric text should be inside a lyric block");
        let end = xml[text_pos..]
            .find("</lyric>")
            .map(|offset| text_pos + offset + "</lyric>".len())
            .expect("lyric block should close");
        &xml[start..end]
    }

    fn measure_block<'a>(xml: &'a str, number: &str) -> &'a str {
        let marker = format!("<measure number=\"{number}\"");
        let start = xml
            .find(&marker)
            .unwrap_or_else(|| panic!("measure {number:?} not found in:\n{xml}"));
        let end = xml[start..]
            .find("</measure>")
            .map(|offset| start + offset + "</measure>".len())
            .expect("measure block should close");
        &xml[start..end]
    }

    fn first_time_block(xml: &str) -> &str {
        let start = xml
            .find("<time")
            .unwrap_or_else(|| panic!("time block not found in:\n{xml}"));
        let end = xml[start..]
            .find("</time>")
            .map(|offset| start + offset + "</time>".len())
            .expect("time block should close");
        &xml[start..end]
    }

    fn foreign_time_score(time_xml: &str) -> String {
        format!(
            r#"<?xml version="1.0"?>
<score-partwise>
  <part-list><score-part id="P1"><part-name>T</part-name></score-part></part-list>
  <part id="P1">
    <measure number="1">
      <attributes><divisions>4</divisions>{time_xml}</attributes>
      <note><pitch><step>C</step><octave>4</octave></pitch><duration>4</duration><voice>1</voice><type>quarter</type></note>
    </measure>
  </part>
</score-partwise>
"#
        )
    }

    fn note_block(xml: &str, index: usize) -> &str {
        let mut cursor = 0usize;
        let mut start = None;
        for _ in 0..=index {
            let found = xml[cursor..]
                .find("<note>")
                .map(|offset| cursor + offset)
                .unwrap_or_else(|| panic!("note {index} not found in:\n{xml}"));
            start = Some(found);
            cursor = found + "<note>".len();
        }
        let start = start.expect("loop should set note start");
        let end = xml[start..]
            .find("</note>")
            .map(|offset| start + offset + "</note>".len())
            .expect("note block should close");
        &xml[start..end]
    }

    fn assert_same_note_verse_lyrics(xml: &str, texts: &[&str]) {
        let first_note = note_block(xml, 0);
        let second_note = note_block(xml, 1);
        assert_eq!(
            first_note.matches("<lyric number=\"1\">").count(),
            texts.len(),
            "first note should keep duplicate same-verse lyric siblings:\n{xml}"
        );
        for text in texts {
            assert!(
                first_note.contains(&format!("<text>{text}</text>")),
                "first note should contain lyric text {text:?}:\n{xml}"
            );
            assert!(
                !second_note.contains(&format!("<text>{text}</text>")),
                "duplicate lyric text {text:?} moved to the second note:\n{xml}"
            );
        }
    }

    /// Lower an ABC fixture to a Score (panicking on a lower failure).
    fn lower(abc: &str) -> Score {
        let document = parse_document(abc, ParseOptions::default()).value;
        lower_score(&document, LowerOptions)
            .value
            .expect("fixture ABC should lower cleanly")
    }

    /// Every barline kind in `voice.events`, in event order.
    fn event_barline_kinds(score: &Score) -> Vec<BarlineKind> {
        let mut kinds = Vec::new();
        for part in &score.parts {
            for voice in &part.voices {
                for event in &voice.events {
                    if let TimedEventKind::Barline(b) = &event.kind {
                        kinds.push(b.kind);
                    }
                }
            }
        }
        kinds
    }

    /// The flat (step, alter, octave) pitch sequence of voice 0 of every part.
    fn pitch_sequence(score: &Score) -> Vec<(char, i32, i32)> {
        let mut pitches = Vec::new();
        for part in &score.parts {
            for voice in &part.voices {
                for event in &voice.events {
                    if let TimedEventKind::Note(note) = &event.kind {
                        pitches.push((
                            note.pitch.step,
                            i32::from(note.pitch.alter),
                            i32::from(note.pitch.octave),
                        ));
                    }
                }
            }
        }
        pitches
    }

    /// Measure count = number of `Measure`s in voice 0 of part 0.
    fn measure_count(score: &Score) -> usize {
        score.parts[0].voices[0].measures.len()
    }

    /// The flat played-duration sequence of voice 0 of every part: the
    /// `event.duration` of every Note/Rest/Chord, in event order. This is the
    /// already-tuplet-scaled (sounding) duration the lowering carries โ€” the
    /// quantity the ABC projection must preserve through XML -> ABC -> Score.
    fn played_duration_sequence(score: &Score) -> Vec<crate::model::Rational> {
        let mut durations = Vec::new();
        for part in &score.parts {
            for voice in &part.voices {
                for event in &voice.events {
                    if matches!(
                        event.kind,
                        TimedEventKind::Note(_)
                            | TimedEventKind::Rest(_)
                            | TimedEventKind::Chord(_)
                    ) {
                        durations.push(event.duration);
                    }
                }
            }
        }
        durations
    }

    #[test]
    fn foreign_sound_tempo_without_metronome_projects_to_sound_tempo_carrier() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <direction placement=\"above\">\n",
            "        <direction-type><words>Fast</words></direction-type>\n",
            "        <sound tempo=\"132\"/>\n",
            "      </direction>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );
        let score = completed_from_xml(xml);
        let tempo = score.parts[0].voices[0]
            .events
            .iter()
            .find_map(|event| match &event.kind {
                TimedEventKind::TempoChange(tempo) => Some(tempo),
                _ => None,
            })
            .expect("sound tempo carrier should become a timed tempo event");
        assert_eq!(tempo.beat_role, TempoBeatRole::PlaybackSoundOnly);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:croma-sound-tempo bpm=132 beat-n=1 beat-d=4 text=\"Fast\"]"),
            "foreign playback-only <sound tempo> must use the croma carrier, not numeric Q:; got:\n{abc}"
        );
        let roundtrip =
            export_musicxml(&abc).expect("sound-tempo carrier ABC projection should export");
        assert!(
            roundtrip.musicxml.contains("<words>Fast</words>")
                && roundtrip.musicxml.contains("<sound tempo=\"132.00\"")
                && !roundtrip.musicxml.contains("<metronome>"),
            "playback-only sound tempo must not gain a printed metronome:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_direction_with_tempo_and_dynamic_preserves_both() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <direction placement=\"above\">\n",
            "        <direction-type><words>rall</words></direction-type>\n",
            "        <direction-type><dynamics><f/></dynamics></direction-type>\n",
            "        <sound tempo=\"120\"/>\n",
            "      </direction>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );
        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:croma-sound-tempo bpm=120 beat-n=1 beat-d=4 text=\"rall\"]"),
            "mixed direction must keep playback tempo carrier:\n{abc}"
        );
        assert!(
            abc.contains("!f!C"),
            "mixed direction must keep co-located dynamic on the next note:\n{abc}"
        );

        let roundtrip =
            export_musicxml(&abc).expect("mixed tempo+dynamic ABC projection should export");
        assert!(
            roundtrip.musicxml.contains("<words>rall</words>")
                && roundtrip.musicxml.contains("<sound tempo=\"120.00\"/>")
                && roundtrip.musicxml.contains("<dynamics>")
                && roundtrip.musicxml.contains("<f/>"),
            "MusicXML round trip must preserve tempo and dynamic:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_dynamic_and_wedge_placement_survive_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>Voice</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <direction placement=\"above\">\n",
            "        <direction-type><dynamics><p/></dynamics></direction-type>\n",
            "      </direction>\n",
            "      <direction placement=\"above\">\n",
            "        <direction-type><wedge type=\"crescendo\"/></direction-type>\n",
            "      </direction>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );
        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        let roundtrip =
            export_musicxml(&abc).expect("placed dynamic/wedge ABC projection should export");

        assert!(
            roundtrip.musicxml.contains("<dynamics>")
                && roundtrip.musicxml.contains("<p/>")
                && roundtrip.musicxml.contains("<wedge type=\"crescendo\"/>"),
            "dynamic and wedge must survive:\n{}",
            roundtrip.musicxml
        );
        assert_eq!(
            roundtrip
                .musicxml
                .matches("<direction placement=\"above\">")
                .count(),
            2,
            "both dynamic and wedge directions must stay above:\n{}",
            roundtrip.musicxml
        );
        assert_eq!(
            roundtrip
                .musicxml
                .matches("<direction placement=\"below\">")
                .count(),
            0,
            "placed imported directions must not fall back below:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn trailing_wedge_stop_on_spacer_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>Voice</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <direction placement=\"above\">\n",
            "        <direction-type><wedge type=\"crescendo\"/></direction-type>\n",
            "      </direction>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "      <direction placement=\"above\">\n",
            "        <direction-type><wedge type=\"stop\"/></direction-type>\n",
            "      </direction>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );
        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        let roundtrip =
            export_musicxml(&abc).expect("trailing wedge-stop ABC projection should export");

        assert_eq!(
            roundtrip
                .musicxml
                .matches("<wedge type=\"crescendo\"")
                .count(),
            1,
            "the wedge start must survive once:\n{}",
            roundtrip.musicxml
        );
        assert_eq!(
            roundtrip.musicxml.matches("<wedge type=\"stop\"").count(),
            1,
            "the trailing wedge stop must survive once:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_lyric_text_with_same_note_extend_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type>",
            "<lyric number=\"1\"><syllabic>single</syllabic><text>non</text><extend/></lyric>",
            "</note>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let direct_xml = write_score_partwise(&read_musicxml(xml).value).value;
        let direct_lyric = lyric_block(&direct_xml, "non");
        assert!(
            direct_lyric.contains("<text>non</text>") && direct_lyric.contains("<extend/>"),
            "direct MusicXML read/write must keep text+extend in one lyric block:\n{direct_xml}"
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:cr le=1]C"),
            "ABC projection needs a croma carrier because w: cannot spell same-note lyric extend:\n{abc}"
        );

        let roundtrip =
            export_musicxml(&abc).expect("lyric same-note extend carrier should export");
        let roundtrip_lyric = lyric_block(&roundtrip.musicxml, "non");
        assert!(
            roundtrip_lyric.contains("<text>non</text>") && roundtrip_lyric.contains("<extend/>"),
            "MusicXML round trip must keep text+extend in one lyric block:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_multi_verse_same_note_lyric_extends_survive_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type>",
            "<lyric number=\"1\"><syllabic>single</syllabic><text>one</text><extend/></lyric>",
            "<lyric number=\"2\"><syllabic>single</syllabic><text>two</text><extend/></lyric>",
            "</note>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:cr le=1]") && abc.contains("[I:cr le=2]"),
            "ABC projection should preserve each verse's same-note extend carrier:\n{abc}"
        );

        let roundtrip =
            export_musicxml(&abc).expect("multi-verse lyric same-note extends should export");
        for text in ["one", "two"] {
            let lyric = lyric_block(&roundtrip.musicxml, text);
            assert!(
                lyric.contains(&format!("<text>{text}</text>")) && lyric.contains("<extend/>"),
                "MusicXML round trip must keep text+extend for lyric {text:?}:\n{}",
                roundtrip.musicxml
            );
        }
    }

    #[test]
    fn foreign_duplicate_same_verse_lyrics_survive_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type>",
            "<lyric number=\"1\"><syllabic>single</syllabic><text>By</text></lyric>",
            "<lyric number=\"1\"><syllabic>single</syllabic><text>John</text></lyric>",
            "</note>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let direct_xml = write_score_partwise(&read_musicxml(xml).value).value;
        assert_same_note_verse_lyrics(&direct_xml, &["By", "John"]);

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("croma-lyric-duplicate verse=1 text=\"John\""),
            "ABC projection needs a croma carrier because w: cannot spell duplicate same-verse lyrics:\n{abc}"
        );
        let roundtrip =
            export_musicxml(&abc).expect("duplicate same-verse lyric ABC projection should export");
        assert_same_note_verse_lyrics(&roundtrip.musicxml, &["By", "John"]);
    }

    #[test]
    fn foreign_chord_head_lyric_keeps_alignment_in_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type>",
            "<lyric number=\"1\"><syllabic>single</syllabic><text>lead</text></lyric></note>\n",
            "      <note><chord/><pitch><step>E</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "      <note><pitch><step>G</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("w:lead *"),
            "the chord-head lyric must align to the first ABC lyric slot:\n{abc}"
        );

        let roundtrip = export_musicxml(&abc).expect("chord-head lyric ABC should export");
        let measure = measure_block(&roundtrip.musicxml, "1");
        let lyric = measure
            .find("<text>lead</text>")
            .unwrap_or_else(|| panic!("roundtrip must keep the lyric:\n{}", roundtrip.musicxml));
        let chord_member = measure
            .find("<chord/>")
            .unwrap_or_else(|| panic!("roundtrip must keep the chord:\n{}", roundtrip.musicxml));
        assert!(
            lyric < chord_member,
            "lyric must stay on the chord head, before the chord member note:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_chord_member_arpeggiate_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type>",
            "<notations><arpeggiate/></notations></note>\n",
            "      <note><chord/><pitch><step>E</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type>",
            "<notations><arpeggiate/></notations></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let direct_xml = write_score_partwise(&read_musicxml(xml).value).value;
        assert_eq!(
            direct_xml.matches("<arpeggiate/>").count(),
            2,
            "precondition: the reader model preserves head and member arpeggiate"
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[C!arpeggio!E]"),
            "member arpeggiate must be projected inside the ABC chord:\n{abc}"
        );
        let roundtrip =
            export_musicxml(&abc).expect("chord-member arpeggiate ABC projection should export");
        let measure = measure_block(&roundtrip.musicxml, "1");
        assert_eq!(
            measure.matches("<arpeggiate/>").count(),
            2,
            "roundtrip must keep arpeggiate on the chord head and member:\nABC:\n{abc}\nXML:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_duplicate_same_verse_lyric_with_inline_delimiter_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type>",
            "<lyric number=\"1\"><syllabic>single</syllabic><text>By</text></lyric>",
            "<lyric number=\"1\"><syllabic>single</syllabic><text>A]B</text></lyric>",
            "</note>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        let roundtrip = export_musicxml(&abc)
            .expect("duplicate same-verse lyric delimiter carrier should export");
        assert_same_note_verse_lyrics(&roundtrip.musicxml, &["By", "A]B"]);
    }

    #[test]
    fn foreign_duplicate_same_verse_lyric_with_comment_marker_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type>",
            "<lyric number=\"1\"><syllabic>single</syllabic><text>By</text></lyric>",
            "<lyric number=\"1\"><syllabic>single</syllabic><text>A%B</text></lyric>",
            "</note>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        let roundtrip = export_musicxml(&abc)
            .expect("duplicate same-verse lyric percent carrier should export");
        assert_same_note_verse_lyrics(&roundtrip.musicxml, &["By", "A%B"]);
    }

    #[test]
    fn foreign_sparse_voice_keeps_measure_offset_in_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "    <measure number=\"2\">\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "      <backup><duration>4</duration></backup>\n",
            "      <note><pitch><step>E</step><octave>3</octave></pitch>",
            "<duration>4</duration><voice>5</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        let roundtrip = export_musicxml(&abc).expect("sparse voice ABC should export");
        let first_measure = measure_block(&roundtrip.musicxml, "1");
        let second_measure = measure_block(&roundtrip.musicxml, "2");
        assert!(
            !first_measure.contains("<voice>5</voice>")
                && second_measure.contains("<voice>5</voice>"),
            "the sparse voice starts in measure 2 and must not be projected into measure 1; abc:\n{abc}\nxml:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_backup_forward_voice_offset_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>16</duration><voice>1</voice><type>whole</type></note>\n",
            "      <backup><duration>16</duration></backup>\n",
            "      <forward><duration>8</duration></forward>\n",
            "      <note><pitch><step>E</step><octave>3</octave></pitch>",
            "<duration>8</duration><voice>2</voice><type>half</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:cr mf]"),
            "ABC projection needs a croma carrier for a MusicXML <forward> cursor gap:\n{abc}"
        );

        let roundtrip =
            export_musicxml(&abc).expect("backup/forward voice-offset ABC should export");
        let measure = measure_block(&roundtrip.musicxml, "1");
        let backup = measure
            .find("<backup>")
            .unwrap_or_else(|| panic!("roundtrip must keep backup:\n{}", roundtrip.musicxml));
        let forward = measure
            .find("<forward>")
            .unwrap_or_else(|| panic!("roundtrip must keep forward:\n{}", roundtrip.musicxml));
        let voice2 = measure
            .find("<voice>2</voice>")
            .unwrap_or_else(|| panic!("roundtrip must keep voice 2 note:\n{}", roundtrip.musicxml));
        let forward_block = &measure[forward..voice2];
        assert!(
            backup < forward && forward < voice2,
            "forward must stay between backup and the offset voice-2 note:\n{}",
            roundtrip.musicxml
        );
        assert!(
            forward_block.contains("<duration>16</duration>"),
            "forward must keep the half-measure cursor-gap duration in the exported divisions:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn backup_positioned_meter_restatement_does_not_synthesize_forward() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>16</duration><voice>1</voice><type>whole</type></note>\n",
            "      <backup><duration>16</duration></backup>\n",
            "      <attributes><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <note><pitch><step>E</step><octave>3</octave></pitch>",
            "<duration>16</duration><voice>5</voice><type>whole</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            !abc.contains("[I:cr mf]"),
            "a restatement after a backup must not rewind the ABC gap cursor and create a fake forward:\n{abc}"
        );

        let roundtrip =
            export_musicxml(&abc).expect("backup-positioned meter restatement should export");
        let measure = measure_block(&roundtrip.musicxml, "1");
        assert!(
            measure.contains("<backup>") && !measure.contains("<forward>"),
            "roundtrip must keep the backup into voice 5 without inventing a forward:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_post_backup_clef_cursor_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>16</duration><voice>1</voice><type>whole</type></note>\n",
            "      <backup><duration>16</duration></backup>\n",
            "      <note><pitch><step>E</step><octave>3</octave></pitch>",
            "<duration>16</duration><voice>5</voice><type>whole</type></note>\n",
            "      <backup><duration>4</duration></backup>\n",
            "      <attributes><clef><sign>F</sign><line>4</line></clef></attributes>\n",
            "      <forward><duration>4</duration></forward>\n",
            "      <backup><duration>16</duration></backup>\n",
            "      <note><pitch><step>G</step><octave>3</octave></pitch>",
            "<duration>16</duration><voice>6</voice><type>whole</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:croma-clef-cursor "),
            "ABC projection needs a private carrier for a post-backup MusicXML clef cursor:\n{abc}"
        );

        let roundtrip = export_musicxml(&abc).expect("post-backup clef cursor ABC should export");
        let measure = measure_block(&roundtrip.musicxml, "1");
        let bass_sign = measure.find("<sign>F</sign>").unwrap_or_else(|| {
            panic!("roundtrip must keep the bass clef:\n{}", roundtrip.musicxml)
        });
        let clef = measure[..bass_sign]
            .rfind("<clef>")
            .unwrap_or_else(|| panic!("bass clef sign must be inside a clef block:\n{measure}"));
        let first_backup = measure[..clef]
            .rfind("<backup>")
            .unwrap_or_else(|| panic!("clef must be preceded by its short backup:\n{measure}"));
        let forward = measure[clef..]
            .find("<forward>")
            .map(|offset| clef + offset)
            .unwrap_or_else(|| {
                panic!("clef must be followed by its cursor-restoring forward:\n{measure}")
            });
        let voice6 = measure
            .find("<voice>6</voice>")
            .unwrap_or_else(|| panic!("roundtrip must keep voice 6:\n{}", roundtrip.musicxml));
        let second_backup = measure[forward..voice6]
            .find("<backup>")
            .map(|offset| forward + offset)
            .unwrap_or_else(|| {
                panic!("voice 6 must still have its own full-measure backup:\n{measure}")
            });
        assert!(
            first_backup < clef
                && clef < forward
                && forward < second_backup
                && second_backup < voice6,
            "roundtrip must preserve backup -> clef -> forward -> backup -> voice ordering:\n{}",
            roundtrip.musicxml
        );
        assert!(
            measure[first_backup..clef].contains("<duration>8</duration>")
                && measure[forward..second_backup].contains("<duration>8</duration>"),
            "clef cursor backup/forward must keep the same one-quarter duration:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_chained_clef_cursor_before_rest_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <note><pitch><step>E</step><octave>4</octave></pitch>",
            "<duration>12</duration><voice>1</voice><type>half</type><dot/></note>\n",
            "      <backup><duration>10</duration></backup>\n",
            "      <attributes><clef><sign>F</sign><line>4</line></clef></attributes>\n",
            "      <forward><duration>8</duration></forward>\n",
            "      <attributes><clef><sign>G</sign><line>2</line></clef></attributes>\n",
            "      <forward><duration>2</duration></forward>\n",
            "      <note><rest/><duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        let roundtrip =
            export_musicxml(&abc).expect("chained clef cursor carrier ABC should export");
        let measure = measure_block(&roundtrip.musicxml, "1");
        let bass_sign = measure.find("<sign>F</sign>").unwrap_or_else(|| {
            panic!("roundtrip must keep the bass clef:\n{}", roundtrip.musicxml)
        });
        let bass_clef = measure[..bass_sign]
            .rfind("<clef>")
            .unwrap_or_else(|| panic!("bass clef sign must be inside a clef block:\n{measure}"));
        let treble_sign = measure[bass_sign..]
            .find("<sign>G</sign>")
            .map(|offset| bass_sign + offset)
            .unwrap_or_else(|| panic!("roundtrip must keep the second treble clef:\n{measure}"));
        let treble_clef = measure[..treble_sign]
            .rfind("<clef>")
            .unwrap_or_else(|| panic!("treble clef sign must be inside a clef block:\n{measure}"));
        let first_forward = measure[bass_clef..treble_clef]
            .find("<forward>")
            .map(|offset| bass_clef + offset)
            .unwrap_or_else(|| panic!("bass clef must be followed by a forward:\n{measure}"));
        assert!(
            !measure[first_forward..treble_clef].contains("<backup>"),
            "chained clef cursor restore must not insert a backup between the two clefs:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_overbackup_between_voice_sequences_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <note><pitch><step>E</step><octave>4</octave></pitch>",
            "<duration>12</duration><voice>1</voice><type>half</type><dot/></note>\n",
            "      <backup><duration>16</duration></backup>\n",
            "      <note><pitch><step>G</step><octave>3</octave></pitch>",
            "<duration>4</duration><voice>5</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:croma-musicxml-sequence-backup "),
            "ABC projection needs a private carrier for over-backup before a voice sequence:\n{abc}"
        );

        let roundtrip = export_musicxml(&abc).expect("over-backup carrier ABC should export");
        let measure = measure_block(&roundtrip.musicxml, "1");
        let voice5 = measure
            .find("<voice>5</voice>")
            .unwrap_or_else(|| panic!("roundtrip must keep voice 5:\n{}", roundtrip.musicxml));
        let backup = measure[..voice5]
            .rfind("<backup>")
            .unwrap_or_else(|| panic!("voice 5 must be preceded by a backup:\n{measure}"));
        assert!(
            measure[backup..voice5].contains("<duration>32</duration>"),
            "roundtrip must keep the original four-quarter backup before voice 5:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_trailing_forward_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>16</duration><voice>1</voice><type>whole</type></note>\n",
            "      <backup><duration>16</duration></backup>\n",
            "      <note><pitch><step>E</step><octave>3</octave></pitch>",
            "<duration>4</duration><voice>2</voice><type>quarter</type></note>\n",
            "      <forward><duration>12</duration></forward>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:cr mf]"),
            "ABC projection needs a croma carrier for a trailing MusicXML <forward>:\n{abc}"
        );

        let roundtrip = export_musicxml(&abc).expect("trailing forward ABC should export");
        let measure = measure_block(&roundtrip.musicxml, "1");
        let voice2 = measure
            .find("<voice>2</voice>")
            .unwrap_or_else(|| panic!("roundtrip must keep voice 2 note:\n{}", roundtrip.musicxml));
        let forward = measure.find("<forward>").unwrap_or_else(|| {
            panic!(
                "roundtrip must keep trailing forward before the measure boundary:\n{}",
                roundtrip.musicxml
            )
        });
        let forward_block = &measure[forward..];
        assert!(
            voice2 < forward,
            "trailing forward must remain after the short voice-2 note:\n{}",
            roundtrip.musicxml
        );
        assert!(
            forward_block.contains("<duration>24</duration>"),
            "trailing forward must keep the remaining three-quarter cursor gap:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_forward_only_measure_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <forward><duration>16</duration></forward>\n",
            "    </measure>\n",
            "    <measure number=\"2\">\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>16</duration><voice>1</voice><type>whole</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:cr mf]"),
            "ABC projection needs a croma carrier for a forward-only measure:\n{abc}"
        );

        let roundtrip = export_musicxml(&abc).expect("forward-only measure ABC should export");
        let first_measure = measure_block(&roundtrip.musicxml, "1");
        assert!(
            first_measure.contains("<forward>")
                && first_measure.contains("<duration>32</duration>"),
            "roundtrip must keep the forward-only measure as a MusicXML <forward>:\n{}",
            roundtrip.musicxml
        );
        assert!(
            measure_block(&roundtrip.musicxml, "2").contains("<voice>1</voice>"),
            "the following note must stay in measure 2:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_ending_stop_on_regular_barline_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <barline location=\"left\"><ending number=\"2\" type=\"start\"/></barline>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>16</duration><voice>1</voice><type>whole</type></note>\n",
            "    </measure>\n",
            "    <measure number=\"2\">\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>16</duration><voice>1</voice><type>whole</type></note>\n",
            "      <barline location=\"right\"><ending number=\"2\" type=\"stop\"/></barline>\n",
            "    </measure>\n",
            "    <measure number=\"3\">\n",
            "      <note><pitch><step>E</step><octave>4</octave></pitch>",
            "<duration>16</duration><voice>1</voice><type>whole</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        let roundtrip =
            export_musicxml(&abc).expect("ending-stop-on-regular-barline ABC should export");
        let second_measure = measure_block(&roundtrip.musicxml, "2");
        assert!(
            second_measure.contains("<ending number=\"2\" type=\"stop\"/>"),
            "roundtrip must keep the explicit regular-barline ending stop in measure 2; abc:\n{abc}\nxml:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_ending_stop_on_left_barline_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <barline location=\"left\"><ending number=\"2\" type=\"start\"/></barline>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>16</duration><voice>1</voice><type>whole</type></note>\n",
            "    </measure>\n",
            "    <measure number=\"2\">\n",
            "      <barline location=\"left\"><ending number=\"2\" type=\"stop\"/></barline>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>16</duration><voice>1</voice><type>whole</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        let roundtrip = export_musicxml(&abc).expect("left ending-stop carrier ABC should export");
        let second_measure = measure_block(&roundtrip.musicxml, "2");
        assert!(
            second_measure.contains("<barline location=\"left\">")
                && second_measure.contains("<ending number=\"2\" type=\"stop\"/>")
                && !second_measure.contains("<barline location=\"right\">"),
            "roundtrip must keep the explicit ending stop on measure 2's left barline; abc:\n{abc}\nxml:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_ending_discontinue_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <barline location=\"left\"><ending number=\"2\" type=\"start\"/></barline>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>16</duration><voice>1</voice><type>whole</type></note>\n",
            "      <barline location=\"right\"><ending number=\"2\" type=\"discontinue\"/></barline>\n",
            "    </measure>\n",
            "    <measure number=\"2\">\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>16</duration><voice>1</voice><type>whole</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        let roundtrip = export_musicxml(&abc).expect("ending-discontinue ABC should export");
        let first_measure = measure_block(&roundtrip.musicxml, "1");
        assert!(
            first_measure.contains("<ending number=\"2\" type=\"discontinue\"/>"),
            "roundtrip must keep explicit MusicXML ending discontinue, not normalize to stop; abc:\n{abc}\nxml:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_dashed_barline_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>16</duration><voice>1</voice><type>whole</type></note>\n",
            "      <barline location=\"right\"><bar-style>dashed</bar-style></barline>\n",
            "    </measure>\n",
            "    <measure number=\"2\">\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>16</duration><voice>1</voice><type>whole</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:croma-barline-style style=dashed]"),
            "ABC projection needs a croma carrier for a MusicXML dashed barline:\n{abc}"
        );

        let roundtrip = export_musicxml(&abc).expect("dashed barline ABC should export");
        let first_measure = measure_block(&roundtrip.musicxml, "1");
        assert!(
            first_measure.contains("<bar-style>dashed</bar-style>"),
            "roundtrip must keep MusicXML dashed barline style; abc:\n{abc}\nxml:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn dashed_barline_carrier_does_not_replace_repeat_end() {
        let abc = "X:1\nM:4/4\nL:1/8\nK:C\nC8 [I:croma-barline-style style=dashed]:|\n";
        let roundtrip = export_musicxml(abc).expect("dashed repeat-end ABC should export");
        let first_measure = measure_block(&roundtrip.musicxml, "1");
        assert!(
            first_measure.contains("<repeat direction=\"backward\"/>"),
            "barline style carrier must not drop repeat-end semantics:\n{}",
            roundtrip.musicxml
        );
        assert!(
            !first_measure.contains("<bar-style>dashed</bar-style>"),
            "dashed style carrier is only preserved for regular bars until mixed style+repeat is modeled:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_redundant_meter_restatement_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "    <measure number=\"2\">\n",
            "      <attributes><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:cr mr] [M:4/4]"),
            "ABC projection must carry a private marker so the no-op [M:] survives re-lowering:\n{abc}"
        );
        assert_eq!(
            write_abc(&lower(&abc), AbcWriteOptions::default()),
            abc,
            "the croma meter restatement carrier should be an ABC fixed point"
        );
        let roundtrip = export_musicxml(&abc).expect("redundant meter ABC should export");
        assert_eq!(
            roundtrip.musicxml.matches("<time>").count(),
            2,
            "MusicXML-origin repeated <time> must survive XML->ABC->XML; abc:\n{abc}\nxml:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_redundant_key_restatement_survives_abc_projection() {
        // A foreign source may restate the already-effective `<key>` mid-tune
        // (a system-break courtesy restatement). The ABC dedupe must not collapse
        // it: like meter, the reader marks it and a carrier forces re-recording
        // (PDMX 0109 / 0916).
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><key><fifths>-1</fifths></key></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "    <measure number=\"2\">\n",
            "      <attributes><key><fifths>-1</fifths></key></attributes>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:cr kr] [K:"),
            "ABC projection must carry a private marker so the no-op [K:] survives re-lowering:\n{abc}"
        );
        assert_eq!(
            write_abc(&lower(&abc), AbcWriteOptions::default()),
            abc,
            "the croma key restatement carrier should be an ABC fixed point"
        );
        let roundtrip = export_musicxml(&abc).expect("redundant key ABC should export");
        assert_eq!(
            roundtrip.musicxml.matches("<fifths>-1</fifths>").count(),
            2,
            "MusicXML-origin repeated <key> must survive XML->ABC->XML; abc:\n{abc}\nxml:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_grace_accidental_survives_clef_octave_shift() {
        // In a clef=treble-8 voice the writer emits anchor notes octave-shifted
        // but grace notes UNshifted, so the reader's accidental-carry simulation
        // must key its measure ledger on the EMITTED (written) octave. Otherwise a
        // C# anchor (written c') and a same-model-octave C# grace (written c)
        // collide in the ledger and the grace's sharp is dropped as if carried โ€”
        // re-parsing the bare grace then loses the alter (PDMX 0344 / 1793).
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>G</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions>\n",
            "        <clef><sign>G</sign><line>2</line><clef-octave-change>-1</clef-octave-change></clef>\n",
            "      </attributes>\n",
            "      <note><pitch><step>C</step><alter>1</alter><octave>5</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type><accidental>sharp</accidental></note>\n",
            "      <note><grace slash=\"yes\"/><pitch><step>C</step><alter>1</alter><octave>5</octave></pitch>",
            "<voice>1</voice><type>eighth</type></note>\n",
            "      <note><pitch><step>D</step><octave>5</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        let roundtrip = export_musicxml(&abc).expect("clef-octave grace ABC should export");
        assert_eq!(
            roundtrip.musicxml.matches("<alter>1</alter>").count(),
            2,
            "both the anchor and grace C# must keep their sharp through XML->ABC->XML; abc:\n{abc}\nxml:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_cut_time_symbol_keeps_source_beats_through_abc_projection() {
        let xml = foreign_time_score(
            "<time symbol=\"cut\"><beats>4</beats><beat-type>2</beat-type></time>",
        );

        let score = completed_from_xml(&xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("M:4/2"),
            "ABC projection must keep the real beats instead of collapsing to M:C|:\n{abc}"
        );

        let roundtrip = export_musicxml(&abc).expect("foreign cut-time ABC should export");
        let time = first_time_block(&roundtrip.musicxml);
        assert!(
            time.contains("<time symbol=\"cut\">")
                && time.contains("<beats>4</beats>")
                && time.contains("<beat-type>2</beat-type>"),
            "MusicXML symbol and beats must both survive XML->ABC->XML:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_common_time_symbol_keeps_source_beats_through_abc_projection() {
        let xml = foreign_time_score(
            "<time symbol=\"common\"><beats>2</beats><beat-type>2</beat-type></time>",
        );

        let score = completed_from_xml(&xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("M:2/2"),
            "ABC projection must keep the real beats instead of collapsing to M:C:\n{abc}"
        );

        let roundtrip = export_musicxml(&abc).expect("foreign common-time ABC should export");
        let time = first_time_block(&roundtrip.musicxml);
        assert!(
            time.contains("<time symbol=\"common\">")
                && time.contains("<beats>2</beats>")
                && time.contains("<beat-type>2</beat-type>"),
            "MusicXML symbol and beats must both survive XML->ABC->XML:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_numeric_common_meter_does_not_gain_time_symbol() {
        let xml = foreign_time_score("<time><beats>4</beats><beat-type>4</beat-type></time>");

        let score = completed_from_xml(&xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("M:4/4"),
            "numeric MusicXML 4/4 must project as numeric ABC, not M:C:\n{abc}"
        );

        let roundtrip = export_musicxml(&abc).expect("foreign numeric-time ABC should export");
        let time = first_time_block(&roundtrip.musicxml);
        assert!(
            !time.contains("symbol="),
            "numeric MusicXML 4/4 must not gain a common-time symbol:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_part_initial_meter_symbol_difference_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list>\n",
            "    <score-part id=\"P1\"><part-name>One</part-name></score-part>\n",
            "    <score-part id=\"P2\"><part-name>Two</part-name></score-part>\n",
            "  </part-list>\n",
            "  <part id=\"P1\"><measure number=\"1\">\n",
            "    <attributes><divisions>4</divisions>",
            "<time symbol=\"cut\"><beats>2</beats><beat-type>2</beat-type></time>",
            "</attributes>\n",
            "    <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "  </measure></part>\n",
            "  <part id=\"P2\"><measure number=\"1\">\n",
            "    <attributes><divisions>4</divisions>",
            "<time><beats>2</beats><beat-type>2</beat-type></time>",
            "</attributes>\n",
            "    <note><pitch><step>E</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "  </measure></part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("M:C|") && abc.contains("croma-initial-meter display=\"2/2\""),
            "ABC projection must preserve P2's numeric 2/2 initial meter separately from P1's cut-time header:\n{abc}"
        );

        let roundtrip = export_musicxml(&abc).expect("part-initial meter ABC should export");
        let p1 = measure_block(&roundtrip.musicxml, "1");
        let p2_start = roundtrip
            .musicxml
            .find("<part id=\"P2\">")
            .expect("P2 should exist");
        let p2 = measure_block(&roundtrip.musicxml[p2_start..], "1");
        assert!(
            first_time_block(p1).contains("<time symbol=\"cut\">"),
            "P1 must keep cut-time symbol:\n{}",
            roundtrip.musicxml
        );
        assert!(
            !first_time_block(p2).contains("symbol="),
            "P2 must keep numeric 2/2 without inheriting cut-time symbol:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_pitch_alter_without_accidental_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <note><pitch><step>F</step><alter>1</alter><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "      <note><grace/><pitch><step>C</step><alter>1</alter><octave>5</octave></pitch>",
            "<voice>1</voice><type>eighth</type></note>\n",
            "      <note><pitch><step>D</step><octave>5</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("^F") && abc.contains("{^c}"),
            "ABC projection must spell MusicXML <alter> values that lack <accidental>:\n{abc}"
        );
        assert_eq!(
            pitch_sequence(&lower(&abc)),
            pitch_sequence(&score),
            "MusicXML <alter> values must survive through ABC re-lowering:\n{abc}"
        );
        let roundtrip = export_musicxml(&abc).expect("altered pitch ABC should export");
        assert!(
            roundtrip.musicxml.matches("<alter>1</alter>").count() >= 2,
            "main and grace altered pitches must survive XML->ABC->XML:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_words_sound_120_without_metronome_keeps_playback_tempo() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <direction placement=\"above\">\n",
            "        <direction-type><words>rall</words></direction-type>\n",
            "        <sound tempo=\"120\"/>\n",
            "      </direction>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );
        let score = completed_from_xml(xml);
        let tempo = score.parts[0].voices[0]
            .events
            .iter()
            .find_map(|event| match &event.kind {
                TimedEventKind::TempoChange(tempo) => Some(tempo),
                _ => None,
            })
            .expect("sound tempo carrier should become a timed tempo event");
        assert_eq!(tempo.beat_role, TempoBeatRole::PlaybackSoundOnly);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:croma-sound-tempo bpm=120 beat-n=1 beat-d=4 text=\"rall\"]"),
            "foreign <sound tempo=\"120\"> is source tempo, not croma's old text-only fallback; got:\n{abc}"
        );
    }

    #[test]
    fn foreign_tempo_multiple_words_keeps_nonempty_text_and_beat() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <direction placement=\"above\">\n",
            "        <direction-type>\n",
            "          <metronome><beat-unit>quarter</beat-unit><per-minute>80</per-minute></metronome>\n",
            "        </direction-type>\n",
            "        <direction-type><words>\n</words><words>andante</words></direction-type>\n",
            "        <sound tempo=\"80\"/>\n",
            "      </direction>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );
        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("Q:\"andante\" 1/4=80\n"),
            "tempo text split across MusicXML words must survive as one nonempty ABC Q text; got:\n{abc}"
        );

        let roundtrip =
            export_musicxml(&abc).expect("multi-word tempo ABC projection should export");
        assert!(
            roundtrip.musicxml.contains("<words>andante</words>")
                && roundtrip.musicxml.contains("<per-minute>80</per-minute>"),
            "ABC projection must re-emit both tempo words and the metronome beat:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_tempo_text_is_normalized_to_one_line_q() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <direction placement=\"above\">\n",
            "        <direction-type><words>\nSwing\n</words></direction-type>\n",
            "        <direction-type><metronome><beat-unit>quarter</beat-unit><per-minute>112</per-minute></metronome></direction-type>\n",
            "        <sound tempo=\"112\"/>\n",
            "      </direction>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );
        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("Q:\"Swing\" 1/4=112\n"),
            "tempo text with XML whitespace must not split the ABC Q field; got:\n{abc}"
        );
        assert!(
            !abc.contains("Q:\"\n"),
            "tempo text must be normalized before ABC quoting; got:\n{abc}"
        );
    }

    #[test]
    fn foreign_tempo_text_with_quotes_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <direction><direction-type>",
            "<words>(robot and elaborated melody for \"funky town\" on D.C)</words>",
            "</direction-type></direction>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );
        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            // ABC 2.1 ยง8.2 spells a quote inside quoted text as `&quot;`.
            abc.contains("Q:\"(robot and elaborated melody for &quot;funky town&quot; on D.C)\""),
            "ABC projection must escape embedded tempo quotes:\n{abc}"
        );
        let roundtrip =
            export_musicxml(&abc).expect("quoted tempo text ABC projection should export");
        assert!(
            roundtrip.musicxml.contains(
                "<words>(robot and elaborated melody for &quot;funky town&quot; on D.C)</words>"
            ),
            "roundtrip must preserve embedded tempo quotes:\nABC:\n{abc}\nXML:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_mid_tune_tempo_text_with_bracket_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "    <measure number=\"2\">\n",
            "      <direction><direction-type>",
            "<words>Notes: Air - [Bass] bracket</words>",
            "<metronome><beat-unit>quarter</beat-unit><per-minute>84</per-minute></metronome>",
            "</direction-type></direction>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );
        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains(
                "[I:croma-tempo role=printed text-hex=4e6f7465733a20416972202d205b426173735d20627261636b6574 bpm=84 beat-n=1 beat-d=4]"
            ),
            "ABC projection must carry the bracketed tempo text and beat through a safe carrier:\n{abc}"
        );
        let roundtrip =
            export_musicxml(&abc).expect("bracketed tempo text ABC projection should export");
        assert!(
            roundtrip
                .musicxml
                .contains("<words>Notes: Air - [Bass] bracket</words>")
                && roundtrip.musicxml.contains("<per-minute>84</per-minute>"),
            "roundtrip must preserve tempo text containing ']' and its beat:\nABC:\n{abc}\nXML:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_header_tempo_text_with_percent_uses_safe_carrier() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <direction><direction-type>",
            "<words>50% swing</words>",
            "<metronome><beat-unit>quarter</beat-unit><per-minute>100</per-minute></metronome>",
            "</direction-type></direction>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );
        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            !abc.contains("Q:\"50% swing\""),
            "tempo text containing '%' must not be emitted through raw Q: syntax:\n{abc}"
        );
        assert!(
            abc.contains(
                "[I:croma-tempo role=printed text-hex=353025207377696e67 bpm=100 beat-n=1 beat-d=4]"
            ),
            "header tempo text containing '%' must use a safe carrier:\n{abc}"
        );
        let roundtrip =
            export_musicxml(&abc).expect("percent tempo text ABC projection should export");
        assert!(
            roundtrip.musicxml.contains("<words>50% swing</words>")
                && roundtrip.musicxml.contains("<per-minute>100</per-minute>"),
            "roundtrip must preserve header tempo text containing '%' and its beat:\nABC:\n{abc}\nXML:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_mid_tune_tempo_text_with_percent_uses_safe_carrier() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "    <measure number=\"2\">\n",
            "      <direction><direction-type>",
            "<words>50% swing</words>",
            "</direction-type></direction>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );
        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            !abc.contains("[Q:\"50% swing\"]"),
            "mid-tune tempo text containing '%' must not be emitted through raw inline Q: syntax:\n{abc}"
        );
        assert!(
            abc.contains("[I:croma-tempo role=printed text-hex=353025207377696e67]"),
            "mid-tune tempo text containing '%' must use a safe carrier:\n{abc}"
        );
        let roundtrip =
            export_musicxml(&abc).expect("percent tempo text ABC projection should export");
        assert!(
            roundtrip.musicxml.contains("<words>50% swing</words>"),
            "roundtrip must preserve mid-tune tempo text containing '%':\nABC:\n{abc}\nXML:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_bare_sound_tempo_projects_to_sound_tempo_carrier() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <direction><sound tempo=\"96\"/></direction>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );
        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:croma-sound-tempo bpm=96 beat-n=1 beat-d=4]"),
            "a bare foreign <sound tempo> must not be dropped or printed as Q:; got:\n{abc}"
        );
    }

    #[test]
    fn foreign_sound_tempo_text_with_bracket_uses_safe_carrier() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "      <direction><direction-type>",
            "<words>Push [rit.]</words>",
            "</direction-type><sound tempo=\"72\"/></direction>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );
        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains(
                "[I:croma-sound-tempo bpm=72 beat-n=1 beat-d=4 text-hex=50757368205b7269742e5d]"
            ),
            "playback-only tempo text containing ']' must use a safe carrier:\n{abc}"
        );
        let roundtrip = export_musicxml(&abc).expect("bracketed sound-tempo carrier should export");
        assert!(
            roundtrip.musicxml.contains("<words>Push [rit.]</words>")
                && roundtrip.musicxml.contains("<sound tempo=\"72.00\"/>"),
            "roundtrip must preserve playback-only tempo text and sound tempo:\nABC:\n{abc}\nXML:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_measure_number_zero_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"0\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <direction placement=\"above\">\n",
            "        <direction-type><metronome><beat-unit>quarter</beat-unit><per-minute>60</per-minute></metronome></direction-type>\n",
            "      </direction>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:croma-measure-number n=0]"),
            "MusicXML measure number 0 needs a private ABC carrier:\n{abc}"
        );

        let roundtrip = export_musicxml(&abc).expect("measure-number carrier should export");
        let measure_zero = measure_block(&roundtrip.musicxml, "0");
        assert!(
            measure_zero.contains("<per-minute>60</per-minute>"),
            "header tempo must stay in source measure number 0:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_restarted_measure_numbers_preserve_tempo_positions() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "    <measure number=\"1\">\n",
            "      <direction placement=\"above\"><direction-type><words>Allegro</words></direction-type></direction>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("| [I:croma-measure-number n=1]"),
            "restarted source measure numbers need a carrier on the later measure:\n{abc}"
        );
        assert_eq!(
            write_abc(&lower(&abc), AbcWriteOptions::default()),
            abc,
            "the measure-number carrier should be an ABC fixed point"
        );

        let roundtrip = export_musicxml(&abc).expect("measure-number carrier should export");
        assert_eq!(
            roundtrip.musicxml.matches("<measure number=\"1\">").count(),
            2,
            "both source measure numbers should survive:\n{}",
            roundtrip.musicxml
        );
        assert!(
            roundtrip
                .musicxml
                .split("<measure number=\"1\">")
                .nth(2)
                .is_some_and(|tail| tail.contains("<words>Allegro</words>")),
            "the Allegro direction must remain in the repeated measure number 1:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_nonnumeric_measure_numbers_survive_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"X1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <direction placement=\"above\"><direction-type><words>Scene</words></direction-type></direction>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "    <measure number=\"X2\">\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:croma-measure-number n=X1]")
                && abc.contains("[I:croma-measure-number n=X2]"),
            "nonnumeric source measure numbers need private ABC carriers:\n{abc}"
        );

        let roundtrip = export_musicxml(&abc).expect("measure-number carrier should export");
        let measure_x1 = measure_block(&roundtrip.musicxml, "X1");
        assert!(
            measure_x1.contains("<words>Scene</words>"),
            "Scene direction must remain in source measure X1:\n{}",
            roundtrip.musicxml
        );
        assert!(
            roundtrip.musicxml.contains("<measure number=\"X2\">"),
            "second nonnumeric source measure number should survive:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_pickup_measure_number_survives_before_leading_repeat() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"0\">\n",
            "      <attributes><divisions>4</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "      <direction placement=\"above\"><direction-type><words>Adagio</words></direction-type><sound tempo=\"92\"/></direction>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "    <measure number=\"1\">\n",
            "      <barline location=\"left\"><bar-style>heavy-light</bar-style><repeat direction=\"forward\"/></barline>\n",
            "      <note><pitch><step>E</step><octave>4</octave></pitch>",
            "<duration>16</duration><voice>1</voice><type>whole</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("|: [I:croma-measure-number n=1]"),
            "the next measure's label carrier must follow its leading repeat:\n{abc}"
        );

        let roundtrip = export_musicxml(&abc).expect("measure-number carrier should export");
        let pickup = measure_block(&roundtrip.musicxml, "0");
        assert!(
            pickup.contains("<words>Adagio</words>") && pickup.contains("<sound tempo=\"92.00\"/>"),
            "pickup tempo must remain in source measure number 0:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_part_initial_key_survives_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list>",
            "<score-part id=\"P1\"><part-name>One</part-name></score-part>",
            "<score-part id=\"P2\"><part-name>Two</part-name></score-part>",
            "</part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><key><fifths>2</fifths></key></attributes>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "  <part id=\"P2\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><key><fifths>0</fifths></key></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:croma-initial-key fifths=0]"),
            "part-local initial key needs a private ABC carrier:\n{abc}"
        );

        let roundtrip = export_musicxml(&abc).expect("part-local key ABC should export");
        let p2 = roundtrip
            .musicxml
            .split("<part id=\"P2\">")
            .nth(1)
            .expect("P2 should be present");
        assert!(
            p2.contains("<fifths>0</fifths>"),
            "P2 must keep its own initial C major key:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_part_initial_key_does_not_suppress_later_key_change() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list>",
            "<score-part id=\"P1\"><part-name>One</part-name></score-part>",
            "<score-part id=\"P2\"><part-name>Two</part-name></score-part>",
            "</part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><key><fifths>2</fifths></key></attributes>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "  <part id=\"P2\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions><key><fifths>0</fifths></key></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "    <measure number=\"2\">\n",
            "      <attributes><key><fifths>-1</fifths></key></attributes>\n",
            "      <note><pitch><step>F</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("[I:croma-initial-key fifths=0]") && abc.contains("[K:F]"),
            "part-local initial key and later key change must both survive in ABC:\n{abc}"
        );

        let roundtrip = export_musicxml(&abc).expect("part-local key ABC should export");
        let p2 = roundtrip
            .musicxml
            .split("<part id=\"P2\">")
            .nth(1)
            .expect("P2 should be present");
        assert!(
            p2.contains("<fifths>0</fifths>") && p2.contains("<fifths>-1</fifths>"),
            "P2 must keep its own initial key and later key change:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_midi_instrument_projects_to_midi_directives() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list>\n",
            "    <score-part id=\"P1\">\n",
            "      <part-name>T</part-name>\n",
            "      <score-instrument id=\"P1-I1\"><instrument-name>Piano</instrument-name></score-instrument>\n",
            "      <midi-instrument id=\"P1-I1\">\n",
            "        <midi-channel>2</midi-channel>\n",
            "        <midi-program>41</midi-program>\n",
            "        <volume>78.7402</volume>\n",
            "        <pan>0</pan>\n",
            "      </midi-instrument>\n",
            "    </score-part>\n",
            "  </part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );
        let score = completed_from_xml(xml);
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("%%MIDI program 2 40\n"),
            "MusicXML midi-program 41 must project to 0-based ABC program 40 with channel 2; got:\n{abc}"
        );
        assert!(
            abc.contains("%%MIDI control 7 100\n"),
            "MusicXML volume 78.7402 must project to MIDI CC7 100; got:\n{abc}"
        );
        assert!(
            abc.contains("%%MIDI control 10 64\n"),
            "MusicXML pan 0 must project to centered MIDI CC10 64; got:\n{abc}"
        );
        assert!(
            abc.contains("V:P1 name=\"T\" nm=\"Piano\"\n"),
            "MusicXML part/instrument names must survive into ABC voice metadata; got:\n{abc}"
        );
    }

    #[test]
    fn completion_synthesizes_voice_barline_events_from_measure_structure() {
        // Before the pass, the reader leaves voice.events barline-free.
        let x1 = export("X:1\nL:1/4\nK:C\nC D E F | G A B c |\n");
        let raw = read_musicxml(&x1).value;
        assert!(
            event_barline_kinds(&raw).is_empty(),
            "the raw reader output must carry NO barline events (they live in Measure.barlines)"
        );
        // After the pass, the INTERNAL boundary `|` is materialised as a Barline
        // event. Both `|` are plain Regular so neither produced a `<barline>`
        // element; the final trailing `|` on the LAST measure is structurally
        // inert and unrecoverable, so only the internal boundary is synthesized
        // (forward lowering of this tune also yields exactly one event per
        // internal boundary in the round-tripped projection).
        let mut completed = raw;
        complete_score_for_abc(&mut completed);
        assert_eq!(
            event_barline_kinds(&completed),
            vec![BarlineKind::Regular],
            "the completion pass must synthesize the internal measure boundary `|`"
        );
        // The structural gate is measure count, which must be preserved exactly.
        let projected = write_abc(&completed, AbcWriteOptions::default());
        assert_eq!(
            measure_count(&lower(&projected)),
            2,
            "both measures must survive XML -> ABC -> Score; abc {projected:?}"
        );
    }

    #[test]
    fn completed_abc_reparses_to_same_measure_count_and_barline_kinds() {
        // A multi-measure tune with a leading repeat, a backward repeat, and a
        // final barline. The completed ABC must carry the right glyphs and
        // re-parse to the same measure count + barline kinds.
        let abc = "X:1\nL:1/4\nK:C\n|: C D E F | G A B c :| c B A G |]\n";
        let completed = completed_from_abc(abc);
        let projected = write_abc(&completed, AbcWriteOptions::default());

        // Glyph spot-check: every special barline survives into the ABC text.
        assert!(projected.contains("|:"), "leading repeat: {projected:?}");
        assert!(projected.contains(":|"), "backward repeat: {projected:?}");
        assert!(projected.contains("|]"), "final barline: {projected:?}");

        // Structural: re-parsing the projected ABC yields the same measure count
        // and the same barline-kind sequence as lowering the original ABC.
        let reference = lower(abc);
        let reparsed = lower(&projected);
        assert_eq!(
            measure_count(&reparsed),
            measure_count(&reference),
            "measure count must survive XML -> ABC -> Score; abc {projected:?}"
        );
        assert_eq!(
            event_barline_kinds(&reparsed),
            event_barline_kinds(&reference),
            "barline kinds must survive XML -> ABC -> Score; abc {projected:?}"
        );
    }

    #[test]
    fn completion_sets_canonical_major_key_display_from_fifths() {
        // fifths = -3 (E-flat major). The raw reader leaves display empty; the
        // pass must fill the canonical major spelling so `K:` is non-empty.
        let x1 = export("X:1\nL:1/4\nK:Eb\nE F G A | B c d e |\n");
        let raw = read_musicxml(&x1).value;
        assert_eq!(
            raw.metadata.key.as_ref().map(|k| k.display.as_str()),
            Some(""),
            "the raw reader leaves the key display empty"
        );
        let mut completed = raw;
        complete_score_for_abc(&mut completed);
        assert_eq!(
            completed.metadata.key.as_ref().map(|k| k.display.as_str()),
            Some("Eb"),
            "fifths -3 must spell as the canonical major key Eb"
        );
        // And the projected ABC carries that `K:Eb`.
        let projected = write_abc(&completed, AbcWriteOptions::default());
        assert!(
            projected.contains("\nK:Eb\n"),
            "completed ABC must emit K:Eb, got {projected:?}"
        );
    }

    #[test]
    fn non_c_key_pitch_sequence_survives_xml_to_abc_to_score() {
        // The empty-K: bug dropped the key fifths (-3 -> 0) and re-applied
        // accidentals wrongly. With the canonical display, the sounding pitch
        // sequence must survive ABC -> XML -> Score -> ABC -> Score.
        let abc = "X:1\nL:1/8\nK:Eb\nE F G A B c d e |\n";
        let reference = lower(abc);
        let completed = completed_from_abc(abc);
        // The reconstructed Score already carries the source sounding pitches.
        assert_eq!(
            pitch_sequence(&completed),
            pitch_sequence(&reference),
            "reconstruction must preserve the sounding pitch sequence in a non-C key"
        );
        // ...and the projected ABC re-parses to that same sequence.
        let projected = write_abc(&completed, AbcWriteOptions::default());
        let reparsed = lower(&projected);
        assert_eq!(
            pitch_sequence(&reparsed),
            pitch_sequence(&reference),
            "completed ABC must reparse to the same pitches in a non-C key; abc {projected:?}"
        );
    }

    #[test]
    fn mid_tune_key_change_display_is_filled_canonically() {
        // A mid-tune `[K:F]` (fifths 1) is reconstructed as a KeyChange event
        // with empty display, which write_abc would emit as `[K:]` -> fifths 0,
        // dropping the change. The pass must fill the canonical major spelling so
        // the inline change re-parses to the same fifths.
        let abc = "X:1\nL:1/4\nK:C\nC D E F | [K:F] G A B c |\n";
        let mut score = read_musicxml(&export(abc)).value;
        complete_score_for_abc(&mut score);
        let change_displays: Vec<String> = score.parts[0].voices[0]
            .events
            .iter()
            .filter_map(|e| match &e.kind {
                TimedEventKind::KeyChange(k) => Some(k.display.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(
            change_displays,
            vec!["F".to_string()],
            "mid-tune KeyChange display must be the canonical major spelling for fifths 1"
        );
        let projected = write_abc(&score, AbcWriteOptions::default());
        assert!(
            projected.contains("[K:F]"),
            "completed ABC must carry the inline [K:F], got {projected:?}"
        );
        // Structural: the inline change survives a re-parse (same fifths sequence).
        let reference = lower(abc);
        let reparsed = lower(&projected);
        let key_fifths = |s: &Score| -> Vec<i8> {
            let mut v = Vec::new();
            for p in &s.parts {
                for voice in &p.voices {
                    for e in &voice.events {
                        if let TimedEventKind::KeyChange(k) = &e.kind {
                            v.push(k.fifths);
                        }
                    }
                }
            }
            v
        };
        assert_eq!(
            key_fifths(&reparsed),
            key_fifths(&reference),
            "mid-tune key fifths must survive XML -> ABC -> Score; abc {projected:?}"
        );
    }

    #[test]
    fn first_and_second_endings_round_trip_through_completed_abc() {
        // A volta bracket: `[1 ... :| [2 ... |]`. The completion pass must
        // synthesize the RepeatEnding events so write_abc emits the brackets.
        let abc = "X:1\nL:1/4\n K:C\n|: C D E F |1 G A B c :|2 c B A G |]\n";
        let completed = completed_from_abc(abc);
        let projected = write_abc(&completed, AbcWriteOptions::default());
        assert!(projected.contains("[1"), "first ending: {projected:?}");
        assert!(projected.contains("[2"), "second ending: {projected:?}");
        // Structural: same measure count + barline kinds after a re-parse.
        let reference = lower(abc);
        let reparsed = lower(&projected);
        assert_eq!(measure_count(&reparsed), measure_count(&reference));
        assert_eq!(
            event_barline_kinds(&reparsed),
            event_barline_kinds(&reference),
            "ending barline kinds must survive; abc {projected:?}"
        );
    }

    #[test]
    fn format_xml_inverse_is_byte_identical_with_and_without_completion() {
        // The load-bearing isolation invariant: the completion pass must NOT
        // perturb the `write_musicxml` view. For several fixtures, the XML
        // re-emission must be byte-identical whether or not the pass ran.
        for abc in [
            "X:1\nL:1/4\nK:C\nC D E F | G A B c |\n",
            "X:1\nL:1/4\nK:Eb\n|: E F G A :| B c d e |]\n",
            "X:1\nL:1/4\nK:D\n|: A B c d |1 e f g a :|2 a g f e |]\n",
        ] {
            let x1 = export(abc);
            let mut score = read_musicxml(&x1).value;
            let xml_before = write_musicxml(&score).musicxml;
            complete_score_for_abc(&mut score);
            let xml_after = write_musicxml(&score).musicxml;
            assert_eq!(
                xml_before, xml_after,
                "completion must not change the write_musicxml inverse for {abc:?}"
            );
            // And both equal the original forward XML (the pure inverse holds).
            assert_eq!(
                xml_after, x1,
                "the XML inverse must stay byte-identical to the forward XML for {abc:?}"
            );
        }
    }

    #[test]
    fn key_display_is_left_untouched_when_metadata_key_is_none() {
        // A reconstructed Score with no key must keep `metadata.key == None`
        // (write_abc defaults to K:C); the pass must not synthesize one.
        let mut score = read_musicxml(&export("X:1\nL:1/4\nK:C\nC D E F |\n")).value;
        score.metadata.key = None;
        complete_score_for_abc(&mut score);
        assert!(
            score.metadata.key.is_none(),
            "the pass must not synthesize a key when none is present"
        );
        let projected = write_abc(&score, AbcWriteOptions::default());
        assert!(
            projected.contains("\nK:C\n"),
            "write_abc must default a key-less Score to K:C, got {projected:?}"
        );
    }

    #[test]
    fn tuplets_in_separate_measures_do_not_merge_in_abc_projection() {
        // R1c regression. The reader assigns tuplet pair_ids FRESH per measure
        // (correct for write_musicxml, which re-derives the MusicXML number from
        // an active-set discipline). But write_abc's tuplet_layout groups tuplet
        // attachments by pair_id GLOBALLY across the whole voice.events, spanning
        // min..=max. With a triplet in EACH of two measures, both reuse pair_id 0,
        // so the un-renumbered projection merged them into ONE group spanning the
        // whole line: an absurd `(3:2:6...`-style span and compounded durations.
        // The completion pass must renumber pair_ids globally-unique per voice so
        // each triplet stays its own `(3:2:3` group.
        let abc = "X:1\nT:TwoMeasureTrips\nM:4/4\nL:1/8\nK:C\n(3CDE A2 z2 | (3FGA c2 z2 |\n";

        // Sanity: the forward XML emits two triplets, both re-numbered `number=1`.
        let x1 = export(abc);
        assert_eq!(
            x1.matches("<tuplet type=\"start\"").count(),
            2,
            "precondition: two triplets, one per measure"
        );

        // The pure reader Score (the per-event sounding durations + pitches the
        // projection must reproduce).
        let direct = read_musicxml(&x1).value;

        let completed = completed_from_abc(abc);
        let projected = write_abc(&completed, AbcWriteOptions::default());

        // The marker must be the clean 3-note triplet form `(3:2:3`, never a
        // merged super-span like `(3:2:6` (or larger), and there must be exactly
        // two such markers โ€” one per measure.
        assert_eq!(
            projected.matches("(3:2:3").count(),
            2,
            "each triplet must project as its own (3:2:3 group; abc {projected:?}"
        );
        assert!(
            !projected.contains("(3:2:4")
                && !projected.contains("(3:2:5")
                && !projected.contains("(3:2:6"),
            "no merged super-span tuplet marker may appear; abc {projected:?}"
        );

        // Structural: XML -> ABC -> Score reproduces the same per-event sounding
        // durations AND pitch sequence as reading the XML directly. (A merged
        // tuplet group compounded the durations, so this is the load-bearing
        // assertion; the marker check above guards the surface symptom.)
        let reparsed = lower(&projected);
        assert_eq!(
            played_duration_sequence(&reparsed),
            played_duration_sequence(&direct),
            "sounding durations must survive XML -> ABC -> Score; abc {projected:?}"
        );
        assert_eq!(
            pitch_sequence(&reparsed),
            pitch_sequence(&direct),
            "pitch sequence must survive XML -> ABC -> Score; abc {projected:?}"
        );
    }

    #[test]
    fn foreign_wide_tuplet_survives_abc_projection_without_invalid_marker() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>480</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>48</duration><voice>1</voice><type>eighth</type>",
            "<time-modification><actual-notes>10</actual-notes><normal-notes>2</normal-notes></time-modification>",
            "<notations><tuplet type=\"start\" bracket=\"no\" show-number=\"none\"/></notations></note>\n",
            "      <note><pitch><step>D</step><octave>4</octave></pitch>",
            "<duration>48</duration><voice>1</voice><type>eighth</type>",
            "<time-modification><actual-notes>10</actual-notes><normal-notes>2</normal-notes></time-modification></note>\n",
            "      <note><pitch><step>E</step><octave>4</octave></pitch>",
            "<duration>48</duration><voice>1</voice><type>eighth</type>",
            "<time-modification><actual-notes>10</actual-notes><normal-notes>2</normal-notes></time-modification></note>\n",
            "      <note><pitch><step>F</step><octave>4</octave></pitch>",
            "<duration>48</duration><voice>1</voice><type>eighth</type>",
            "<time-modification><actual-notes>10</actual-notes><normal-notes>2</normal-notes></time-modification></note>\n",
            "      <note><pitch><step>G</step><octave>4</octave></pitch>",
            "<duration>48</duration><voice>1</voice><type>eighth</type>",
            "<time-modification><actual-notes>10</actual-notes><normal-notes>2</normal-notes></time-modification></note>\n",
            "      <note><pitch><step>A</step><octave>4</octave></pitch>",
            "<duration>48</duration><voice>1</voice><type>eighth</type>",
            "<time-modification><actual-notes>10</actual-notes><normal-notes>2</normal-notes></time-modification></note>\n",
            "      <note><pitch><step>B</step><octave>4</octave></pitch>",
            "<duration>48</duration><voice>1</voice><type>eighth</type>",
            "<time-modification><actual-notes>10</actual-notes><normal-notes>2</normal-notes></time-modification></note>\n",
            "      <note><pitch><step>C</step><octave>5</octave></pitch>",
            "<duration>48</duration><voice>1</voice><type>eighth</type>",
            "<time-modification><actual-notes>10</actual-notes><normal-notes>2</normal-notes></time-modification></note>\n",
            "      <note><pitch><step>D</step><octave>5</octave></pitch>",
            "<duration>48</duration><voice>1</voice><type>eighth</type>",
            "<time-modification><actual-notes>10</actual-notes><normal-notes>2</normal-notes></time-modification></note>\n",
            "      <note><pitch><step>E</step><octave>5</octave></pitch>",
            "<duration>48</duration><voice>1</voice><type>eighth</type>",
            "<time-modification><actual-notes>10</actual-notes><normal-notes>2</normal-notes></time-modification>",
            "<notations><tuplet type=\"stop\" number=\"1\"/></notations></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let direct = read_musicxml(xml).value;
        let completed = completed_from_xml(xml);
        let projected = write_abc(&completed, AbcWriteOptions::default());
        assert!(
            !projected.contains("(10:2"),
            "ABC projection must not emit parser-invalid wide tuplets:\n{projected}"
        );
        assert!(
            projected.contains("[I:croma-musicxml-tuplet "),
            "wide MusicXML tuplets need a private carrier:\n{projected}"
        );

        let reparsed = lower(&projected);
        assert_eq!(
            played_duration_sequence(&reparsed),
            played_duration_sequence(&direct),
            "sounding durations must survive XML -> ABC -> Score; abc {projected:?}"
        );

        let roundtrip = export_musicxml(&projected).expect("wide-tuplet carrier ABC should export");
        assert!(
            roundtrip
                .musicxml
                .contains("<actual-notes>10</actual-notes>")
                && roundtrip
                    .musicxml
                    .contains("<normal-notes>2</normal-notes>")
                && roundtrip
                    .musicxml
                    .contains("<tuplet type=\"start\" bracket=\"no\"/>")
                && roundtrip
                    .musicxml
                    .contains("<tuplet type=\"stop\" number=\"1\"/>"),
            "roundtrip must keep the 10:2 MusicXML tuplet:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn foreign_wide_tuplet_on_chord_survives_abc_projection() {
        // Same 10:2 group as the sibling test, but the tuplet's start and stop
        // roles land on CHORDS, not single notes. The carrier must reach the
        // chord head so the `<time-modification>` and `<tuplet>` bracket survive
        // the XML -> ABC -> XML projection.
        let tm = "<time-modification><actual-notes>10</actual-notes><normal-notes>2</normal-notes></time-modification>";
        let mut body = String::new();
        body.push_str(&format!(
            "<note><pitch><step>C</step><octave>4</octave></pitch><duration>48</duration><voice>1</voice><type>eighth</type>{tm}<notations><tuplet type=\"start\" bracket=\"no\" show-number=\"none\"/></notations></note>"
        ));
        body.push_str(&format!(
            "<note><chord/><pitch><step>E</step><octave>4</octave></pitch><duration>48</duration><voice>1</voice><type>eighth</type>{tm}</note>"
        ));
        for (step, octave) in [
            ("D", "4"),
            ("E", "4"),
            ("F", "4"),
            ("G", "4"),
            ("A", "4"),
            ("B", "4"),
            ("C", "5"),
            ("D", "5"),
        ] {
            body.push_str(&format!(
                "<note><pitch><step>{step}</step><octave>{octave}</octave></pitch><duration>48</duration><voice>1</voice><type>eighth</type>{tm}</note>"
            ));
        }
        body.push_str(&format!(
            "<note><pitch><step>E</step><octave>5</octave></pitch><duration>48</duration><voice>1</voice><type>eighth</type>{tm}<notations><tuplet type=\"stop\" number=\"1\"/></notations></note>"
        ));
        body.push_str(&format!(
            "<note><chord/><pitch><step>G</step><octave>5</octave></pitch><duration>48</duration><voice>1</voice><type>eighth</type>{tm}</note>"
        ));
        let xml = format!(
            "<?xml version=\"1.0\"?>\n<score-partwise>\n  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n  <part id=\"P1\">\n    <measure number=\"1\">\n      <attributes><divisions>480</divisions><time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n      {body}\n    </measure>\n  </part>\n</score-partwise>\n"
        );

        let direct = read_musicxml(&xml).value;
        let completed = completed_from_xml(&xml);
        let projected = write_abc(&completed, AbcWriteOptions::default());
        assert!(
            !projected.contains("(10:2"),
            "ABC projection must not emit parser-invalid wide tuplets:\n{projected}"
        );
        assert!(
            projected.contains("[I:croma-musicxml-tuplet "),
            "wide MusicXML tuplets need a private carrier:\n{projected}"
        );

        let reparsed = lower(&projected);
        assert_eq!(
            played_duration_sequence(&reparsed),
            played_duration_sequence(&direct),
            "sounding durations must survive XML -> ABC -> Score; abc {projected:?}"
        );

        let roundtrip = export_musicxml(&projected).expect("wide-tuplet carrier ABC should export");
        assert!(
            roundtrip
                .musicxml
                .contains("<actual-notes>10</actual-notes>")
                && roundtrip
                    .musicxml
                    .contains("<normal-notes>2</normal-notes>")
                && roundtrip
                    .musicxml
                    .contains("<tuplet type=\"start\" bracket=\"no\"/>")
                && roundtrip
                    .musicxml
                    .contains("<tuplet type=\"stop\" number=\"1\"/>"),
            "roundtrip must keep the 10:2 MusicXML tuplet when it lands on a chord:\n{}",
            roundtrip.musicxml
        );
    }

    // --- P1: empty / all-spacer trailing measure preservation ---------------

    /// The (slur-start, slur-stop) pair_id count across a lowered Score, used to
    /// assert grace-anchored slurs survive the projection. Counts both event-level
    /// slurs and grace-group/grace-event slurs so a slur moving between channels is
    /// still seen.
    fn total_slur_starts(score: &Score) -> usize {
        use crate::model::SlurRole;
        let mut starts = 0;
        for part in &score.parts {
            for voice in &part.voices {
                for event in &voice.events {
                    starts += event
                        .attachments
                        .slurs
                        .iter()
                        .filter(|s| s.role == SlurRole::Start)
                        .count();
                    for group in event
                        .attachments
                        .grace_groups
                        .iter()
                        .chain(&event.attachments.after_grace_groups)
                    {
                        starts += group
                            .slurs
                            .iter()
                            .filter(|s| s.role == SlurRole::Start)
                            .count();
                        for grace in &group.events {
                            starts += grace
                                .slurs
                                .iter()
                                .filter(|s| s.role == SlurRole::Start)
                                .count();
                        }
                    }
                }
            }
        }
        starts
    }

    #[test]
    fn foreign_grace_note_decorations_survive_abc_projection() {
        let xml = concat!(
            "<?xml version=\"1.0\"?>\n",
            "<score-partwise>\n",
            "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
            "  <part id=\"P1\">\n",
            "    <measure number=\"1\">\n",
            "      <attributes><divisions>4</divisions></attributes>\n",
            "      <note><grace/><pitch><step>B</step><octave>4</octave></pitch>",
            "<voice>1</voice><type>eighth</type>",
            "<notations><fermata type=\"upright\"/><articulations><staccato/></articulations></notations>",
            "</note>\n",
            "      <note><pitch><step>C</step><octave>4</octave></pitch>",
            "<duration>4</duration><voice>1</voice><type>quarter</type></note>\n",
            "    </measure>\n",
            "  </part>\n",
            "</score-partwise>\n",
        );

        let score = completed_from_xml(xml);
        let names = grace_note_decoration_names(
            &score.parts[0].voices[0].events[0].attachments.grace_groups[0],
            0,
        );
        assert_eq!(
            names,
            vec!["fermata", "staccato"],
            "foreign grace-note notations reconstruct onto the grace note"
        );
        let abc = write_abc(&score, AbcWriteOptions::default());
        assert!(
            abc.contains("{!fermata!!staccato!B}C2"),
            "foreign grace-note decorations must remain inside the grace braces:\n{abc}"
        );

        let roundtrip =
            export_musicxml(&abc).expect("decorated grace-note ABC projection should export");
        assert!(
            roundtrip.musicxml.contains("<fermata type=\"upright\"/>")
                && roundtrip.musicxml.contains("<staccato/>"),
            "MusicXML round trip must preserve grace-note notations:\n{}",
            roundtrip.musicxml
        );
    }

    #[test]
    fn empty_trailing_all_spacer_measure_is_preserved_in_abc_projection() {
        // A tune whose LAST measure is entirely spacers (`y8 ...`) emits an empty
        // `<measure></measure>` in MusicXML (spacers have no XML element). The raw
        // reader keeps an empty `Measure` for it, but the completion pass dropped
        // it (no content, no barline, last measure => no synthesized `|`), so the
        // re-parsed ABC lost the boundary and the measure count fell by one.
        let abc = "X:1\nL:1/4\nK:C\nC D E F | y4 y4 y4 y4\n";
        let reference = lower(abc);
        assert_eq!(
            measure_count(&reference),
            2,
            "precondition: the source has two measures (content + all-spacer)"
        );
        let completed = completed_from_abc(abc);
        let projected = write_abc(&completed, AbcWriteOptions::default());
        let reparsed = lower(&projected);
        assert_eq!(
            measure_count(&reparsed),
            measure_count(&reference),
            "the trailing all-spacer measure must survive XML -> ABC -> Score; abc {projected:?}"
        );
    }

    #[test]
    fn empty_trailing_measure_preservation_keeps_xml_inverse_byte_identical() {
        // P1 isolation: synthesizing the trailing spacer in the ABC projection
        // must not perturb the write_musicxml pure inverse.
        let abc = "X:1\nL:1/4\nK:C\nC D E F | y4 y4 y4 y4\n";
        let x1 = export(abc);
        let mut score = read_musicxml(&x1).value;
        let xml_before = write_musicxml(&score).musicxml;
        complete_score_for_abc(&mut score);
        let xml_after = write_musicxml(&score).musicxml;
        assert_eq!(
            xml_before, xml_after,
            "completion must not change the write_musicxml inverse"
        );
        assert_eq!(xml_after, x1, "the XML inverse must stay byte-identical");
    }

    #[test]
    fn empty_interior_measure_is_preserved_in_abc_projection() {
        // P1 extension: an empty *interior* measure (`| ||` โ€” a measure with no
        // content whose boundaries to both neighbours are synthesized plain `|`)
        // emits an empty `<measure></measure>` in MusicXML. The original P1 guard
        // (`out.len() == start_len`) did NOT fire for it, because the boundary to
        // the next measure adds a synthesized trailing `|`: the measure emitted a
        // lone `|`, so the projected ABC read `... | | ...` (an empty `| |` the
        // parser drops) and the measure count fell by one. The spacer must be
        // emitted whenever a content-empty measure has no opening barline/ending,
        // so the measure renders `y |` and survives.
        let abc = "X:1\nL:1/4\nK:C\nC D E F | || G A B c | d e f g |\n";
        let reference = lower(abc);
        assert_eq!(
            measure_count(&reference),
            4,
            "precondition: `| ||` yields an empty interior measure (4 total)"
        );
        let completed = completed_from_abc(abc);
        let projected = write_abc(&completed, AbcWriteOptions::default());
        let reparsed = lower(&projected);
        assert_eq!(
            measure_count(&reparsed),
            measure_count(&reference),
            "the empty interior measure must survive XML -> ABC -> Score; abc {projected:?}"
        );
        // The content notes must all survive, in order (no fact lost).
        assert_eq!(
            pitch_sequence(&reparsed),
            pitch_sequence(&reference),
            "every note must survive XML -> ABC -> Score; abc {projected:?}"
        );
    }

    #[test]
    fn empty_interior_measure_preservation_keeps_xml_inverse_byte_identical() {
        // P1 isolation: synthesizing the interior spacer in the ABC projection
        // must not perturb the write_musicxml pure inverse (a spacer emits no XML).
        let abc = "X:1\nL:1/4\nK:C\nC D E F | || G A B c | d e f g |\n";
        let x1 = export(abc);
        let mut score = read_musicxml(&x1).value;
        let xml_before = write_musicxml(&score).musicxml;
        complete_score_for_abc(&mut score);
        let xml_after = write_musicxml(&score).musicxml;
        assert_eq!(
            xml_before, xml_after,
            "completion must not change the write_musicxml inverse"
        );
        assert_eq!(xml_after, x1, "the XML inverse must stay byte-identical");
    }

    /// A three-measure part whose MIDDLE `<measure>` is directive-only: it holds
    /// just an `<attributes><key>` restatement and no notes โ€” exactly the empty
    /// key-restatement slot croma's forward writer parks at a `||` section
    /// boundary (observed on corpus `tune_012588`). The reader keeps a `Measure`
    /// for it, but it anchors no `write_abc` segment, so without the P1 spacer the
    /// projected `| [K:G] |` folds into a neighbour and the measure count drops.
    const DIRECTIVE_ONLY_MIDDLE_XML: &str = concat!(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
        "<score-partwise version=\"3.1\">\n",
        "  <part-list><score-part id=\"P1\"><part-name>P</part-name></score-part></part-list>\n",
        "  <part id=\"P1\">\n",
        "    <measure number=\"1\">\n",
        "      <attributes><divisions>1</divisions><key><fifths>0</fifths></key>\n",
        "        <time><beats>4</beats><beat-type>4</beat-type></time></attributes>\n",
        "      <note><pitch><step>C</step><octave>4</octave></pitch><duration>4</duration><voice>1</voice><type>whole</type></note>\n",
        "    </measure>\n",
        "    <measure number=\"2\">\n",
        "      <attributes><key><fifths>1</fifths></key></attributes>\n",
        "    </measure>\n",
        "    <measure number=\"3\">\n",
        "      <note><pitch><step>G</step><octave>4</octave></pitch><duration>4</duration><voice>1</voice><type>whole</type></note>\n",
        "    </measure>\n",
        "  </part>\n",
        "</score-partwise>\n",
    );

    #[test]
    fn directive_only_measure_is_preserved_in_abc_projection() {
        // P1 extension: a measure whose ONLY content is a mid-tune key change
        // anchors no segment, so `write_abc` emits `| [K:G] |`, which the parser
        // folds into the adjacent measure โ€” the measure count falls by one. The
        // spacer must fire for it too, so the measure renders `[K:G] y |`.
        let raw = read_musicxml(DIRECTIVE_ONLY_MIDDLE_XML).value;
        assert_eq!(
            measure_count(&raw),
            3,
            "precondition: the reader keeps a Measure for the directive-only middle measure"
        );
        let mut completed = raw;
        complete_score_for_abc(&mut completed);
        let projected = write_abc(&completed, AbcWriteOptions::default());
        let reparsed = lower(&projected);
        assert_eq!(
            measure_count(&reparsed),
            3,
            "the directive-only measure must survive XML -> ABC -> Score; abc {projected:?}"
        );
        assert_eq!(
            pitch_sequence(&reparsed),
            vec![('C', 0, 4), ('G', 0, 4)],
            "both notes must survive, none lost to the folded measure; abc {projected:?}"
        );
    }

    #[test]
    fn directive_only_measure_preservation_keeps_xml_inverse_byte_identical() {
        // P1 isolation: the directive-only spacer must not perturb the
        // write_musicxml pure inverse (a spacer emits no XML element).
        let mut score = read_musicxml(DIRECTIVE_ONLY_MIDDLE_XML).value;
        let xml_before = write_musicxml(&score).musicxml;
        complete_score_for_abc(&mut score);
        let xml_after = write_musicxml(&score).musicxml;
        assert_eq!(
            xml_before, xml_after,
            "completion must not change the write_musicxml inverse (the spacer emits no XML)"
        );
    }

    // --- P2: grace-anchored slur start preservation -------------------------

    #[test]
    fn grace_anchored_slur_start_survives_abc_projection() {
        // `({Bc}B2)`: a slur opens on the FIRST grace note and closes on the main
        // note. Forward lowering records the start in `group.slurs` (so write_abc
        // emits `(` BEFORE the `{`). The reader folds grace slurs into the per-
        // grace-event `slurs`, which write_abc emits INSIDE the braces (`{(Bc}`),
        // dropping the slur on re-parse. The completion pass must hoist the
        // group-anchored start back to `group.slurs`.
        let abc = "X:1\nL:1/8\nK:C\n({Bc}B2) A2 |\n";
        let reference = lower(abc);
        assert_eq!(
            total_slur_starts(&reference),
            1,
            "precondition: the source has exactly one slur start"
        );
        let completed = completed_from_abc(abc);
        let projected = write_abc(&completed, AbcWriteOptions::default());
        assert!(
            projected.contains("({"),
            "grace-anchored slur must open before the grace group `({{`, got {projected:?}"
        );
        let reparsed = lower(&projected);
        assert_eq!(
            total_slur_starts(&reparsed),
            total_slur_starts(&reference),
            "the grace-anchored slur start must survive XML -> ABC -> Score; abc {projected:?}"
        );
    }

    #[test]
    fn internal_grace_slur_survives_abc_projection() {
        // `{(ef)}g2`: a slur that opens AND closes inside the grace group. The
        // reader's flat READER_SPAN made write_abc emit the closing `)` AFTER the
        // brace (`{(ef})`), which re-parses to zero slurs. The completion pass must
        // place the internal stop so it renders inside the braces.
        let abc = "X:1\nL:1/8\nK:C\n{(ef)}g2 |\n";
        let reference = lower(abc);
        assert_eq!(
            total_slur_starts(&reference),
            1,
            "precondition: one internal grace slur"
        );
        let completed = completed_from_abc(abc);
        let projected = write_abc(&completed, AbcWriteOptions::default());
        let reparsed = lower(&projected);
        assert_eq!(
            total_slur_starts(&reparsed),
            total_slur_starts(&reference),
            "the internal grace slur must survive XML -> ABC -> Score; abc {projected:?}"
        );
    }

    #[test]
    fn after_grace_trailing_slur_survives_abc_projection() {
        // `(f4{ef})`: a slur opens on the MAIN note `f4`, then an AFTER-grace group
        // `{ef}`, with the slur closing on the after-grace note โ€” rendered as a
        // trailing `)` AFTER the `}`. The grace-slur re-projection must NOT pull
        // this stop inside the braces (an earlier over-broad span tweak did, which
        // reordered the slur and dropped a measure on re-parse).
        let abc = "X:1\nL:1/8\nK:C\n(f4{ef}) g2 |\n";
        let reference = lower(abc);
        assert_eq!(
            total_slur_starts(&reference),
            1,
            "precondition: one slur start on the main note"
        );
        let completed = completed_from_abc(abc);
        let projected = write_abc(&completed, AbcWriteOptions::default());
        let reparsed = lower(&projected);
        assert_eq!(
            total_slur_starts(&reparsed),
            total_slur_starts(&reference),
            "the after-grace trailing slur must survive XML -> ABC -> Score; abc {projected:?}"
        );
        // The played-duration / pitch sequence must also survive (the regression
        // dropped a measure, so this guards the structural shape).
        assert_eq!(
            pitch_sequence(&reparsed),
            pitch_sequence(&reference),
            "after-grace slur pitch sequence must survive; abc {projected:?}"
        );
    }

    #[test]
    fn grace_slur_preservation_keeps_xml_inverse_byte_identical() {
        // P2 isolation: the grace-slur hoist must not perturb the write_musicxml
        // pure inverse.
        for abc in [
            "X:1\nL:1/8\nK:C\n({Bc}B2) A2 |\n",
            "X:1\nL:1/8\nK:C\n{(ef)}g2 |\n",
            "X:1\nL:1/8\nK:C\n(f4{ef}) g2 |\n",
        ] {
            let x1 = export(abc);
            let mut score = read_musicxml(&x1).value;
            let xml_before = write_musicxml(&score).musicxml;
            complete_score_for_abc(&mut score);
            let xml_after = write_musicxml(&score).musicxml;
            assert_eq!(
                xml_before, xml_after,
                "completion must not change the write_musicxml inverse for {abc:?}"
            );
            assert_eq!(
                xml_after, x1,
                "the XML inverse must stay byte-identical for {abc:?}"
            );
        }
    }

    // --- P3: explicit key-signature accidentals in the ABC display ----------

    /// The flat (step, alter) explicit-accidental list of the header key.
    fn header_key_explicit(score: &Score) -> Vec<(char, i8)> {
        score
            .metadata
            .key
            .as_ref()
            .map(|key| {
                key.explicit_accidentals
                    .iter()
                    .map(|acc| (acc.step, acc.accidental.alter()))
                    .collect()
            })
            .unwrap_or_default()
    }

    #[test]
    fn explicit_key_accidentals_survive_abc_projection() {
        // `K: C _B`: C major (fifths 0) PLUS an explicit `_B` accidental in the key
        // signature. The reader reconstructs `fifths` + `explicit_accidentals`, but
        // the completion pass spelled the display as the bare canonical major
        // (`K:C`), dropping the `_B`. The pass must build a display that re-parses
        // to the same explicit accidentals.
        let abc = "X:1\nL:1/8\nK:C _B\nB c d e |\n";
        let reference = lower(abc);
        assert_eq!(
            header_key_explicit(&reference),
            vec![('B', -1)],
            "precondition: the source key carries one explicit flat on B"
        );
        let mut completed = read_musicxml(&export(abc)).value;
        complete_score_for_abc(&mut completed);
        assert_eq!(
            header_key_explicit(&completed),
            header_key_explicit(&reference),
            "reconstruction must carry the explicit key accidental"
        );
        let projected = write_abc(&completed, AbcWriteOptions::default());
        let reparsed = lower(&projected);
        assert_eq!(
            header_key_explicit(&reparsed),
            header_key_explicit(&reference),
            "explicit key accidentals must survive XML -> ABC -> Score; abc {projected:?}"
        );
        // The sounding pitches depend on the key accidental (B is flattened), so
        // they must survive too.
        assert_eq!(
            pitch_sequence(&reparsed),
            pitch_sequence(&reference),
            "explicit-key sounding pitches must survive; abc {projected:?}"
        );
    }

    #[test]
    fn explicit_exp_key_accidentals_survive_abc_projection() {
        // `[K:D exp _B^g]`: the `exp` form forces fifths 0 and defines the
        // signature purely by explicit accidentals. Both header and mid-tune forms
        // must round-trip their explicit accidentals.
        let abc = "X:1\nL:1/8\nK:D exp _B ^g\nB c d e |\n";
        let reference = lower(abc);
        assert_eq!(
            header_key_explicit(&reference),
            vec![('B', -1), ('G', 1)],
            "precondition: exp key carries _B and ^g"
        );
        let mut completed = read_musicxml(&export(abc)).value;
        complete_score_for_abc(&mut completed);
        let projected = write_abc(&completed, AbcWriteOptions::default());
        let reparsed = lower(&projected);
        assert_eq!(
            header_key_explicit(&reparsed),
            header_key_explicit(&reference),
            "exp-key explicit accidentals must survive; abc {projected:?}"
        );
    }

    #[test]
    fn mid_tune_explicit_key_accidentals_survive_abc_projection() {
        // A mid-tune `[K:=e]`: an explicit natural cancellation on the key. The
        // KeyChange display must carry the explicit accidental, not just the
        // canonical major spelling.
        let abc = "X:1\nL:1/8\nK:Bb\nB c d e | [K:=e] e f g a |\n";
        let reference = lower(abc);
        let mid_tune_explicit = |s: &Score| -> Vec<Vec<(char, i8)>> {
            let mut out = Vec::new();
            for p in &s.parts {
                for v in &p.voices {
                    for e in &v.events {
                        if let TimedEventKind::KeyChange(k) = &e.kind {
                            out.push(
                                k.explicit_accidentals
                                    .iter()
                                    .map(|a| (a.step, a.accidental.alter()))
                                    .collect(),
                            );
                        }
                    }
                }
            }
            out
        };
        assert_eq!(
            mid_tune_explicit(&reference),
            vec![vec![('E', 0)]],
            "precondition: mid-tune [K:=e] carries one explicit natural on E"
        );
        let mut completed = read_musicxml(&export(abc)).value;
        complete_score_for_abc(&mut completed);
        let projected = write_abc(&completed, AbcWriteOptions::default());
        let reparsed = lower(&projected);
        assert_eq!(
            mid_tune_explicit(&reparsed),
            mid_tune_explicit(&reference),
            "mid-tune explicit key accidentals must survive; abc {projected:?}"
        );
    }

    #[test]
    fn explicit_key_preservation_keeps_xml_inverse_byte_identical() {
        // P3 isolation: building an explicit-accidental display must not perturb
        // the write_musicxml pure inverse.
        for abc in [
            "X:1\nL:1/8\nK:C _B\nB c d e |\n",
            "X:1\nL:1/8\nK:D exp _B ^g\nB c d e |\n",
            "X:1\nL:1/8\nK:Bb\nB c d e | [K:=e] e f g a |\n",
        ] {
            let x1 = export(abc);
            let mut score = read_musicxml(&x1).value;
            let xml_before = write_musicxml(&score).musicxml;
            complete_score_for_abc(&mut score);
            let xml_after = write_musicxml(&score).musicxml;
            assert_eq!(
                xml_before, xml_after,
                "completion must not change the write_musicxml inverse for {abc:?}"
            );
            assert_eq!(
                xml_after, x1,
                "the XML inverse must stay byte-identical for {abc:?}"
            );
        }
    }
}

// --- R1: ABC -> XML -> Score -> ABC re-emission measurement ------------------

/// Totality arm for the ABC re-emission loop, run over the whole corpus. For
/// each corpus `.abc` that lowers cleanly, `s1 = lower(parse(abc))`, then we
/// drive `write_abc(read_musicxml(write_musicxml(&s1).xml).value)` against
/// `write_abc(&s1)` and count byte-identical full-document matches.
///
/// **This arm asserts TOTALITY ONLY (0 panics over ~10k files); the reported
/// byte-identity count is expected to be near-zero and is NOT a gate.** Full
/// ABC-*document* byte equality is the wrong bar here: `write_abc` emits
/// ABC-only state โ€” the `X:` reference number, `W:` post-tune lyrics, `V:` ids,
/// an empty display `K:` โ€” that the lossy MusicXML round-trip legitimately
/// drops, so the documents differ by construction even when every structural
/// musical fact is preserved. The byte count therefore measures nothing useful
/// and the test makes no hard count assertion on it; it exists to prove the
/// reader is *total* over the corpus (it never panics). The **real** R1 metric
/// โ€” a normalized STRUCTURAL projection that ignores this ABC-only state โ€” lives
/// in croma-test's `tools/prove_reader_abc_roundtrip.py` (the structural sibling
/// of croma-test's `tools/prove_abc_roundtrip.py`), which is where the round-trip
/// *correctness* proof belongs.
///
/// **Report-only**, mirroring the XML measurement's discipline: it prints
/// `N/total` plus a first-divergence note for a few non-matches and asserts no
/// hard count. Env-gated on `ABC_ROOT`; a no-op when unset, exactly like the
/// sibling measurement.
#[test]
fn corpus_abc_reemission_through_xml() {
    use crate::to_abc::{AbcWriteOptions, write_abc};

    let Ok(root) = std::env::var("ABC_ROOT") else {
        eprintln!("ABC_ROOT unset โ€” skipping R1 ABC-reemission-through-XML measurement");
        return;
    };
    let files = abc_files(&PathBuf::from(&root));
    if files.is_empty() {
        eprintln!("no .abc files under {root} โ€” skipping");
        return;
    }

    let mut total = 0usize;
    let mut lowered = 0usize;
    let mut idempotent = 0usize;
    let mut first_divergences: Vec<String> = Vec::new();

    for path in &files {
        let Ok(bytes) = fs::read(path) else { continue };
        let source = String::from_utf8_lossy(&bytes);
        total += 1;

        // Only files that export cleanly have an X1 to invert; that same set is
        // the one that lowers to a Score, so `export_musicxml` is the gate.
        let Ok(export) = export_musicxml(&source) else {
            continue;
        };
        lowered += 1;
        let x1 = export.musicxml;

        // s1 = lower(parse(abc)); its canonical ABC is the reference.
        let document = crate::parse_document(&source, crate::ParseOptions::default()).value;
        let Some(s1) = crate::lower_score(&document, crate::LowerOptions).value else {
            continue;
        };
        let expected_abc = write_abc(&s1, AbcWriteOptions::default());

        let reconstructed = read_musicxml(&x1).value;
        let round_trip_abc = write_abc(&reconstructed, AbcWriteOptions::default());

        if round_trip_abc == expected_abc {
            idempotent += 1;
        } else if first_divergences.len() < 5 {
            let line = first_diverging_line(&expected_abc, &round_trip_abc);
            let name = path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("<unknown>");
            first_divergences.push(format!("{name}: {line}"));
        }
    }

    eprintln!(
        "ABC re-emission through XML (ABC -> XML -> Score -> ABC): {idempotent}/{lowered} \
         files are BYTE-identical full documents ({total} total .abc). NOTE: this byte \
         count is EXPECTED to be near-zero and is not a metric โ€” write_abc emits \
         ABC-only state (X:/W:/V: ids, empty display K:) that the lossy XML round-trip \
         legitimately drops, so the documents differ by construction. This arm asserts \
         TOTALITY ONLY (0 panics). The real structural round-trip proof lives in \
         tools/prove_reader_abc_roundtrip.py."
    );
    if !first_divergences.is_empty() {
        eprintln!("first ABC divergences (up to 5):");
        for note in &first_divergences {
            eprintln!("  {note}");
        }
    }

    // No hard count on the byte-identity tally: full ABC-document byte equality
    // is expected to be near-zero (write_abc emits ABC-only state absent from
    // the lossy XML round-trip), so it is not a gate. The structural proof is
    // croma-test's tools/prove_reader_abc_roundtrip.py. Here we require only that
    // the loop is total over the corpus (no panic) and that at least one file was
    // measured.
    assert!(
        lowered > 0,
        "expected at least one corpus file to lower and export"
    );
}

// --- Phase-62 P1a: synthesize `%%score` from `<part-group>` ----------------
//
// Each test builds a minimal MusicXML document with a `<part-group>` and
// asserts that `read_musicxml` reconstructs the correct `%%score` directive
// in `metadata.directives`, and that `write_abc` emits the expected line.
//
// Self-loop-neutral: croma's own writer never emits `<part-group>`, so the
// synthesis fires only on foreign XML and the self-loop 9933/9935 is
// unchanged by construction.

/// Minimal part XML: one measure, one C quarter note, at `<divisions>4</divisions>`.
fn minimal_part(id: &str) -> String {
    format!(
        "  <part id=\"{id}\">\n    <measure number=\"1\">\
         \n      <attributes><divisions>4</divisions></attributes>\
         \n      <note><pitch><step>C</step><octave>4</octave></pitch>\
         \n        <duration>4</duration><voice>1</voice><type>quarter</type></note>\
         \n    </measure>\n  </part>\n"
    )
}

/// Minimal part XML with two voices sharing one MusicXML part.
fn minimal_two_voice_part(id: &str) -> String {
    format!(
        "  <part id=\"{id}\">\n    <measure number=\"1\">\
         \n      <attributes><divisions>4</divisions></attributes>\
         \n      <note><pitch><step>C</step><octave>4</octave></pitch>\
         \n        <duration>4</duration><voice>1</voice><type>quarter</type></note>\
         \n      <backup><duration>4</duration></backup>\
         \n      <note><pitch><step>E</step><octave>4</octave></pitch>\
         \n        <duration>4</duration><voice>2</voice><type>quarter</type></note>\
         \n    </measure>\n  </part>\n"
    )
}

#[test]
fn part_group_bracket_synthesizes_score_directive() {
    // A `<part-group type="start"><group-symbol>bracket</group-symbol>` wrapping
    // three single-staff parts โ†’ `%%score [P1 P2 P3]` in metadata.directives AND
    // in the write_abc output.
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <part-group number=\"1\" type=\"start\">\n",
        "      <group-symbol>bracket</group-symbol>\n",
        "    </part-group>\n",
        "    <score-part id=\"P1\"><part-name/></score-part>\n",
        "    <score-part id=\"P2\"><part-name/></score-part>\n",
        "    <score-part id=\"P3\"><part-name/></score-part>\n",
        "    <part-group number=\"1\" type=\"stop\"/>\n",
        "  </part-list>\n",
    );
    let parts = format!(
        "{}{}{}",
        minimal_part("P1"),
        minimal_part("P2"),
        minimal_part("P3")
    );
    let xml = format!("{xml}{parts}</score-partwise>\n");
    let score = read_musicxml(&xml).value;

    // The directive must be present.
    assert_eq!(
        score.metadata.directives.len(),
        1,
        "bracket group must synthesize exactly one %%score directive; \
         directives = {:?}",
        score
            .metadata
            .directives
            .iter()
            .map(|d| &d.value.text)
            .collect::<Vec<_>>()
    );
    let directive_text = &score.metadata.directives[0].value.text;
    assert_eq!(
        directive_text, "[P1 P2 P3]",
        "bracket group must produce `[P1 P2 P3]`"
    );

    // write_abc must emit the %%score line.
    use crate::to_abc::{AbcWriteOptions, write_abc};
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("%%score [P1 P2 P3]\n"),
        "write_abc must emit `%%score [P1 P2 P3]` for the bracket group; got:\n{abc}"
    );
}

#[test]
fn part_group_with_multi_voice_part_uses_one_combined_score_directive() {
    // The bracket is a visual group; the parenthesized P1 voices are semantic
    // part ownership. Both must live in the same %%score directive.
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <part-group number=\"1\" type=\"start\">\n",
        "      <group-symbol>bracket</group-symbol>\n",
        "    </part-group>\n",
        "    <score-part id=\"P1\"><part-name/></score-part>\n",
        "    <score-part id=\"P2\"><part-name/></score-part>\n",
        "    <part-group number=\"1\" type=\"stop\"/>\n",
        "  </part-list>\n",
    );
    let parts = format!("{}{}", minimal_two_voice_part("P1"), minimal_part("P2"));
    let xml = format!("{xml}{parts}</score-partwise>\n");
    let score = read_musicxml(&xml).value;

    assert_eq!(
        score.metadata.directives.len(),
        1,
        "mixed visual and ownership grouping must synthesize one %%score directive"
    );
    let directive_text = &score.metadata.directives[0].value.text;
    assert_eq!(
        directive_text, "[(P1 P1#2) P2]",
        "bracket group must preserve P1 voice ownership inside the visual group"
    );

    use crate::to_abc::{AbcWriteOptions, write_abc};
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("%%score [(P1 P1#2) P2]\n"),
        "write_abc must emit the combined %%score directive; got:\n{abc}"
    );
    let roundtrip = export_musicxml(&abc).expect("combined score directive should export");
    assert_eq!(
        roundtrip.musicxml.matches("<score-part id=").count(),
        2,
        "ABC->MusicXML must keep P1 voices in one part and P2 in the other:\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn part_group_brace_synthesizes_score_directive() {
    // A `<part-group type="start"><group-symbol>brace</group-symbol>` wrapping
    // two parts โ†’ `%%score {P1 P2}` in metadata.directives and write_abc output.
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <part-group number=\"1\" type=\"start\">\n",
        "      <group-symbol>brace</group-symbol>\n",
        "    </part-group>\n",
        "    <score-part id=\"P1\"><part-name/></score-part>\n",
        "    <score-part id=\"P2\"><part-name/></score-part>\n",
        "    <part-group number=\"1\" type=\"stop\"/>\n",
        "  </part-list>\n",
    );
    let parts = format!("{}{}", minimal_part("P1"), minimal_part("P2"));
    let xml = format!("{xml}{parts}</score-partwise>\n");
    let score = read_musicxml(&xml).value;

    assert_eq!(
        score.metadata.directives.len(),
        1,
        "brace group must synthesize exactly one %%score directive"
    );
    let directive_text = &score.metadata.directives[0].value.text;
    assert_eq!(
        directive_text, "{P1 P2}",
        "brace group must produce `{{P1 P2}}`"
    );

    use crate::to_abc::{AbcWriteOptions, write_abc};
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("%%score {P1 P2}\n"),
        "write_abc must emit `%%score {{P1 P2}}` for the brace group; got:\n{abc}"
    );
}

#[test]
fn part_group_nested_synthesizes_score_directive() {
    // A bracket group wrapping an inner brace sub-group plus a standalone part:
    // bracket([brace(P1 P2), P3]) โ†’ `%%score [{ P1 P2 } P3]`.
    // MusicXML: group-1(bracket) contains group-2(brace) over P1,P2, then P3.
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <part-group number=\"1\" type=\"start\">\n",
        "      <group-symbol>bracket</group-symbol>\n",
        "    </part-group>\n",
        "    <part-group number=\"2\" type=\"start\">\n",
        "      <group-symbol>brace</group-symbol>\n",
        "    </part-group>\n",
        "    <score-part id=\"P1\"><part-name/></score-part>\n",
        "    <score-part id=\"P2\"><part-name/></score-part>\n",
        "    <part-group number=\"2\" type=\"stop\"/>\n",
        "    <score-part id=\"P3\"><part-name/></score-part>\n",
        "    <part-group number=\"1\" type=\"stop\"/>\n",
        "  </part-list>\n",
    );
    let parts = format!(
        "{}{}{}",
        minimal_part("P1"),
        minimal_part("P2"),
        minimal_part("P3")
    );
    let xml = format!("{xml}{parts}</score-partwise>\n");
    let score = read_musicxml(&xml).value;

    assert_eq!(
        score.metadata.directives.len(),
        1,
        "nested groups must produce exactly one %%score directive"
    );
    let directive_text = &score.metadata.directives[0].value.text;
    assert_eq!(
        directive_text, "[{P1 P2} P3]",
        "nested bracket(brace(P1,P2),P3) must produce `[{{P1 P2}} P3]`"
    );

    use crate::to_abc::{AbcWriteOptions, write_abc};
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("%%score [{P1 P2} P3]\n"),
        "write_abc must emit `%%score [{{P1 P2}} P3]` for nested groups; got:\n{abc}"
    );
}

#[test]
fn no_part_group_synthesizes_no_score_directive() {
    // A MusicXML file with NO `<part-group>` and only single-voice parts must
    // not synthesize any %%score directive โ€” no spurious output.
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <score-part id=\"P1\"><part-name/></score-part>\n",
        "    <score-part id=\"P2\"><part-name/></score-part>\n",
        "  </part-list>\n",
    );
    let parts = format!("{}{}", minimal_part("P1"), minimal_part("P2"));
    let xml = format!("{xml}{parts}</score-partwise>\n");
    let score = read_musicxml(&xml).value;

    assert!(
        score.metadata.directives.is_empty(),
        "no <part-group> must not synthesize any %%score directive; \
         got {:?}",
        score
            .metadata
            .directives
            .iter()
            .map(|d| &d.value.text)
            .collect::<Vec<_>>()
    );

    use crate::to_abc::{AbcWriteOptions, write_abc};
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        !abc.contains("%%score"),
        "write_abc must not emit %%score when there is no part-group; got:\n{abc}"
    );
}

// --- Fix 1 (P1a review): sibling top-level groups ----------------------------
//
// When the `<part-list>` has two or more sibling bracket/brace groups with NO
// enclosing outer group, `build_score_text` must render BOTH groups in document
// order, e.g. `[P1 P2] [P3 P4]`.  The pre-fix code silently dropped the second
// group (it selected the first group as "outermost" and the second failed the
// subset check).

#[test]
fn two_sibling_bracket_groups_both_emitted() {
    // Two bracket groups, each covering 2 parts, with NO enclosing outer group.
    // Expected: `%%score [P1 P2] [P3 P4]`.
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <part-group number=\"1\" type=\"start\">\n",
        "      <group-symbol>bracket</group-symbol>\n",
        "    </part-group>\n",
        "    <score-part id=\"P1\"><part-name/></score-part>\n",
        "    <score-part id=\"P2\"><part-name/></score-part>\n",
        "    <part-group number=\"1\" type=\"stop\"/>\n",
        "    <part-group number=\"2\" type=\"start\">\n",
        "      <group-symbol>bracket</group-symbol>\n",
        "    </part-group>\n",
        "    <score-part id=\"P3\"><part-name/></score-part>\n",
        "    <score-part id=\"P4\"><part-name/></score-part>\n",
        "    <part-group number=\"2\" type=\"stop\"/>\n",
        "  </part-list>\n",
    );
    let parts = format!(
        "{}{}{}{}",
        minimal_part("P1"),
        minimal_part("P2"),
        minimal_part("P3"),
        minimal_part("P4"),
    );
    let xml = format!("{xml}{parts}</score-partwise>\n");
    let score = read_musicxml(&xml).value;

    assert_eq!(
        score.metadata.directives.len(),
        1,
        "two sibling bracket groups must produce exactly one %%score directive; \
         directives = {:?}",
        score
            .metadata
            .directives
            .iter()
            .map(|d| &d.value.text)
            .collect::<Vec<_>>()
    );
    let directive_text = &score.metadata.directives[0].value.text;
    assert_eq!(
        directive_text, "[P1 P2] [P3 P4]",
        "two sibling bracket groups must produce `[P1 P2] [P3 P4]`; got `{directive_text}`"
    );

    use crate::to_abc::{AbcWriteOptions, write_abc};
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("%%score [P1 P2] [P3 P4]\n"),
        "write_abc must emit `%%score [P1 P2] [P3 P4]` for two sibling bracket groups; got:\n{abc}"
    );
}

#[test]
fn sibling_bracket_and_brace_groups_both_emitted() {
    // One bracket group [P1 P2] followed by one brace group {P3 P4}, no outer wrapper.
    // Expected: `%%score [P1 P2] {P3 P4}`.
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <part-group number=\"1\" type=\"start\">\n",
        "      <group-symbol>bracket</group-symbol>\n",
        "    </part-group>\n",
        "    <score-part id=\"P1\"><part-name/></score-part>\n",
        "    <score-part id=\"P2\"><part-name/></score-part>\n",
        "    <part-group number=\"1\" type=\"stop\"/>\n",
        "    <part-group number=\"2\" type=\"start\">\n",
        "      <group-symbol>brace</group-symbol>\n",
        "    </part-group>\n",
        "    <score-part id=\"P3\"><part-name/></score-part>\n",
        "    <score-part id=\"P4\"><part-name/></score-part>\n",
        "    <part-group number=\"2\" type=\"stop\"/>\n",
        "  </part-list>\n",
    );
    let parts = format!(
        "{}{}{}{}",
        minimal_part("P1"),
        minimal_part("P2"),
        minimal_part("P3"),
        minimal_part("P4"),
    );
    let xml = format!("{xml}{parts}</score-partwise>\n");
    let score = read_musicxml(&xml).value;

    assert_eq!(
        score.metadata.directives.len(),
        1,
        "sibling bracket+brace groups must produce exactly one %%score directive; \
         directives = {:?}",
        score
            .metadata
            .directives
            .iter()
            .map(|d| &d.value.text)
            .collect::<Vec<_>>()
    );
    let directive_text = &score.metadata.directives[0].value.text;
    assert_eq!(
        directive_text, "[P1 P2] {P3 P4}",
        "sibling bracket+brace groups must produce `[P1 P2] {{P3 P4}}`; got `{directive_text}`"
    );

    use crate::to_abc::{AbcWriteOptions, write_abc};
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("%%score [P1 P2] {P3 P4}\n"),
        "write_abc must emit `%%score [P1 P2] {{P3 P4}}` for sibling bracket+brace groups; \
         got:\n{abc}"
    );
}

// --- Fix 2 (P1a review): diagnostic on unclosed group -------------------------
//
// An unmatched `<part-group type="start">` with no matching stop at end of
// `<part-list>` must emit a `musicxml.read.unbalanced_part_group` warning
// diagnostic.  The reader must still be non-panicking and must still produce
// a reasonable score (the unbalanced group's parts are ignored, not panicked).

#[test]
fn unbalanced_part_group_emits_diagnostic() {
    // One `<part-group type="start">` with NO matching stop.
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <part-group number=\"1\" type=\"start\">\n",
        "      <group-symbol>bracket</group-symbol>\n",
        "    </part-group>\n",
        "    <score-part id=\"P1\"><part-name/></score-part>\n",
        "    <score-part id=\"P2\"><part-name/></score-part>\n",
        "  </part-list>\n",
    );
    let parts = format!("{}{}", minimal_part("P1"), minimal_part("P2"));
    let xml = format!("{xml}{parts}</score-partwise>\n");
    let report = read_musicxml(&xml);
    let score = &report.value;

    // Must NOT panic (totality) and must still have 2 parts.
    assert_eq!(
        score.parts.len(),
        2,
        "unclosed group must still produce 2 parts"
    );

    // Must emit at least one diagnostic with the expected code.
    let has_diag = report
        .diagnostics
        .iter()
        .any(|d| d.code == "musicxml.read.unbalanced_part_group");
    assert!(
        has_diag,
        "unclosed <part-group> must emit a `musicxml.read.unbalanced_part_group` diagnostic; \
         got diagnostics: {:?}",
        report
            .diagnostics
            .iter()
            .map(|d| d.code)
            .collect::<Vec<_>>()
    );
}

// --- Fix 3 (P1a review): ungrouped parts must appear in %%score ---------------
//
// When a `<part-list>` has SOME parts inside a `<part-group>` and OTHERS
// outside any group, the synthesized `%%score` must list EVERY part in
// document order โ€” grouped parts inside their brackets, ungrouped parts as
// bare voice-id tokens at their document-order position.
//
// Without this fix the ungrouped part's voice is HIDDEN by `%%score` (ABC
// renderers only print voices named in `%%score`), which is a fidelity
// regression versus the pre-P1a behaviour (no `%%score` โ†’ all voices print).

#[test]
fn ungrouped_part_included_in_score_directive() {
    // 4 parts: bracket group over P1, P2, P3; P4 is standalone (ungrouped).
    // Expected %%score: `[P1 P2 P3] P4`  (P4 in its document position after
    // the group).
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <part-list>\n",
        "    <part-group number=\"1\" type=\"start\">\n",
        "      <group-symbol>bracket</group-symbol>\n",
        "    </part-group>\n",
        "    <score-part id=\"P1\"><part-name/></score-part>\n",
        "    <score-part id=\"P2\"><part-name/></score-part>\n",
        "    <score-part id=\"P3\"><part-name/></score-part>\n",
        "    <part-group number=\"1\" type=\"stop\"/>\n",
        "    <score-part id=\"P4\"><part-name/></score-part>\n",
        "  </part-list>\n",
    );
    let parts = format!(
        "{}{}{}{}",
        minimal_part("P1"),
        minimal_part("P2"),
        minimal_part("P3"),
        minimal_part("P4"),
    );
    let xml = format!("{xml}{parts}</score-partwise>\n");
    let score = read_musicxml(&xml).value;

    assert_eq!(
        score.metadata.directives.len(),
        1,
        "bracket group + standalone P4 must produce exactly one %%score directive; \
         directives = {:?}",
        score
            .metadata
            .directives
            .iter()
            .map(|d| &d.value.text)
            .collect::<Vec<_>>()
    );
    let directive_text = &score.metadata.directives[0].value.text;
    assert_eq!(
        directive_text, "[P1 P2 P3] P4",
        "bracket group + standalone P4 must produce `[P1 P2 P3] P4`; got `{directive_text}`"
    );

    use crate::to_abc::{AbcWriteOptions, write_abc};
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("%%score [P1 P2 P3] P4\n"),
        "write_abc must emit `%%score [P1 P2 P3] P4` for bracket group + standalone P4; \
         got:\n{abc}"
    );
}

// --- P3: body/inline `P:` section label <-> <rehearsal> ----------------------

/// Collect every `SectionLabel(label)` across all parts/voices, in document
/// order, as owned strings โ€” the model surface the writer emits as
/// `<rehearsal>` and the reader reconstructs from one.
fn section_labels(score: &Score) -> Vec<String> {
    let mut labels = Vec::new();
    for part in &score.parts {
        for voice in &part.voices {
            for event in &voice.events {
                if let TimedEventKind::SectionLabel(label) = &event.kind {
                    labels.push(label.clone());
                }
            }
        }
    }
    labels
}

#[test]
fn body_part_label_round_trips_through_rehearsal() {
    // A body `P:A` section label (ABC 2.1 ยง4.3) must become a <rehearsal> in the
    // writer, read back into a SectionLabel event, and re-write byte-identically.
    let abc = "X:1\nT:Sections\nM:4/4\nL:1/4\nK:C\nP:A\nC D E F |\nP:B\nG A B c |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<rehearsal font-weight=\"bold\">A</rehearsal>"),
        "precondition: body `P:A` must emit a <rehearsal>A direction; got:\n{x1}"
    );
    assert!(
        x1.contains("<rehearsal font-weight=\"bold\">B</rehearsal>"),
        "precondition: body `P:B` must emit a <rehearsal>B direction"
    );
    let score = assert_idempotent_full(abc);
    assert_eq!(
        section_labels(&score),
        vec!["A".to_owned(), "B".to_owned()],
        "the reader must reconstruct both body section labels in order"
    );
}

#[test]
fn inline_part_label_round_trips_through_rehearsal() {
    // An inline `[P:B]` mid-line section label must round-trip identically too.
    let abc = "X:1\nT:Inline\nM:4/4\nL:1/4\nK:C\nC D [P:B] E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<rehearsal font-weight=\"bold\">B</rehearsal>"),
        "precondition: inline `[P:B]` must emit a <rehearsal>B direction; got:\n{x1}"
    );
    let score = assert_idempotent_full(abc);
    assert_eq!(
        section_labels(&score),
        vec!["B".to_owned()],
        "the reader must reconstruct the inline section label"
    );
}

#[test]
fn foreign_rehearsal_imports_as_part_label() {
    // A minimal foreign MusicXML carrying abc2xml's <rehearsal> shape must read
    // into a SectionLabel and write back to ABC as `[P:A]`.
    let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<score-partwise version="3.1">
  <part-list>
    <score-part id="P1"><part-name>V</part-name></score-part>
  </part-list>
  <part id="P1">
    <measure number="1">
      <attributes>
        <divisions>1</divisions>
        <key><fifths>0</fifths></key>
        <time><beats>4</beats><beat-type>4</beat-type></time>
        <clef><sign>G</sign><line>2</line></clef>
      </attributes>
      <direction placement="above">
        <direction-type>
          <rehearsal font-weight="bold">A</rehearsal>
        </direction-type>
      </direction>
      <note>
        <pitch><step>C</step><octave>4</octave></pitch>
        <duration>4</duration>
        <type>whole</type>
      </note>
    </measure>
  </part>
</score-partwise>
"#;
    let report = read_musicxml(xml);
    assert_eq!(
        section_labels(&report.value),
        vec!["A".to_owned()],
        "a foreign <rehearsal> must import as a SectionLabel; diags: {:?}",
        report.diagnostics
    );
    use crate::to_abc::{AbcWriteOptions, write_abc};
    let abc = write_abc(&report.value, AbcWriteOptions::default());
    assert!(
        abc.contains("[P:A]"),
        "write_abc must emit `[P:A]` for the imported section label; got:\n{abc}"
    );
}

#[test]
fn foreign_rehearsal_newline_does_not_break_inline_label() {
    // A foreign <rehearsal> may carry a trailing/interior newline (e.g.
    // "pre chorus\n", "G#7\n"). An inline `[P:...]` field is single-line, so a raw
    // newline split the line and corrupted the following music (PDMX section-label
    // cluster: pdmx_1142, pdmx_1389, pdmx_1807). The label's control characters must
    // normalise to a space (then trim) so the field stays on one line.
    let xml = "<?xml version=\"1.0\"?>\n\
<score-partwise>\n\
  <part-list><score-part id=\"P1\"><part-name>V</part-name></score-part></part-list>\n\
  <part id=\"P1\"><measure number=\"1\">\n\
    <attributes><divisions>1</divisions></attributes>\n\
    <direction placement=\"above\"><direction-type>\n\
      <rehearsal>pre chorus\n</rehearsal>\n\
    </direction-type></direction>\n\
    <note><pitch><step>C</step><octave>4</octave></pitch><duration>4</duration><type>whole</type></note>\n\
  </measure></part>\n\
</score-partwise>\n";
    let report = read_musicxml(xml);
    use crate::to_abc::{AbcWriteOptions, write_abc};
    let abc = write_abc(&report.value, AbcWriteOptions::default());
    assert!(
        abc.contains("[P:pre chorus]"),
        "the rehearsal newline must normalise so `[P:...]` stays on one line; got:\n{abc}"
    );
    // The note must survive re-export (no line-break cascade).
    let roundtrip = export_musicxml(&abc).expect("sanitised section-label ABC should export");
    assert!(
        roundtrip.musicxml.contains("<step>C</step>"),
        "the following note must survive section-label normalisation:\n{}",
        roundtrip.musicxml
    );
}

#[test]
fn header_play_order_is_not_a_rehearsal() {
    // CRITICAL boundary: a HEADER `P:ABAB` is the play-order macro, NOT a section
    // label. It must stay dropped (no <rehearsal>, no SectionLabel event), exactly
    // as today โ€” turning it into a rehearsal mark would corrupt the file.
    let abc = "X:1\nT:PlayOrder\nM:4/4\nL:1/4\nP:ABAB\nK:C\nC D E F |\n";
    let x1 = export(abc);
    assert!(
        !x1.contains("<rehearsal"),
        "a header `P:ABAB` must NOT emit a <rehearsal>; got:\n{x1}"
    );
    let report = read_musicxml(&x1);
    assert!(
        section_labels(&report.value).is_empty(),
        "a header `P:ABAB` must produce no SectionLabel events"
    );
}

#[test]
fn rehearsal_label_xml_escapes_round_trip() {
    // A label containing `&` and `<` must be XML-escaped on write and unescaped on
    // read, round-tripping byte-identically.
    let abc = "X:1\nT:Escape\nM:4/4\nL:1/4\nK:C\nP:A&<B\nC D E F |\n";
    let x1 = export(abc);
    assert!(
        x1.contains("<rehearsal font-weight=\"bold\">A&amp;&lt;B</rehearsal>"),
        "the `&`/`<` in the label must be XML-escaped in <rehearsal>; got:\n{x1}"
    );
    let score = assert_idempotent_full(abc);
    assert_eq!(
        section_labels(&score),
        vec!["A&<B".to_owned()],
        "the reader must XML-unescape the label back to `A&<B`"
    );
}

/// The first line at which two ABC documents diverge, rendered as
/// `` `<expected>` != `<actual>` ``. `None`-free: returns a sentinel when one is
/// a prefix of the other. Used only for the human-readable divergence note.
fn first_diverging_line(expected: &str, actual: &str) -> String {
    for (line_e, line_a) in expected.lines().zip(actual.lines()) {
        if line_e != line_a {
            return format!("`{line_e}` != `{line_a}`");
        }
    }
    let expected_lines = expected.lines().count();
    let actual_lines = actual.lines().count();
    if expected_lines == actual_lines {
        "<equal-lines-unequal-bytes>".to_owned()
    } else {
        format!("<line-count differs: expected {expected_lines}, actual {actual_lines}>")
    }
}

// --- Per-part divisions (issue #239) ----------------------------------------
//
// MusicXML scopes `<divisions>` to each part's `<attributes>` (and a later
// measure may redefine it). A multi-part score can therefore carry a different
// divisions per part โ€” common in Finale/MuseScore exports. The reader must
// decode each part's `<duration>` against THAT part's divisions, not a single
// global value taken from the first `<divisions>` in document order.

#[test]
fn per_part_divisions_are_decoded_independently() {
    // P1 declares divisions=4, P2 declares divisions=2. Both notes are quarter
    // notes (duration = one beat in their own part). Both must reconstruct as
    // 1/4. Reading P2's `<duration>2</duration>` against P1's divisions=4 would
    // misread it as an eighth (1/8) โ€” the Faurรฉ piano bug in miniature.
    let xml = concat!(
        "<score-partwise version=\"4.0\">",
        "<part-list>",
        "<score-part id=\"P1\"><part-name>A</part-name></score-part>",
        "<score-part id=\"P2\"><part-name>B</part-name></score-part>",
        "</part-list>",
        "<part id=\"P1\"><measure number=\"1\">",
        "<attributes><divisions>4</divisions><key><fifths>0</fifths></key>",
        "<time><beats>1</beats><beat-type>4</beat-type></time>",
        "<clef><sign>G</sign><line>2</line></clef></attributes>",
        "<note><pitch><step>C</step><octave>4</octave></pitch>",
        "<duration>4</duration><type>quarter</type></note>",
        "</measure></part>",
        "<part id=\"P2\"><measure number=\"1\">",
        "<attributes><divisions>2</divisions><key><fifths>0</fifths></key>",
        "<time><beats>1</beats><beat-type>4</beat-type></time>",
        "<clef><sign>F</sign><line>4</line></clef></attributes>",
        "<note><pitch><step>C</step><octave>3</octave></pitch>",
        "<duration>2</duration><type>quarter</type></note>",
        "</measure></part>",
        "</score-partwise>",
    );
    let score = read_musicxml(xml).value;
    assert_eq!(score.parts.len(), 2, "two parts");
    assert_eq!(
        score.parts[0].voices[0].events[0].duration,
        Fraction::new(1, 4),
        "P1 quarter at its own divisions=4"
    );
    assert_eq!(
        score.parts[1].voices[0].events[0].duration,
        Fraction::new(1, 4),
        "P2 quarter at its own divisions=2 must be 1/4, not misread against P1's divisions=4"
    );
}

#[test]
fn mid_part_divisions_change_is_applied() {
    // A later measure redefines `<divisions>`. Notes after the change must be
    // decoded against the new value. Measure 1: div=2, quarter (dur=2) -> 1/4.
    // Measure 2: div=8, quarter (dur=8) -> 1/4. A reader that froze divisions at
    // the part's first value would misread measure 2's quarter as a whole note.
    let xml = concat!(
        "<score-partwise version=\"4.0\">",
        "<part-list><score-part id=\"P1\"><part-name>A</part-name></score-part></part-list>",
        "<part id=\"P1\">",
        "<measure number=\"1\">",
        "<attributes><divisions>2</divisions><key><fifths>0</fifths></key>",
        "<time><beats>1</beats><beat-type>4</beat-type></time>",
        "<clef><sign>G</sign><line>2</line></clef></attributes>",
        "<note><pitch><step>C</step><octave>4</octave></pitch>",
        "<duration>2</duration><type>quarter</type></note>",
        "</measure>",
        "<measure number=\"2\">",
        "<attributes><divisions>8</divisions></attributes>",
        "<note><pitch><step>D</step><octave>4</octave></pitch>",
        "<duration>8</duration><type>quarter</type></note>",
        "</measure>",
        "</part></score-partwise>",
    );
    let score = read_musicxml(xml).value;
    let events = &score.parts[0].voices[0].events;
    assert_eq!(
        events[0].duration,
        Fraction::new(1, 4),
        "measure 1 quarter at divisions=2"
    );
    assert_eq!(
        events[1].duration,
        Fraction::new(1, 4),
        "measure 2 quarter at the redefined divisions=8 must still be 1/4"
    );
}

// --- Movement-title fallback (issue #240) -----------------------------------

#[test]
fn movement_title_populates_metadata_title_when_work_title_absent() {
    // A score titled via top-level <movement-title> with no <work><work-title>
    // (common in Finale/MuseScore exports) must populate metadata.title so the
    // ABC projection emits a T: line.
    let xml = concat!(
        "<score-partwise version=\"4.0\">",
        "<movement-title>Apres un reve</movement-title>",
        "<part-list><score-part id=\"P1\"><part-name>V</part-name></score-part></part-list>",
        "<part id=\"P1\"><measure number=\"1\">",
        "<attributes><divisions>1</divisions><key><fifths>0</fifths></key>",
        "<time><beats>4</beats><beat-type>4</beat-type></time>",
        "<clef><sign>G</sign><line>2</line></clef></attributes>",
        "<note><pitch><step>C</step><octave>4</octave></pitch>",
        "<duration>4</duration><type>whole</type></note>",
        "</measure></part></score-partwise>",
    );
    let score = read_musicxml(xml).value;
    assert_eq!(
        score.metadata.title.as_ref().map(|t| t.text.as_str()),
        Some("Apres un reve"),
        "<movement-title> must populate metadata.title when <work-title> is absent"
    );
}

#[test]
fn work_title_wins_over_movement_title() {
    // When both are present, <work-title> takes precedence (it is what croma's
    // own writer emits, so the self-loop stays byte-stable).
    let xml = concat!(
        "<score-partwise version=\"4.0\">",
        "<work><work-title>Work Title</work-title></work>",
        "<movement-title>Movement Title</movement-title>",
        "<part-list><score-part id=\"P1\"><part-name>V</part-name></score-part></part-list>",
        "<part id=\"P1\"><measure number=\"1\">",
        "<attributes><divisions>1</divisions><key><fifths>0</fifths></key>",
        "<time><beats>4</beats><beat-type>4</beat-type></time>",
        "<clef><sign>G</sign><line>2</line></clef></attributes>",
        "<note><pitch><step>C</step><octave>4</octave></pitch>",
        "<duration>4</duration><type>whole</type></note>",
        "</measure></part></score-partwise>",
    );
    let score = read_musicxml(xml).value;
    assert_eq!(
        score.metadata.title.as_ref().map(|t| t.text.as_str()),
        Some("Work Title"),
        "<work-title> must win when both are present"
    );
}

// --- Composer projection (collateral of #239/#240 audit) --------------------
//
// The reader captures `<creator type="composer">` into `metadata.composers`, and
// `write_musicxml` re-emits it, so composer survives the MusicXML self-loop. But
// the ABC PROJECTION (`write_abc`) dropped it โ€” no `C:` field โ€” so a
// MusicXML -> ABC -> MusicXML round trip lost the structured composer entirely.
// The ABC parser already reads `C:` into composers, so emitting it closes the
// loop.

#[test]
fn composer_projects_to_abc_c_field_and_round_trips() {
    let xml = concat!(
        "<score-partwise version=\"4.0\">",
        "<work><work-title>Song</work-title></work>",
        "<identification><creator type=\"composer\">Gabriel Faure</creator></identification>",
        "<part-list><score-part id=\"P1\"><part-name>V</part-name></score-part></part-list>",
        "<part id=\"P1\"><measure number=\"1\">",
        "<attributes><divisions>1</divisions><key><fifths>0</fifths></key>",
        "<time><beats>4</beats><beat-type>4</beat-type></time>",
        "<clef><sign>G</sign><line>2</line></clef></attributes>",
        "<note><pitch><step>C</step><octave>4</octave></pitch>",
        "<duration>4</duration><type>whole</type></note>",
        "</measure></part></score-partwise>",
    );
    let score = read_musicxml(xml).value;
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(
        abc.contains("\nC:Gabriel Faure\n"),
        "ABC projection must emit a C: composer field, got:\n{abc}"
    );
    // Closing the loop: the projected ABC must export back to a <creator>.
    let xml2 = export(&abc);
    assert!(
        xml2.contains("<creator type=\"composer\">Gabriel Faure</creator>"),
        "C: must export back to <creator type=\"composer\">, got:\n{xml2}"
    );
}

// --- Multi-staff grand staff (bass clef) ------------------------------------
//
// A piano grand staff is ONE MusicXML part with `<staves>2`, a `<clef number=N>`
// per staff, and each note tagged with its `<staff>`. The reader must build
// `Part.staves` with one entry per staff, route each voice to its staff, and give
// each voice its staff's clef โ€” so the bass-clef (staff 2) voice reads in bass,
// not treble. Single-staff parts (no `<staves>`) are unaffected.

#[test]
fn two_staff_part_reconstructs_staves_and_per_staff_clefs() {
    let xml = concat!(
        "<score-partwise version=\"4.0\">",
        "<part-list><score-part id=\"P1\"><part-name>Piano</part-name></score-part></part-list>",
        "<part id=\"P1\"><measure number=\"1\">",
        "<attributes><divisions>1</divisions><key><fifths>0</fifths></key>",
        "<time><beats>4</beats><beat-type>4</beat-type></time>",
        "<staves>2</staves>",
        "<clef number=\"1\"><sign>G</sign><line>2</line></clef>",
        "<clef number=\"2\"><sign>F</sign><line>4</line></clef></attributes>",
        "<note><pitch><step>C</step><octave>5</octave></pitch><duration>4</duration>",
        "<voice>1</voice><type>whole</type><staff>1</staff></note>",
        "<backup><duration>4</duration></backup>",
        "<note><pitch><step>C</step><octave>3</octave></pitch><duration>4</duration>",
        "<voice>2</voice><type>whole</type><staff>2</staff></note>",
        "</measure></part></score-partwise>",
    );
    let score = read_musicxml(xml).value;
    let part = &score.parts[0];
    assert_eq!(part.staves.len(), 2, "two staves reconstructed");
    assert_eq!(part.voices.len(), 2, "two voices");
    assert_eq!(part.voices[0].staff.value, 1, "voice 1 routed to staff 1");
    assert_eq!(part.voices[1].staff.value, 2, "voice 2 routed to staff 2");
    assert_eq!(
        part.voices[0]
            .initial_properties
            .clef
            .as_ref()
            .map(|c| c.text.as_str()),
        None,
        "staff 1 is treble (default, no clef property)"
    );
    assert_eq!(
        part.voices[1]
            .initial_properties
            .clef
            .as_ref()
            .map(|c| c.text.as_str()),
        Some("bass"),
        "staff 2 voice must carry the bass clef"
    );
    // Pure MusicXML round-trip (write_musicxml inverse) must re-emit the grand staff.
    let xml2 = write_score_partwise(&score).value;
    assert!(
        xml2.contains("<staves>2</staves>"),
        "re-emit <staves>2, got:\n{xml2}"
    );
    assert!(
        xml2.contains("<clef number=\"2\">") && xml2.contains("<sign>F</sign>"),
        "re-emit the bass <clef number=2>, got:\n{xml2}"
    );
}

#[test]
fn two_staff_part_synthesizes_brace_score_directive() {
    // A grand-staff part's voices must be grouped with a BRACE `{โ€ฆ}` in %%score
    // (separate staves), not a PAREN `(โ€ฆ)` (shared staff). That brace is what
    // tells the lowering to rebuild two staves on the ABC round trip.
    let xml = concat!(
        "<score-partwise version=\"4.0\">",
        "<part-list><score-part id=\"P1\"><part-name>Piano</part-name></score-part></part-list>",
        "<part id=\"P1\"><measure number=\"1\">",
        "<attributes><divisions>1</divisions><key><fifths>0</fifths></key>",
        "<time><beats>4</beats><beat-type>4</beat-type></time>",
        "<staves>2</staves>",
        "<clef number=\"1\"><sign>G</sign><line>2</line></clef>",
        "<clef number=\"2\"><sign>F</sign><line>4</line></clef></attributes>",
        "<note><pitch><step>C</step><octave>5</octave></pitch><duration>4</duration>",
        "<voice>1</voice><type>whole</type><staff>1</staff></note>",
        "<backup><duration>4</duration></backup>",
        "<note><pitch><step>C</step><octave>3</octave></pitch><duration>4</duration>",
        "<voice>2</voice><type>whole</type><staff>2</staff></note>",
        "</measure></part></score-partwise>",
    );
    let score = read_musicxml(xml).value;
    let directive = score
        .metadata
        .directives
        .iter()
        .find(|d| d.value.text.contains("P1"))
        .expect("a %%score directive for the grand staff");
    assert_eq!(
        directive.value.text.trim(),
        "{P1 P1#2}",
        "grand staff must use a brace group, got {:?}",
        directive.value.text
    );
}

#[test]
fn brace_score_group_lowers_to_one_part_with_two_staves() {
    // `%%score {V1 V2}` is a grand staff: ONE part with two staves, each voice on
    // its own staff with its own clef. A paren group `(V1 V2)` shares one staff;
    // the brace must instead produce <staves>2 and a per-staff <clef>, so the bass
    // voice's clef=bass survives the ABC -> MusicXML export.
    // The grand staff's two voices share a base id (P1, P1#2) โ€” croma's
    // continuation naming โ€” which is how a brace is told apart from a
    // `<part-group>` brace over distinct parts (`{P1 P2}`, which stays separate).
    let abc = concat!(
        "X:1\n",
        "%%score {P1 P1#2}\n",
        "M:4/4\nL:1/4\nK:C\n",
        "V:P1 clef=treble\n",
        "C D E F |\n",
        "V:P1#2 clef=bass\n",
        "C,, D,, E,, F,, |\n",
    );
    let xml = export(abc);
    assert_eq!(
        xml.matches("<part id=").count(),
        1,
        "a same-part brace group is ONE part (grand staff), got:\n{xml}"
    );
    assert!(
        xml.contains("<staves>2</staves>"),
        "the grand staff must export <staves>2, got:\n{xml}"
    );
    assert!(
        xml.contains("<clef number=\"2\">") && xml.contains("<sign>F</sign>"),
        "the bass voice must export a <clef number=\"2\"> F clef, got:\n{xml}"
    );
}

#[test]
fn brace_over_distinct_parts_stays_two_parts() {
    // `{P1 P2}` braces two DISTINCT parts (a `<part-group symbol="brace">`, e.g. a
    // piano-and-voice system), NOT a grand staff. It must stay TWO parts โ€” the
    // grand-staff merge only applies when the members share a base voice id.
    let abc = concat!(
        "X:1\n",
        "%%score {P1 P2}\n",
        "M:4/4\nL:1/4\nK:C\n",
        "V:P1\n",
        "C D E F |\n",
        "V:P2\n",
        "C,, D,, E,, F,, |\n",
    );
    let xml = export(abc);
    assert_eq!(
        xml.matches("<part id=").count(),
        2,
        "a brace over distinct part ids must stay two parts, got:\n{xml}"
    );
    assert!(
        !xml.contains("<staves>"),
        "two distinct parts must not collapse into a multi-staff part, got:\n{xml}"
    );
}

/// Issue #267: a mid-tune `<clef>` must survive MusicXML -> ABC. The clef change
/// events the reader builds carry no `musicxml_cursor_back` metadata (that field
/// exists only for the clef-cursor carrier the ABC->XML direction plants), and the
/// ABC writer emitted the carrier or nothing at all, so every ordinary clef change
/// was silently dropped on the way out.
#[test]
fn mid_tune_clef_change_projects_to_inline_abc_field() {
    let xml = concat!(
        "<score-partwise version=\"4.0\"><part-list><score-part id=\"P1\">",
        "<part-name>Music</part-name></score-part></part-list><part id=\"P1\">",
        "<measure number=\"1\">",
        "<attributes><divisions>2</divisions><key><fifths>0</fifths></key>",
        "<time><beats>4</beats><beat-type>4</beat-type></time>",
        "<clef><sign>G</sign><line>2</line></clef></attributes>",
        "<note><pitch><step>C</step><octave>4</octave></pitch><duration>2</duration>",
        "<voice>1</voice><type>quarter</type></note>",
        "<attributes><clef><sign>F</sign><line>4</line></clef></attributes>",
        "<note><pitch><step>C</step><octave>3</octave></pitch><duration>6</duration>",
        "<voice>1</voice><type>half</type></note>",
        "</measure></part></score-partwise>",
    );
    let report = read_musicxml(xml);
    let abc = write_abc(&report.value, AbcWriteOptions::default());
    assert!(
        abc.contains("[K:clef=bass]"),
        "a mid-tune <clef> must project as an inline `[K:clef=..]` field; got:\n{abc}"
    );
    // The change must survive re-export at the same position (one mid-tune
    // `<attributes>` holding only the bass clef, after the first note).
    let roundtrip = export_musicxml(&abc).expect("clef-change ABC should export");
    assert!(
        roundtrip
            .musicxml
            .contains("<attributes>\n        <clef>\n          <sign>F</sign>"),
        "the clef change must re-export as its own mid-tune <attributes>; got:\n{}",
        roundtrip.musicxml
    );
}

/// Issue #267: a `<clef number="N">` change belongs to the voices on staff `N`,
/// not to whichever voice happened to be active at that point in the measure. The
/// reproducer routes a staff-2 clef change that appears while voice 1 is current
/// (after a `<backup>`/`<forward>` pair) and, in the next measure, in a leading
/// `<attributes>` block before any note.
#[test]
fn numbered_clef_change_routes_to_its_staff_voice() {
    let xml = concat!(
        "<score-partwise version=\"4.0\"><part-list><score-part id=\"P1\">",
        "<part-name>Piano</part-name></score-part></part-list><part id=\"P1\">",
        "<measure number=\"1\"><attributes><divisions>8</divisions>",
        "<key><fifths>3</fifths></key><time><beats>2</beats><beat-type>4</beat-type></time>",
        "<staves>2</staves><clef number=\"1\"><sign>G</sign><line>2</line></clef>",
        "<clef number=\"2\"><sign>F</sign><line>4</line></clef></attributes>",
        "<forward><duration>2</duration><voice>1</voice><staff>1</staff></forward>",
        "<note><pitch><step>A</step><octave>4</octave></pitch><duration>4</duration>",
        "<voice>1</voice><type>eighth</type><staff>1</staff></note>",
        "<backup><duration>6</duration></backup>",
        "<forward><duration>2</duration><voice>3</voice><staff>2</staff></forward>",
        "<attributes><clef number=\"2\"><sign>G</sign><line>2</line></clef></attributes>",
        "<note><pitch><step>A</step><octave>4</octave></pitch><duration>4</duration>",
        "<voice>3</voice><type>eighth</type><staff>2</staff></note></measure>",
        "<measure number=\"2\"><attributes>",
        "<clef number=\"2\"><sign>F</sign><line>4</line></clef></attributes>",
        "<note><pitch><step>E</step><octave>4</octave></pitch><duration>16</duration>",
        "<voice>1</voice><type>half</type><staff>1</staff></note>",
        "<backup><duration>16</duration></backup>",
        "<note><pitch><step>A</step><octave>3</octave></pitch><duration>16</duration>",
        "<voice>3</voice><type>half</type><staff>2</staff></note></measure>",
        "</part></score-partwise>",
    );
    let report = read_musicxml(xml);
    let abc = write_abc(&report.value, AbcWriteOptions::default());
    let lower_staff = abc
        .lines()
        .skip_while(|line| !line.starts_with("V:P1#3"))
        .skip(1)
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        lower_staff.contains("[K:clef=treble]") && lower_staff.contains("[K:clef=bass]"),
        "both staff-2 clef changes belong to the lower staff's voice; got:\n{abc}"
    );
    let upper_staff = abc
        .lines()
        .skip_while(|line| !line.starts_with("V:P1 "))
        .take_while(|line| !line.starts_with("V:P1#3"))
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        !upper_staff.contains("clef="),
        "no clef change belongs to the upper staff's voice; got:\n{abc}"
    );
    // Re-export must put both changes back on staff 2.
    let roundtrip = export_musicxml(&abc).expect("grand-staff clef ABC should export");
    assert_eq!(
        roundtrip.musicxml.matches("<clef number=\"2\">").count(),
        3,
        "staff 2 keeps its header clef plus both changes; got:\n{}",
        roundtrip.musicxml
    );
}

/// Issue #267 guard: `write_abc` spells every pitch of a voice for ONE octave
/// shift (the voice's `clef=ยฑ8`/`octave=`/`middle=`), so projecting a mid-tune
/// clef change whose `ยฑ8`/`ยฑ15` component differs would move that shift on
/// re-parse and transpose every following note by an octave. The inline field
/// must carry the compensating `octave=`, keeping the round-trip pitch-exact.
#[test]
fn octave_shifting_clef_change_compensates_the_voice_shift() {
    let abc = "X:1\nM:4/4\nL:1/4\nK:C\nV:1\nC C [K:clef=treble-8] C C |\n";
    let x1 = export(abc);
    let report = read_musicxml(&x1);
    let projected = write_abc(&report.value, AbcWriteOptions::default());
    assert!(
        projected.contains("[K:clef=treble-8 octave=1]"),
        "the -8 clef change must carry its `octave=` compensation; got:\n{projected}"
    );
    let x2 = export_musicxml(&projected)
        .expect("clef-change projection should export")
        .musicxml;
    assert_eq!(
        x1, x2,
        "the octave-shifting clef change must round-trip pitch-exactly"
    );
}

#[test]
fn legend_lists_only_the_codes_the_document_uses() {
    // `mr` (meter restatement) round-trips self-contained from plain ABC: an
    // `[I:cr le=1]` melisma carrier, by contrast, only survives when it is
    // paired with a matching `w:` lyric line, so it is not usable here as a
    // minimal single-carrier fixture.
    let abc = "X:1\nM:4/4\nL:1/4\nK:C\n[I:cr mr][M:4/4]C D E F |\n";
    let score = crate::lower_score(
        &crate::parse_document(abc, crate::ParseOptions::default()).value,
        crate::LowerOptions,
    )
    .value
    .expect("score");

    let plain = write_abc(&score, AbcWriteOptions::default());
    assert!(!plain.contains('%'), "the legend is opt-in; got:\n{plain}");

    let options = AbcWriteOptions { legend: true };
    let with_legend = write_abc(&score, options);
    assert!(
        with_legend.starts_with("% croma carriers used in this file:"),
        "got:\n{with_legend}"
    );
    // The literal `[I:cr mr]` also appears in the tune body itself (see the
    // fixture above), so asserting on it alone would pass even if the legend
    // body were empty or wrong. Assert on the `mr` line's human-readable
    // description instead, which only the legend text can contain.
    assert!(
        with_legend.contains("meter restatement"),
        "legend body must describe the `mr` carrier it lists, not just emit \
         the header; got:\n{with_legend}"
    );
    assert!(
        !with_legend.contains("dp="),
        "unused codes must not be listed; got:\n{with_legend}"
    );

    // The block is an ABC comment: it must not change what the file means.
    assert_eq!(
        export_musicxml(&with_legend)
            .expect("legend ABC exports")
            .musicxml,
        export_musicxml(&plain).expect("plain ABC exports").musicxml,
    );
}

/// The `%%score` text the reader synthesises for a `<part-list>` body (the
/// groups and `<score-part>`s between `<part-list>` tags) over parts P1..Pn.
fn score_text_for_part_list(part_list: &str, part_count: usize) -> String {
    let parts: String = (1..=part_count)
        .map(|n| minimal_part(&format!("P{n}")))
        .collect();
    let xml = format!(
        "<?xml version=\"1.0\"?>\n<score-partwise>\n  <part-list>\n{part_list}  </part-list>\n\
         {parts}</score-partwise>\n"
    );
    let score = read_musicxml(&xml).value;
    assert_eq!(score.metadata.directives.len(), 1, "one %%score directive");
    score.metadata.directives[0].value.text.clone()
}

fn group_start(number: u32, symbol: &str) -> String {
    format!(
        "    <part-group number=\"{number}\" type=\"start\"><group-symbol>{symbol}</group-symbol></part-group>\n"
    )
}

fn group_stop(number: u32) -> String {
    format!("    <part-group number=\"{number}\" type=\"stop\"/>\n")
}

fn score_part(id: &str) -> String {
    format!("    <score-part id=\"{id}\"><part-name/></score-part>\n")
}

#[test]
fn part_groups_over_identical_parts_nest_in_start_order() {
    // A bracket and a brace both spanning P1 P2 used to cancel out (each counted
    // as inside the other, so neither was top-level) and gave `P1 P2`. Both
    // survive, the one started first outermost, whichever stops first.
    for (first_stop, second_stop) in [(2, 1), (1, 2)] {
        let part_list = [
            group_start(1, "bracket"),
            group_start(2, "brace"),
            score_part("P1"),
            score_part("P2"),
            group_stop(first_stop),
            group_stop(second_stop),
        ]
        .concat();
        assert_eq!(score_text_for_part_list(&part_list, 2), "[{P1 P2}]");
    }
}

#[test]
fn three_level_part_group_nesting_keeps_every_level() {
    // bracket{P1-P4} > brace{P1-P3} > bracket{P1-P2}: sub-groups were keyed by
    // their first part and rendered one level deep, so the innermost group
    // (sharing P1 with the brace) was lost. Every level must survive.
    let part_list = [
        group_start(1, "bracket"),
        group_start(2, "brace"),
        group_start(3, "bracket"),
        score_part("P1"),
        score_part("P2"),
        group_stop(3),
        score_part("P3"),
        group_stop(2),
        score_part("P4"),
        group_stop(1),
    ]
    .concat();
    assert_eq!(score_text_for_part_list(&part_list, 4), "[{[P1 P2] P3} P4]");
}

#[test]
fn huge_lyric_numbers_are_dropped_instead_of_expanding_into_empty_verses() {
    // Verse N is the Nth `w:` line in ABC, so `<lyric number="65536">` used to
    // write 65,535 `w:*` placeholders. Numbers above MAX_LYRIC_VERSE are now
    // dropped with a warning; ordinary numbers still read.
    let lyric_part = |number: &str| {
        format!(
            "<?xml version=\"1.0\"?>\n<score-partwise>\n  <part-list>\n\
             <score-part id=\"P1\"><part-name/></score-part>\n  </part-list>\n\
             <part id=\"P1\"><measure number=\"1\">\
             <attributes><divisions>4</divisions></attributes>\
             <note><pitch><step>C</step><octave>4</octave></pitch><duration>4</duration>\
             <voice>1</voice><type>quarter</type>\
             <lyric number=\"{number}\"><syllabic>single</syllabic><text>la</text></lyric>\
             </note></measure></part>\n</score-partwise>\n"
        )
    };
    use crate::to_abc::{AbcWriteOptions, write_abc};

    let report = read_musicxml(&lyric_part("65536"));
    assert!(
        report
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.code == "musicxml.read.lyric_number_out_of_range")
    );
    let abc = write_abc(&report.value, AbcWriteOptions::default());
    assert!(
        abc.lines().filter(|line| line.starts_with("w:")).count() <= 1,
        "{abc}"
    );

    let report = read_musicxml(&lyric_part("2"));
    let abc = write_abc(&report.value, AbcWriteOptions::default());
    assert!(
        abc.contains("w:*\nw:la"),
        "verse 2 keeps its position:\n{abc}"
    );
}

#[test]
fn score_grouping_survives_abc_to_xml_to_abc() {
    // The writer now emits `<part-group>` for `%%score` brackets and braces, and
    // the reader turns them back into `%%score`, so grouping round-trips.
    use crate::to_abc::{AbcWriteOptions, write_abc};
    let source = "X:1\n%%score [{V1 V2} V3] V4\nL:1/4\nK:C\n\
                  V:V1\nC4|\nV:V2\nD4|\nV:V3\nE4|\nV:V4\nF4|\n";
    let xml = crate::export_musicxml(source).expect("export").musicxml;
    let score = read_musicxml(&xml).value;
    let abc = write_abc(&score, AbcWriteOptions::default());
    assert!(abc.contains("%%score [{P1 P2} P3] P4\n"), "{abc}");
}

#[test]
fn text_with_abc_special_characters_survives_xml_to_abc_to_xml() {
    // The ABC writer encodes `%` (comment), `\` (escape), `&` (entity) and a
    // quote inside quoted text per ABC 2.1 ยง8.2, so the re-parse decodes back
    // to the same characters.
    let xml = concat!(
        "<?xml version=\"1.0\"?>\n",
        "<score-partwise>\n",
        "  <work><work-title>50% off: A\\B &amp; C&amp;D \"live\"</work-title></work>\n",
        "  <part-list><score-part id=\"P1\"><part-name>T</part-name></score-part></part-list>\n",
        "  <part id=\"P1\">\n",
        "    <measure number=\"1\">\n",
        "      <attributes><divisions>4</divisions></attributes>\n",
        "      <direction placement=\"above\"><direction-type>",
        "<words>say \"Ouch\" 100%</words></direction-type></direction>\n",
        "      <note><pitch><step>C</step><octave>4</octave></pitch>",
        "<duration>4</duration><voice>1</voice><type>quarter</type>",
        "<lyric number=\"1\"><syllabic>single</syllabic><text>R&amp;B%</text></lyric></note>\n",
        "    </measure>\n",
        "  </part>\n",
        "</score-partwise>\n",
    );
    let mut score = read_musicxml(xml).value;
    crate::complete_score_for_abc(&mut score);
    let abc = crate::to_abc::write_abc(&score, crate::to_abc::AbcWriteOptions::default());
    let again = crate::export_musicxml(&abc).expect("re-export").musicxml;
    for expected in [
        "<work-title>50% off: A\\B &amp; C&amp;D &quot;live&quot;</work-title>",
        "say &quot;Ouch&quot; 100%",
        "<text>R&amp;B%</text>",
    ] {
        assert!(
            again.contains(expected),
            "missing {expected:?}\nABC:\n{abc}\nXML:\n{again}"
        );
    }
}