ossctl-core 0.4.0

Core library for ossctl: contract normalizer, repo-fact detection, audit scoring, release engine, and the versioned protocol DTOs.
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
//! Normalization pipeline: validate every field/enum/cross-field floor,
//! materialize all defaults, and expand `targets` from `ecosystems`.
//!
//! A faithful port of `check-oss-release.py`'s `normalize`. `contract show`
//! emits the canonical (normalized) form; `contract validate` runs the identical
//! pipeline and discards the document, emitting only pass/fail (ADR-0001 §1).
//!
//! Every field is validated independently and **all** problems are collected —
//! an invalid enum records an error *and* substitutes a default so the pass
//! continues to surface every other problem (mirroring the Python `Problems`
//! collector). The built [`Contract`] is only meaningful when
//! [`Normalized::is_valid`] holds; callers gate on that (or, in the CLI, on the
//! process exit code), never on parsing a document that failed.

use std::io;
use std::path::{Component, Path, PathBuf};

use serde_yaml::{Mapping, Value};

use crate::contract::schema::{
    Adapter, Changelog, ChangelogMode, ChangelogSource, Contract, ContributionProvenance,
    DependencyBot, Distribution, DistributionAdapter, DocsSite, Ecosystem, HealthBadge, Installer,
    Maturity, ProvenanceLevel, Registry, Release, ReleaseLayout, ReleaseModel, Status, Target,
    VersioningBase, DEFAULT_CROSS_PLATFORM_TARGETS, DEFAULT_FRAGMENT_DIR, KNOWN_SCHEMA_VERSION,
};
use crate::contract::spdx::spdx_valid;
use crate::ports::Fs;

/// The contract file the normalizer reads, relative to the repo root.
pub const CONTRACT_FILENAME: &str = "OSS-RELEASE.md";

/// Canonical ecosystem order — used to de-duplicate and stably order the
/// `ecosystems` list (mirrors the Python `VALID_ECOSYSTEMS` ordered list).
const ECOSYSTEM_ORDER: [Ecosystem; 5] = [
    Ecosystem::Rust,
    Ecosystem::Node,
    Ecosystem::Python,
    Ecosystem::Go,
    Ecosystem::Binary,
];

/// Known top-level frontmatter keys; anything else is preserved under
/// [`Contract::extra_fields`] (forward-compat).
///
/// **Invariant:** this list MUST stay in sync with the [`Contract`] struct
/// fields — every parsed field has its source key here. A field added to
/// [`Contract`] without its key here would be captured as an "unknown" field on
/// input; the `all_known_keys_*` tests guard against that drift.
///
/// The two trailing entries — `extra_fields` and `warnings` — are the canonical
/// *output* metadata keys, reserved here so canonical JSON (which carries them)
/// re-fed to the normalizer as YAML does NOT re-capture them into a nested
/// `extra_fields.extra_fields` on each pass. They are handled asymmetrically:
/// `extra_fields`'s mapping contents are merged back into the captured map (see
/// [`capture_unknown_fields`]) so the block round-trips losslessly; `warnings` is
/// derived diagnostic output, regenerated every pass, so any input value under it
/// is intentionally ignored (not preserved — it is not user contract data).
const KNOWN_KEYS: &[&str] = &[
    "schema_version",
    "status",
    "maturity",
    "ecosystems",
    "targets",
    // Both distribution input keys are known: `distribution` (a single mapping,
    // v1 back-compat) and `distributions` (a sequence, the monorepo shape). See
    // [`parse_distributions`]; declaring both is an error, not an unknown-field.
    "distribution",
    "distributions",
    "versioning",
    "changelog",
    "conventional_commits",
    "release",
    "contribution_provenance",
    "provenance_level",
    "dependency_bot",
    "health_badges",
    "license",
    "docs_site",
    // Reserved canonical-output metadata keys (not parsed) — see doc above.
    "extra_fields",
    "warnings",
];

/// Collected fatal errors and non-fatal warnings from a normalization pass.
#[derive(Debug, Default)]
pub struct Problems {
    /// Fatal validation errors; a non-empty list means the config would not
    /// normalize (the CLI exits non-zero with the §10 error envelope).
    pub errors: Vec<String>,
    /// Non-fatal notes (aspirational draft producers, the unknown-field report).
    pub warnings: Vec<String>,
}

impl Problems {
    fn err(&mut self, msg: String) {
        self.errors.push(msg);
    }

    fn warn(&mut self, msg: String) {
        self.warnings.push(msg);
    }
}

/// The result of a normalization pass: the canonical [`Contract`] plus the
/// [`Problems`] gathered while building it.
#[derive(Debug)]
pub struct Normalized {
    /// The canonical contract. Only meaningful when [`Self::is_valid`] holds.
    pub contract: Contract,
    /// Errors and warnings gathered during normalization.
    pub problems: Problems,
}

impl Normalized {
    /// Whether the config normalized cleanly (no fatal errors).
    #[must_use]
    pub fn is_valid(&self) -> bool {
        self.problems.errors.is_empty()
    }
}

/// Why the contract file could not be loaded (distinct from a *validation*
/// failure, which is carried by [`Problems`]). Maps to a §2 exit-2 system error.
#[derive(Debug)]
pub enum LoadError {
    /// No `OSS-RELEASE.md` at the expected path.
    NotFound(PathBuf),
    /// The file exists but could not be read.
    Io(PathBuf, io::Error),
    /// The file is not valid UTF-8.
    Utf8(PathBuf),
}

impl std::fmt::Display for LoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotFound(p) => write!(
                f,
                "no {CONTRACT_FILENAME} at {} (run /oss-init to generate one)",
                p.display()
            ),
            Self::Io(p, e) => write!(f, "cannot read {}: {e}", p.display()),
            Self::Utf8(p) => write!(f, "{} is not valid UTF-8", p.display()),
        }
    }
}

/// Read `<repo_root>/OSS-RELEASE.md` through the [`Fs`] port and normalize it.
///
/// # Errors
/// Returns [`LoadError`] when the file is missing, unreadable, or not UTF-8. A
/// *validation* failure is not an error here — it is carried in the returned
/// [`Normalized::problems`]; check [`Normalized::is_valid`].
pub fn normalize(repo_root: &Path, fs: &dyn Fs) -> Result<Normalized, LoadError> {
    let path = repo_root.join(CONTRACT_FILENAME);
    let bytes = fs.read(&path).map_err(|e| match e.kind() {
        io::ErrorKind::NotFound => LoadError::NotFound(path.clone()),
        _ => LoadError::Io(path.clone(), e),
    })?;
    let text = String::from_utf8(bytes).map_err(|_| LoadError::Utf8(path.clone()))?;
    Ok(normalize_str(&text, repo_root, fs))
}

/// Normalize the full text of an `OSS-RELEASE.md` (frontmatter + body).
///
/// Split from [`normalize`] so tests can exercise the pipeline on a string
/// without a real file. `repo_root` and `fs` are still needed for the
/// filesystem-dependent floors (the fragment-dir path floor and its advisory
/// existence check).
#[must_use]
pub fn normalize_str(text: &str, repo_root: &Path, fs: &dyn Fs) -> Normalized {
    let mut p = Problems::default();
    let map = match split_frontmatter(text, &mut p) {
        Some(fm) => parse_frontmatter(&fm, &mut p),
        None => Mapping::new(),
    };
    let contract = build(&map, &mut p, repo_root, fs);
    Normalized {
        contract,
        problems: p,
    }
}

/// Read a required enum field, or record an error and fall back to `default`.
/// Absent → `default` silently; present-but-invalid → error + `default`
/// (matching the Python default-substitution behavior).
macro_rules! enum_field {
    ($map:expr, $key:expr, $ty:ty, $default:expr, $p:expr) => {{
        match $map.get($key) {
            None => $default,
            Some(v) => match v.as_str().and_then(<$ty>::parse) {
                Some(x) => x,
                None => {
                    $p.err(format!(
                        "{} {} invalid — must be one of {:?}",
                        $key,
                        yaml_display(v),
                        <$ty>::VALID
                    ));
                    $default
                }
            },
        }
    }};
}

#[allow(clippy::too_many_lines)]
fn build(map: &Mapping, p: &mut Problems, repo_root: &Path, fs: &dyn Fs) -> Contract {
    // schema_version — validate the DECLARED version (a too-new config is a hard
    // stop, a sub-1 or non-integer is an error), but do NOT echo it: the canonical
    // output is ALWAYS the current shape, so the emitted `schema_version` is
    // KNOWN_SCHEMA_VERSION regardless of what the (older, still-readable) document
    // declared. Echoing the declared version would stamp a canonical v2 body with a
    // v1 number — a mislabeled, self-inconsistent shape a strict consumer cannot
    // trust. The tool reads a v1 `distribution:` mapping and emits the v2
    // `distributions: [...]` shape under `schema_version: 2`.
    match map.get("schema_version") {
        None => {}
        Some(v) => match v.as_i64() {
            Some(n) if n > i64::from(KNOWN_SCHEMA_VERSION) => p.err(format!(
                "schema_version {n} exceeds what this tool knows ({KNOWN_SCHEMA_VERSION}); \
                 upgrade the OSS-release skills before reading this config (refusing rather \
                 than guessing)."
            )),
            Some(n) if n < 1 => p.err(format!("schema_version {n} is invalid (must be >= 1)")),
            Some(_) => {}
            None => p.err(format!(
                "schema_version must be an integer, got {}",
                yaml_display(v)
            )),
        },
    }
    let schema_version = KNOWN_SCHEMA_VERSION;

    let status = enum_field!(map, "status", Status, Status::Draft, p);

    // maturity — required (inference is /oss-init's job, not the normalizer's).
    let maturity = match map.get("maturity") {
        None => {
            p.err("maturity is required (spike|mvp|production) — /oss-init infers it".to_string());
            Maturity::Mvp
        }
        Some(v) => {
            if let Some(m) = v.as_str().and_then(Maturity::parse) {
                m
            } else {
                p.err(format!(
                    "maturity {} invalid — must be one of {:?}",
                    yaml_display(v),
                    Maturity::VALID
                ));
                Maturity::Mvp
            }
        }
    };

    // ecosystems — validate, then de-dup into canonical order.
    let mut parsed_ecos: Vec<Ecosystem> = Vec::new();
    for item in as_list(map.get("ecosystems")) {
        match item.as_str().and_then(Ecosystem::parse) {
            Some(e) => parsed_ecos.push(e),
            None => p.err(format!(
                "ecosystems: {} invalid — must be one of {:?}",
                yaml_display(&item),
                Ecosystem::VALID
            )),
        }
    }
    let ecosystems: Vec<Ecosystem> = ECOSYSTEM_ORDER
        .into_iter()
        .filter(|e| parsed_ecos.contains(e))
        .collect();

    // versioning — split the base enum from the calver pattern.
    let (versioning, versioning_pattern) = parse_versioning(map.get("versioning"), p);

    // release (model + layout).
    let (model, layout) = match map.get("release") {
        None | Some(Value::Null) => (ReleaseModel::Gated, ReleaseLayout::Single),
        Some(Value::Mapping(m)) => (
            enum_field!(m, "model", ReleaseModel, ReleaseModel::Gated, p),
            enum_field!(m, "layout", ReleaseLayout, ReleaseLayout::Single, p),
        ),
        Some(_) => {
            p.err("release must be a mapping with model/layout".to_string());
            (ReleaseModel::Gated, ReleaseLayout::Single)
        }
    };

    // targets — expand from ecosystems when the key is OMITTED; but an explicit
    // empty list is the author's authoritative "never publish anywhere" and is
    // honored as-is (not re-expanded). Distinguishing *absent* from *explicit
    // empty* is the whole point: a version-tracked/changelogged repo with no
    // registry publish (a private service deployed by its own script) must be
    // expressible. An empty target set is a valid, honored state — every floor
    // and downstream consumer already treats "no targets" gracefully (no
    // registry-license floor, no `registry` health badge, "nothing to publish"
    // in the release engine).
    let targets = match map.get("targets") {
        None | Some(Value::Null) => expand_targets(&ecosystems, layout),
        Some(Value::Sequence(seq)) if seq.is_empty() => Vec::new(),
        Some(Value::Sequence(seq)) => validate_targets(seq, &ecosystems, layout, p),
        Some(_) => {
            p.err(
                "targets must be a list of {ecosystem, package?, registry, adapter?} maps"
                    .to_string(),
            );
            Vec::new()
        }
    };

    // distributions — the binary-distribution blocks (cargo-dist/goreleaser); a
    // registry-only repo has none (→ empty list), leaving its contract shape
    // unchanged. The homebrew cross-field truth table (tap ↔ installer-producer ↔
    // target-producer) is enforced afterwards by [`check_homebrew_configuration`],
    // once both `targets` and `distributions` are resolved.
    let distributions = parse_distributions(map, &targets, schema_version, p);

    // changelog (mode + source + fragment_dir).
    let changelog = match map.get("changelog") {
        None | Some(Value::Null) => Changelog {
            mode: ChangelogMode::Curated,
            source: ChangelogSource::Manual,
            fragment_dir: DEFAULT_FRAGMENT_DIR.to_string(),
        },
        Some(Value::Mapping(m)) => {
            let mode = enum_field!(m, "mode", ChangelogMode, ChangelogMode::Curated, p);
            let source = enum_field!(m, "source", ChangelogSource, ChangelogSource::Manual, p);
            let fragment_dir = match m.get("fragment_dir") {
                None => DEFAULT_FRAGMENT_DIR.to_string(),
                Some(v) => {
                    if let Some(s) = v.as_str() {
                        s.to_string()
                    } else {
                        p.err("changelog.fragment_dir must be a string path".to_string());
                        DEFAULT_FRAGMENT_DIR.to_string()
                    }
                }
            };
            Changelog {
                mode,
                source,
                fragment_dir,
            }
        }
        Some(_) => {
            p.err("changelog must be a mapping with mode/source".to_string());
            Changelog {
                mode: ChangelogMode::Curated,
                source: ChangelogSource::Manual,
                fragment_dir: DEFAULT_FRAGMENT_DIR.to_string(),
            }
        }
    };
    // fragment_dir must be a relative path inside the repo (floor 6).
    if !path_inside_repo(&changelog.fragment_dir) {
        p.err(format!(
            "floor: changelog.fragment_dir {} must be a relative path inside the repo (an \
             absolute or '../'-escaping path is refused)",
            quote_for_diagnostic(&changelog.fragment_dir)
        ));
    }

    // conventional_commits.
    let conventional_commits = match map.get("conventional_commits") {
        None => false,
        Some(Value::Bool(b)) => *b,
        Some(v) => {
            p.err(format!(
                "conventional_commits must be true|false, got {}",
                yaml_display(v)
            ));
            false
        }
    };

    let contribution_provenance = enum_field!(
        map,
        "contribution_provenance",
        ContributionProvenance,
        ContributionProvenance::None,
        p
    );
    let provenance_level = enum_field!(
        map,
        "provenance_level",
        ProvenanceLevel,
        ProvenanceLevel::None,
        p
    );

    let dep_default = if maturity == Maturity::Spike {
        DependencyBot::None
    } else {
        DependencyBot::Dependabot
    };
    let dependency_bot = enum_field!(map, "dependency_bot", DependencyBot, dep_default, p);

    // license — a valid SPDX expression when set (default MIT).
    let license = match map.get("license") {
        None => "MIT".to_string(),
        Some(v) => match v.as_str() {
            Some(s) if !s.trim().is_empty() => {
                if !spdx_valid(s) {
                    p.err(format!(
                        "license {} is not a valid SPDX expression (unknown id or malformed \
                         AND/OR/WITH grammar)",
                        quote_for_diagnostic(s)
                    ));
                }
                s.to_string()
            }
            _ => {
                p.err("license must be a non-empty SPDX id/expression (default MIT)".to_string());
                "MIT".to_string()
            }
        },
    };

    let docs_site = enum_field!(map, "docs_site", DocsSite, DocsSite::None, p);

    // health_badges — validate when present (key-presence, per Python), else
    // materialize a floor-clean default (maturity/target aware).
    let health_badges = if map.contains_key("health_badges") {
        let mut out = Vec::new();
        for item in as_list(map.get("health_badges")) {
            match item.as_str().and_then(HealthBadge::parse) {
                Some(hb) => out.push(hb),
                None => p.err(format!(
                    "health_badges: {} invalid — must be one of {:?}",
                    yaml_display(&item),
                    HealthBadge::VALID
                )),
            }
        }
        out
    } else {
        default_health_badges(maturity, &targets)
    };

    // ── Cross-field floors (§2) — config-internal, ALWAYS hard errors ────────
    if model == ReleaseModel::Auto && maturity == Maturity::Spike {
        p.err(
            "floor: release.model 'auto' is not allowed on maturity 'spike' — a spike is not \
             being published; raise maturity or set release.model: gated"
                .to_string(),
        );
    }
    if provenance_level == ProvenanceLevel::SlsaL3 && maturity != Maturity::Production {
        p.err(format!(
            "floor: provenance_level 'slsa-l3' is production-only — current maturity is '{}'",
            maturity.as_str()
        ));
    }
    // A target with a registry requires a valid SPDX license. Every expanded
    // target carries a registry, so "any registry" reduces to "any target".
    if !targets.is_empty() && !spdx_valid(&license) {
        p.err(format!(
            "floor: a target has a registry (crates.io/npm/PyPI/… require a license) but license \
             {} is not a valid SPDX expression",
            quote_for_diagnostic(&license)
        ));
    }
    check_badge_producers(&health_badges, maturity, &targets, p);
    // Homebrew cross-field consistency: missing-tap (either producer), the
    // double-publish collision, and the dead-tap advisory — the full truth table.
    check_homebrew_configuration(&targets, &distributions, p);
    // A distribution block ships public binaries (GH-Release artifacts, a curl-pipe
    // installer, a Homebrew tap PR) — that is publishing, and a spike is not being
    // published. Mirrors the `release.model: auto` floor: raise maturity or drop the
    // block. (No blocks → no constraint; registry-only spikes are unaffected.)
    if !distributions.is_empty() && maturity == Maturity::Spike {
        p.err(
            "floor: a distribution block ships public binaries (installer + tap) — not allowed on \
             maturity 'spike' (a spike is not being published); raise maturity or drop distribution"
                .to_string(),
        );
    }

    // ── Filesystem/producer-existence semantic check — ADVISORY, never fatal ─
    if changelog.mode == ChangelogMode::Fragment
        && path_inside_repo(&changelog.fragment_dir)
        && !fs.is_dir(&repo_root.join(&changelog.fragment_dir))
    {
        p.warn(format!(
            "changelog.mode 'fragment' but the fragment dir {} does not exist yet under {}\
             /oss-changelog creates it; /oss-readiness reports it as a gap until then",
            quote_for_diagnostic(&changelog.fragment_dir),
            repo_root.display()
        ));
    }

    // ── Forward-compat: preserve unknown fields, report once ─────────────────
    let extra_fields =
        capture_unknown_fields(map, KNOWN_KEYS, CaptureScope::TopLevel, schema_version, p);

    let warnings = p.warnings.clone();
    Contract {
        schema_version,
        status,
        maturity,
        ecosystems,
        targets,
        distributions,
        versioning,
        versioning_pattern,
        changelog,
        conventional_commits,
        release: Release { model, layout },
        contribution_provenance,
        provenance_level,
        dependency_bot,
        health_badges,
        license,
        docs_site,
        extra_fields,
        warnings,
    }
}

fn parse_versioning(value: Option<&Value>, p: &mut Problems) -> (VersioningBase, Option<String>) {
    let Some(v) = value else {
        return (VersioningBase::Semver, None);
    };
    let Some(s) = v.as_str() else {
        p.err(format!(
            "versioning {} invalid — must be semver | calver:<pattern> | zerover",
            yaml_display(v)
        ));
        return (VersioningBase::Semver, None);
    };
    if let Some(rest) = s.strip_prefix("calver:") {
        let pattern = rest.trim();
        if pattern.is_empty() {
            p.err(
                "versioning 'calver:' carries no pattern — e.g. calver:YYYY.MM.MICRO".to_string(),
            );
        }
        (VersioningBase::Calver, Some(pattern.to_string()))
    } else if s == "calver" {
        p.err(
            "versioning 'calver' must carry its pattern (calver:YYYY.MM.MICRO), not a bare label"
                .to_string(),
        );
        (VersioningBase::Calver, None)
    } else if let Some(base) = VersioningBase::parse(s) {
        (base, None)
    } else {
        p.err(format!(
            "versioning {} invalid — must be semver | calver:<pattern> | zerover",
            quote_for_diagnostic(s)
        ));
        (VersioningBase::Semver, None)
    }
}

/// Derive one target per ecosystem with default registry + adapter.
fn expand_targets(ecosystems: &[Ecosystem], layout: ReleaseLayout) -> Vec<Target> {
    ecosystems
        .iter()
        .map(|&e| Target {
            ecosystem: e,
            package: None,
            registry: e.default_registry(),
            adapter: e.default_adapter(layout),
        })
        .collect()
}

fn validate_targets(
    seq: &[Value],
    ecosystems: &[Ecosystem],
    layout: ReleaseLayout,
    p: &mut Problems,
) -> Vec<Target> {
    let mut out = Vec::new();
    for (idx, item) in seq.iter().enumerate() {
        let Value::Mapping(m) = item else {
            p.err(format!(
                "targets[{idx}] must be a map with at least {{ecosystem, registry}}"
            ));
            continue;
        };

        let ecosystem = if let Some(s) = m.get("ecosystem").and_then(Value::as_str) {
            if let Some(e) = Ecosystem::parse(s) {
                if !ecosystems.is_empty() && !ecosystems.contains(&e) {
                    p.err(format!(
                        "targets[{idx}].ecosystem {} is not in ecosystems {:?}",
                        quote_for_diagnostic(s),
                        ecosystems.iter().map(|e| e.as_str()).collect::<Vec<_>>()
                    ));
                }
                Some(e)
            } else {
                p.err(format!(
                    "targets[{idx}].ecosystem {} invalid — one of {:?}",
                    quote_for_diagnostic(s),
                    Ecosystem::VALID
                ));
                None
            }
        } else {
            p.err(format!(
                "targets[{idx}].ecosystem invalid — one of {:?}",
                Ecosystem::VALID
            ));
            None
        };

        let registry = match m.get("registry").and_then(Value::as_str) {
            None => {
                p.err(format!(
                    "targets[{idx}] has no registry (required — the publish destination)"
                ));
                None
            }
            Some(s) => {
                if let Some(r) = Registry::parse(s) {
                    Some(r)
                } else {
                    p.err(format!(
                        "targets[{idx}].registry {} invalid — one of {:?}",
                        quote_for_diagnostic(s),
                        Registry::VALID
                    ));
                    None
                }
            }
        };

        let adapter = match m.get("adapter") {
            None => ecosystem.map(|e| e.default_adapter(layout)),
            Some(v) => {
                if let Some(a) = v.as_str().and_then(Adapter::parse) {
                    Some(a)
                } else {
                    p.err(format!(
                        "targets[{idx}].adapter {} invalid — one of {:?}",
                        yaml_display(v),
                        Adapter::VALID
                    ));
                    None
                }
            }
        };

        // Floor: registry/adapter compatibility. A `homebrew`-registry target is
        // served only by a homebrew adapter — `homebrew-tap` (push a formula to a
        // personal tap) or `homebrew-core` (bump the central formula). Any other
        // adapter (e.g. the ecosystem default `cargo-publish`, or `manual`) has no
        // homebrew formula path, so the target would silently do nothing at cut
        // time. Reject it here rather than at release time. Only checked once both
        // are well-formed (a parse error already reported its own problem).
        if let (Some(Registry::Homebrew), Some(a)) = (registry, adapter) {
            if !matches!(a, Adapter::HomebrewTap | Adapter::HomebrewCore) {
                p.err(format!(
                    "floor: targets[{idx}] has registry 'homebrew' but adapter {} — a \
                     homebrew-registry target requires adapter 'homebrew-tap' (personal tap) \
                     or 'homebrew-core' (central formula)",
                    quote_for_diagnostic(a.as_str())
                ));
            }
        }

        // On the error path, placeholders keep the strong type; the document is
        // never emitted when problems.errors is non-empty.
        out.push(Target {
            ecosystem: ecosystem.unwrap_or(Ecosystem::Binary),
            package: m.get("package").and_then(Value::as_str).map(str::to_string),
            registry: registry.unwrap_or(Registry::GhReleases),
            adapter: adapter.unwrap_or(Adapter::Manual),
        });
    }
    out
}

/// Known `distribution`-block keys; anything else is preserved under
/// [`Distribution::extra_fields`] (forward-compat), the nested analogue of
/// [`KNOWN_KEYS`].
///
/// **Invariant:** this list MUST stay in sync with the [`Distribution`] struct
/// fields (see the [`KNOWN_KEYS`] note). The trailing `extra_fields` entry is the
/// reserved canonical-output metadata key — its contents are merged back rather
/// than nested (see [`capture_unknown_fields`]). A [`Distribution`] carries no
/// `warnings` (those live only at the top level), so only `extra_fields` needs
/// reserving here.
const KNOWN_DISTRIBUTION_KEYS: &[&str] = &[
    "package",
    "adapter",
    "gh_releases",
    "installers",
    "homebrew_tap",
    "platforms",
    // Reserved canonical-output metadata key (not parsed) — see doc above.
    "extra_fields",
];

/// Canonical installer order — used to de-duplicate and stably order the
/// `distribution.installers` list (mirrors [`ECOSYSTEM_ORDER`]'s role).
const INSTALLER_ORDER: [Installer; 5] = [
    Installer::Shell,
    Installer::Powershell,
    Installer::Homebrew,
    Installer::Msi,
    Installer::Npm,
];

/// Parse the optional distribution layer, accepting BOTH input spellings:
/// `distribution:` (a single mapping — v1 back-compat, the overwhelmingly common
/// case) and `distributions:` (a sequence of mappings — a monorepo shipping
/// several independently-distributed binaries). A registry-only repo declares
/// neither (or a bare/null key) and gets an empty list, leaving its contract
/// shape unchanged. Declaring BOTH keys at once is ambiguous and is an error.
///
/// Each element is parsed by [`parse_one_distribution`]; the collection-level
/// floor (a monorepo's `package` must be present and unique) lives here.
fn parse_distributions(
    map: &Mapping,
    targets: &[Target],
    schema_version: u32,
    p: &mut Problems,
) -> Vec<Distribution> {
    let single = map.get("distribution");
    let many = map.get("distributions");
    // Distinguish "absent" from "present-but-null": a bare `distribution:` /
    // `distributions:` (null value) reads as absent, exactly like the sibling keys.
    let single_present = matches!(single, Some(v) if !v.is_null());
    let many_present = matches!(many, Some(v) if !v.is_null());
    if single_present && many_present {
        p.err(
            "declare either `distribution` (one block) or `distributions` (a list), not both — \
             they are the singular and plural spellings of the same field"
                .to_string(),
        );
        // Fall through parsing the plural so the rest of the pass still surfaces
        // problems; the document is never emitted while `errors` is non-empty.
    }

    let distributions = match (single, many) {
        // `distributions:` — a sequence of mappings (the monorepo shape). Wins
        // over a stray singular key (already flagged above).
        (_, Some(Value::Sequence(seq))) => {
            let mut out = Vec::with_capacity(seq.len());
            for (idx, item) in seq.iter().enumerate() {
                match item {
                    Value::Mapping(m) => {
                        out.push(parse_one_distribution(m, schema_version, p));
                    }
                    _ => p.err(format!(
                        "distributions[{idx}] must be a mapping with {{package, adapter, \
                         gh_releases?, installers?, homebrew_tap?, platforms?}}"
                    )),
                }
            }
            out
        }
        (_, Some(v)) if !v.is_null() => {
            p.err(format!(
                "distributions must be a list of distribution mappings, got {}",
                yaml_display(v)
            ));
            Vec::new()
        }
        // `distribution:` — a single mapping (v1 back-compat) → a one-element list.
        (Some(Value::Mapping(m)), _) => {
            vec![parse_one_distribution(m, schema_version, p)]
        }
        (Some(v), _) if !v.is_null() => {
            p.err(
                "distribution must be a mapping with {adapter?, gh_releases?, installers?, \
                 homebrew_tap?, platforms?} (or use `distributions:` for a list)"
                    .to_string(),
            );
            Vec::new()
        }
        // Neither key (or both null) → a registry-only repo.
        _ => Vec::new(),
    };

    // Collection floor: a monorepo (≥2 distributions) must tag each entry with a
    // non-null, UNIQUE `package` — otherwise its distributions are
    // indistinguishable and the association is meaningless. A single distribution
    // may leave `package` null (the bare `distribution:` back-compat case).
    if distributions.len() >= 2 {
        let mut seen: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
        for (idx, d) in distributions.iter().enumerate() {
            match d.package.as_deref() {
                None => p.err(format!(
                    "floor: distributions[{idx}] has no `package` — with two or more \
                     distributions each must name the package it builds (the monorepo \
                     association key), so they can be told apart"
                )),
                Some(pkg) if !seen.insert(pkg) => p.err(format!(
                    "floor: distributions[{idx}].package {} is used by more than one \
                     distribution — each distribution must name a distinct package",
                    quote_for_diagnostic(pkg)
                )),
                Some(_) => {}
            }
        }

        // Typo guard (advisory): once a monorepo names packages, a distribution
        // whose `package` matches NO `targets[].package` is very likely a typo — a
        // distribution should build a package the contract also tracks as a target.
        // A warning, not a floor: a binary-only package legitimately need not appear
        // in the registry `targets`, and `targets` may be empty (a version-tracked,
        // unpublished repo) — so it fires only when there ARE named target packages
        // to compare against.
        let target_pkgs: std::collections::BTreeSet<&str> = targets
            .iter()
            .filter_map(|t| t.package.as_deref())
            .collect();
        if !target_pkgs.is_empty() {
            for (idx, d) in distributions.iter().enumerate() {
                if let Some(pkg) = d.package.as_deref() {
                    if !target_pkgs.contains(pkg) {
                        p.warn(format!(
                            "distributions[{idx}].package {} matches no targets[].package \
                             ({target_pkgs:?}) — likely a typo; a distribution should build a \
                             package the contract also lists as a target",
                            quote_for_diagnostic(pkg)
                        ));
                    }
                }
            }
        }
    }

    distributions
}

/// Parse ONE distribution mapping (an element of `distributions`, or the sole
/// `distribution:` block) into a [`Distribution`]. On the error path it records
/// problems and returns a placeholder — the document is never emitted while
/// `problems.errors` is non-empty.
#[allow(clippy::too_many_lines)]
fn parse_one_distribution(m: &Mapping, schema_version: u32, p: &mut Problems) -> Distribution {
    // package — the monorepo association key. Optional (null for the sole/bare
    // distribution); the collection-level floor in `parse_distributions` requires
    // it once there are two or more distributions.
    let package = match m.get("package") {
        None | Some(Value::Null) => None,
        Some(v) => match v.as_str() {
            // Store the TRIMMED value: surrounding whitespace would otherwise make
            // `" alpha"` and `"alpha"` distinct to the uniqueness floor and to the
            // per-package association/audit keying, silently breaking both.
            Some(s) if !s.trim().is_empty() => Some(s.trim().to_string()),
            _ => {
                p.err(
                    "distribution.package must be a non-empty string (the package this \
                     distribution builds)"
                        .to_string(),
                );
                None
            }
        },
    };

    // adapter — required when the block is present. Which tool OWNS the existing
    // tag-triggered release workflow is not the normalizer's to guess (it renames
    // release semantics and picks a Rust-specific default); inference is
    // /oss-init's job, exactly as for `maturity`. A bare `distribution: {}` is
    // therefore an error, not a silent "cargo-dist owns this repo".
    let adapter = match m.get("adapter") {
        None => {
            p.err(
                "distribution.adapter is required when a distribution block is present \
                 (cargo-dist|goreleaser|manual) — /oss-init infers it"
                    .to_string(),
            );
            DistributionAdapter::CargoDist
        }
        Some(v) => {
            if let Some(a) = v.as_str().and_then(DistributionAdapter::parse) {
                a
            } else {
                p.err(format!(
                    "distribution.adapter {} invalid — must be one of {:?}",
                    yaml_display(v),
                    DistributionAdapter::VALID
                ));
                DistributionAdapter::CargoDist
            }
        }
    };

    let gh_releases = match m.get("gh_releases") {
        // cargo-dist/goreleaser attach per-platform binaries by default.
        None => true,
        Some(Value::Bool(b)) => *b,
        Some(v) => {
            p.err(format!(
                "distribution.gh_releases must be true|false, got {}",
                yaml_display(v)
            ));
            true
        }
    };

    // installers — validate each, then de-dup into canonical order.
    let mut parsed_installers: Vec<Installer> = Vec::new();
    for item in as_list(m.get("installers")) {
        match item.as_str().and_then(Installer::parse) {
            Some(i) => parsed_installers.push(i),
            None => p.err(format!(
                "distribution.installers: {} invalid — must be one of {:?}",
                yaml_display(&item),
                Installer::VALID
            )),
        }
    }
    let installers: Vec<Installer> = INSTALLER_ORDER
        .into_iter()
        .filter(|i| parsed_installers.contains(i))
        .collect();

    let homebrew_tap = match m.get("homebrew_tap") {
        None | Some(Value::Null) => None,
        Some(v) => match v.as_str() {
            Some(s) if is_tap_slug(s) => Some(s.to_string()),
            // An invalid slug substitutes `None` (not the bad value) so the
            // built `Distribution` never carries a malformed tap — matching the
            // "placeholders keep the strong type" error-path rule the rest of the
            // normalizer follows, and letting the homebrew-needs-tap floor below
            // still fire (a present-but-invalid tap is no tap).
            Some(s) => {
                p.err(format!(
                    "distribution.homebrew_tap {} invalid — must be an 'owner/repo' slug",
                    quote_for_diagnostic(s)
                ));
                None
            }
            None => {
                p.err("distribution.homebrew_tap must be an 'owner/repo' string".to_string());
                None
            }
        },
    };

    let wants_homebrew = installers.contains(&Installer::Homebrew);
    // Floor: a `homebrew` installer needs a tap to push the generated formula to.
    // This is a PER-BLOCK check — cargo-dist pushes the formula to the tap
    // configured in this same distribution, so the tap must live here, not in a
    // sibling distribution. (The target-side missing-tap floor, the double-publish
    // collision, and the dead-tap advisory are cross-field and aggregate over all
    // distributions + targets — they live in [`check_homebrew_configuration`].)
    if wants_homebrew && homebrew_tap.is_none() {
        p.err(
            "floor: distribution.installers includes 'homebrew' but no distribution.homebrew_tap \
             is set — the generated formula has nowhere to be pushed"
                .to_string(),
        );
    }

    // platforms — the binary target-triple set. Omitted/null → the cross-platform
    // default (macOS + Linux musl), so a distribution that doesn't specify
    // platforms covers Linux by default (the cross-platform install requirement).
    // An explicit list is validated per triple and de-duplicated, preserving the
    // author's order (like the sibling `targets` list — there is no canonical
    // triple ordering to impose). An explicit *empty* list is NOT the same as
    // omitted: it is a mistake, and silently defaulting it would surprise the
    // author with targets they never listed and erase the intent the downstream
    // cross-platform audit needs — so it is a hard error.
    let platforms = match m.get("platforms") {
        None | Some(Value::Null) => default_cross_platform_targets(),
        Some(Value::Sequence(seq)) if seq.is_empty() => {
            // Default fallback keeps error-collection going; the contract is never
            // emitted while `problems.errors` is non-empty.
            p.err(
                "distribution.platforms is an empty list — omit the key to accept the \
                 cross-platform default (macOS + Linux) or list explicit target-triples; a \
                 distribution with no platforms builds nothing"
                    .to_string(),
            );
            default_cross_platform_targets()
        }
        Some(Value::Sequence(seq)) => {
            let mut out: Vec<String> = Vec::new();
            for item in seq {
                match item.as_str() {
                    Some(s) if looks_like_target_triple(s) => {
                        let triple = s.to_string();
                        if !out.contains(&triple) {
                            out.push(triple);
                        }
                    }
                    Some(s) => p.err(format!(
                        "distribution.platforms: {} is not a well-formed target-triple \
                         (e.g. x86_64-unknown-linux-musl, aarch64-apple-darwin) — structural \
                         check only; the toolchain is the final authority on what builds",
                        quote_for_diagnostic(s)
                    )),
                    None => p.err(format!(
                        "distribution.platforms: {} invalid — each entry must be a \
                         target-triple string",
                        yaml_display(item)
                    )),
                }
            }
            out
        }
        Some(v) => {
            p.err(format!(
                "distribution.platforms must be a list of target-triple strings, got {}",
                yaml_display(v)
            ));
            default_cross_platform_targets()
        }
    };

    // Cross-check: an OS-specific installer whose target OS is absent from the
    // resolved `platforms` set is dead config — the generated installer points at
    // a binary the release never builds ("the installer has nothing to install").
    // A warning, not a floor (mirrors the `homebrew_tap`-without-consumer advisory
    // above): the contract is internally consistent, just wasteful. Only the
    // OS-specific installers constrain the set — see [`installer_os_need`] for the
    // full installer→OS table; npm/shell/powershell are not cross-checked.
    //
    // Gated on a clean parse: this is a cross-field semantic advisory, so it must
    // read only well-formed triples. A malformed triple (rejected above) that
    // happens to contain an OS keyword must neither satisfy nor spuriously fail
    // the coverage check — otherwise the warning would flip as the author fixes an
    // unrelated error. Errors already block emission, so gating here loses nothing.
    if p.errors.is_empty() {
        let has_windows = platforms.iter().any(|t| is_windows_triple(t));
        let has_macos = platforms.iter().any(|t| is_macos_triple(t));
        let has_linux = platforms.iter().any(|t| is_linux_triple(t));
        for &installer in &installers {
            let unmet = match installer_os_need(installer) {
                OsNeed::Unchecked => None,
                OsNeed::Windows => (!has_windows).then_some(
                    "distribution.installers includes 'msi' but the resolved \
                     distribution.platforms set has no Windows (*-windows-*) target — the MSI \
                     installer has nothing to install",
                ),
                // Homebrew serves macOS natively AND Linux via Linuxbrew, so a
                // single Linux triple satisfies it just as a darwin triple does;
                // the warning fires only when NEITHER is present (the issue's stated
                // intent when the darwin-vs-linux question is ambiguous).
                OsNeed::MacosOrLinux => (!has_macos && !has_linux).then_some(
                    "distribution.installers includes 'homebrew' but the resolved \
                     distribution.platforms set has no macOS (*-apple-darwin) or Linux \
                     (*-linux-*) target — the Homebrew formula has nothing to install",
                ),
            };
            if let Some(msg) = unmet {
                p.warn(msg.to_string());
            }
        }
    }

    // Forward-compat: preserve unknown distribution sub-keys (the nested analogue
    // of the top-level `extra_fields` scan), so an older reader round-trips a
    // newer contract's distribution keys rather than dropping them. Reported once,
    // scoped to the block via the `Distribution` scope, mirroring the top-level
    // unknown-field warning — the shared helper keeps the two from drifting.
    let extra_fields = capture_unknown_fields(
        m,
        KNOWN_DISTRIBUTION_KEYS,
        CaptureScope::Distribution,
        schema_version,
        p,
    );

    Distribution {
        package,
        adapter,
        gh_releases,
        installers,
        homebrew_tap,
        platforms,
        extra_fields,
    }
}

/// The cross-platform default `distribution.platforms` set as owned strings —
/// materialized when the block omits `platforms` (or gives an empty list). Always
/// contains at least one Linux triple (the cross-platform install requirement).
fn default_cross_platform_targets() -> Vec<String> {
    DEFAULT_CROSS_PLATFORM_TARGETS
        .iter()
        .map(|&s| s.to_string())
        .collect()
}

/// The OS coverage an installer needs from `distribution.platforms` to install
/// anything — the small installer→OS spec behind the installer↔platform
/// cross-check warning. Kept as one table (see [`installer_os_need`]) rather than
/// scattered conditionals so the mapping stays inspectable in one place.
enum OsNeed {
    /// Not cross-checked — this installer never constrains `platforms`.
    Unchecked,
    /// Needs at least one Windows triple.
    Windows,
    /// Needs at least one macOS OR Linux triple.
    MacosOrLinux,
}

/// The OS an installer's generated artifact can actually install onto — the spec
/// that lets the normalizer flag an installer whose target OS is absent from
/// `platforms`. Only `msi` and `homebrew` are OS-gated; the rest are deliberately
/// left `Unchecked` (a scoping choice, not a claim that they run everywhere):
///
/// | installer    | need              | rationale                                          |
/// |--------------|-------------------|----------------------------------------------------|
/// | `msi`        | Windows           | an `.msi` installs only on Windows                 |
/// | `homebrew`   | macOS **or** Linux| Homebrew serves macOS natively and Linux (Linuxbrew) |
/// | `shell`      | — (not checked)   | a POSIX script; only msi/homebrew are gated for now |
/// | `powershell` | — (not checked)   | Windows-oriented; only msi/homebrew are gated for now |
/// | `npm`        | — (not checked)   | published to a registry, not tied to one OS's artifact |
fn installer_os_need(i: Installer) -> OsNeed {
    match i {
        Installer::Msi => OsNeed::Windows,
        Installer::Homebrew => OsNeed::MacosOrLinux,
        Installer::Shell | Installer::Powershell | Installer::Npm => OsNeed::Unchecked,
    }
}

/// The OS ("system") component of a target-triple — the 3rd `-`-separated field
/// in the `<arch>-<vendor>-<os>[-<env>]` shape the shipped desktop triples use
/// (`x86_64-pc-windows-msvc`, `aarch64-apple-darwin`, `x86_64-unknown-linux-musl`).
/// `None` for a 2-component triple that names no vendor (`wasm32-wasip1`). Matching
/// the OS *positionally* (rather than "any component equals …") is what keeps
/// `aarch64-linux-android` out of the Linux bucket: its `linux` sits in the vendor
/// slot and the real OS component is `android`.
fn triple_os(s: &str) -> Option<&str> {
    s.split('-').nth(2)
}

/// Whether a target-triple targets Windows — OS component `windows` (covering
/// both `-windows-msvc` and `-windows-gnu`).
fn is_windows_triple(s: &str) -> bool {
    triple_os(s) == Some("windows")
}

/// Whether a target-triple targets macOS — OS component `darwin` (e.g.
/// `aarch64-apple-darwin`). Apple's non-macOS triples (`*-apple-ios`, `-tvos`, …)
/// carry a different OS component and are correctly excluded.
fn is_macos_triple(s: &str) -> bool {
    triple_os(s) == Some("darwin")
}

/// Whether a target-triple targets Linux — OS component `linux` (e.g.
/// `x86_64-unknown-linux-musl`), covering the Linuxbrew case for `homebrew`.
/// Android (`aarch64-linux-android`) has `android` as its OS component and does
/// not count.
fn is_linux_triple(s: &str) -> bool {
    triple_os(s) == Some("linux")
}

/// Whether `s` is a *structurally* plausible target-triple — 2–4 `-`-separated
/// components, each a non-empty run of `[a-z0-9_.]`. Deliberately LEXICAL, not
/// semantic: the real triple set is open and rustc-defined, so this is a
/// well-formedness gate, not a whitelist. It rejects what could never be a triple
/// (empty parts, uppercase, whitespace, punctuation, injection chars, wrong shape)
/// and accepts real triples including dotted arch names like
/// `thumbv8m.main-none-eabi` — but it also accepts structurally-valid nonsense like
/// `aa-bb`, because the toolchain is the final authority on whether a triple
/// actually builds. The OS component stays intact and inspectable so the
/// cross-platform `audit` can classify a set downstream.
fn looks_like_target_triple(s: &str) -> bool {
    let parts: Vec<&str> = s.split('-').collect();
    (2..=4).contains(&parts.len())
        && parts.iter().all(|part| {
            !part.is_empty()
                && part.bytes().all(|b| {
                    b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.')
                })
        })
}

/// Whether `s` is a plausible `owner/repo` tap slug — exactly one `/`, and each
/// part a non-empty run of the GitHub-name character set (ASCII alphanumeric plus
/// `-`, `_`, `.`), with `.`/`..` rejected. Lexical only — existence is not
/// checked. Deliberately strict: this value flows into `brew tap` and repo URLs
/// downstream, so arbitrary punctuation, whitespace, or path traversal
/// (`owner/..`) must not pass.
fn is_tap_slug(s: &str) -> bool {
    fn valid_part(part: &str) -> bool {
        !part.is_empty()
            && part != "."
            && part != ".."
            && part
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
    }
    match s.split_once('/') {
        Some((owner, repo)) => valid_part(owner) && valid_part(repo) && !repo.contains('/'),
        None => false,
    }
}

/// A floor-clean default badge set: `ci` at mvp+, `registry` when a publishable
/// target exists, `license` always.
fn default_health_badges(maturity: Maturity, targets: &[Target]) -> Vec<HealthBadge> {
    let mut badges = Vec::new();
    if matches!(maturity, Maturity::Mvp | Maturity::Production) {
        badges.push(HealthBadge::Ci);
    }
    if !targets.is_empty() {
        badges.push(HealthBadge::Registry);
    }
    badges.push(HealthBadge::License);
    badges
}

/// Every enabled badge must have its producer enabled (floor 4).
fn check_badge_producers(
    badges: &[HealthBadge],
    maturity: Maturity,
    targets: &[Target],
    p: &mut Problems,
) {
    let has_registry_target = !targets.is_empty();
    for b in badges {
        match b {
            HealthBadge::Ci if maturity == Maturity::Spike => p.err(
                "floor: health_badge 'ci' has no producer at maturity 'spike' (no CI until mvp) — \
                 drop it or raise maturity"
                    .to_string(),
            ),
            HealthBadge::Registry if !has_registry_target => p.err(
                "floor: health_badge 'registry' has no producer — no target has a registry to \
                 publish to"
                    .to_string(),
            ),
            HealthBadge::Coverage if maturity != Maturity::Production => p.err(format!(
                "floor: health_badge 'coverage' has no producer — the coverage gate is a \
                 production-tier /oss-ci output; current maturity is '{}'",
                maturity.as_str()
            )),
            HealthBadge::Scorecard if maturity != Maturity::Production => p.err(format!(
                "floor: health_badge 'scorecard' has no producer — the Scorecard action is a \
                 production-tier output; current maturity is '{}'",
                maturity.as_str()
            )),
            _ => {}
        }
    }
}

/// Cross-field Homebrew consistency — the full truth table over three aggregate
/// signals: a **tap** configured on any distribution, an installer-side formula
/// **producer** (a `homebrew` installer on any distribution — cargo-dist), and a
/// target-side formula **producer** (a `homebrew`-registry target whose adapter is
/// `homebrew-tap`, i.e. the release engine pushes a formula to the personal tap).
///
/// A `homebrew-core` target is deliberately NOT a tap-producer: it bumps the
/// central formula via a PR and needs no personal tap, so it neither requires a
/// `homebrew_tap` nor collides with the installer's tap push.
///
/// The floors (all hard errors, per the AI-first fail-fast contract):
/// - **missing-tap (target side):** a `homebrew-tap` target with no `homebrew_tap`
///   anywhere — the engine's `dist` phase has nowhere to push the formula. (The
///   installer side is floored per-block in [`parse_one_distribution`].)
/// - **double-publish:** a `homebrew` installer AND a `homebrew-tap` target both
///   generate + push a formula to the personal tap — a guaranteed collision.
///
/// Plus one **advisory** (warning, not a floor): a configured tap with no producer
/// of either kind is dead config — nothing ever writes to it.
///
/// **Why aggregate, not per-package (deliberate).** The three signals are OR-ed
/// across all distributions/targets rather than grouped by the monorepo `package`
/// key. This matches the release engine's actual homebrew model: a cut carries a
/// SINGLE tap (`ReleasePlan::homebrew_tap` is the first-found tap, see
/// `release::plan`), and the CLI's `ensure_single_distribution` rejects a
/// multi-distribution monorepo BEFORE it can be planned — a per-package multi-tap
/// monorepo is an explicit deferred follow-up, not a shape the engine can cut. For
/// everything the engine supports (≤1 distribution), aggregate == per-package, and
/// crucially the aggregate view is what lets a bare `package: null` distribution's
/// tap serve a named-package `homebrew-tap` target (ossctl's OWN contract shape) —
/// a strict `target.package == distribution.package` grouping would wrongly reject
/// it. Revisit this only alongside the engine's per-package-tap follow-up.
fn check_homebrew_configuration(
    targets: &[Target],
    distributions: &[Distribution],
    p: &mut Problems,
) {
    let has_tap = distributions.iter().any(|d| d.homebrew_tap.is_some());
    let installer_producer = distributions
        .iter()
        .any(|d| d.installers.contains(&Installer::Homebrew));
    // Narrowed to `homebrew-tap` (not merely `registry == homebrew`): only the tap
    // adapter pushes a formula to the personal tap. `validate_targets` already
    // floors any other adapter on a `homebrew` registry, so a `homebrew-core`
    // target is the only other well-formed case, and it is not a tap-producer.
    let tap_target_producer = targets
        .iter()
        .any(|t| t.registry == Registry::Homebrew && t.adapter == Adapter::HomebrewTap);

    // Floor: a homebrew-tap target needs a tap destination for its formula.
    if tap_target_producer && !has_tap {
        p.err(
            "floor: a 'homebrew'-registry target with adapter 'homebrew-tap' generates a formula \
             but no distribution sets homebrew_tap — the formula has nowhere to be pushed (set \
             distribution.homebrew_tap to the 'owner/repo' tap)"
                .to_string(),
        );
    }

    // Floor: the double-publish collision — two mechanisms push a formula to the
    // personal tap (cargo-dist's installer AND the engine's homebrew-tap adapter).
    if installer_producer && tap_target_producer {
        p.err(
            "floor: both a 'homebrew' installer (distribution.installers) and a 'homebrew'-registry \
             target with adapter 'homebrew-tap' generate + push a formula to the tap — they would \
             collide; keep exactly one homebrew formula producer, not both"
                .to_string(),
        );
    }

    // Advisory: a tap nobody writes to (no installer producer, no tap target).
    if has_tap && !installer_producer && !tap_target_producer {
        p.warn(
            "distribution.homebrew_tap is set but there is neither a 'homebrew' installer in \
             distribution.installers nor a 'homebrew'-registry target with adapter 'homebrew-tap' \
             — no formula is generated, so the tap will never be updated"
                .to_string(),
        );
    }
}

// ── Frontmatter extraction + parse ───────────────────────────────────────────

/// A `---` fence line (exactly three dashes plus optional trailing whitespace).
fn is_fence(line: &str) -> bool {
    let t = line.trim_end();
    t == "---" || (t.starts_with("---") && t[3..].chars().all(char::is_whitespace))
}

/// Split the YAML frontmatter block out of the document. Returns the frontmatter
/// text (body discarded — the normalizer never reads it), or `None` on a
/// structural error (recorded on `p`).
fn split_frontmatter(text: &str, p: &mut Problems) -> Option<String> {
    let mut lines = text.lines();
    match lines.next() {
        Some(first) if is_fence(first) => {}
        _ => {
            p.err("frontmatter missing: file must begin with a '---' YAML block".to_string());
            return None;
        }
    }
    let mut fm = String::new();
    for line in lines {
        if is_fence(line) {
            return Some(fm);
        }
        fm.push_str(line);
        fm.push('\n');
    }
    p.err("frontmatter not closed: no terminating '---' line found".to_string());
    None
}

/// Parse the frontmatter into a YAML mapping. `serde_yaml` rejects duplicate
/// keys natively; a non-mapping top level or any YAML error is recorded on `p`.
fn parse_frontmatter(fm: &str, p: &mut Problems) -> Mapping {
    if fm.trim().is_empty() {
        return Mapping::new();
    }
    match serde_yaml::from_str::<Value>(fm) {
        Ok(Value::Null) => Mapping::new(),
        Ok(Value::Mapping(m)) => m,
        Ok(_) => {
            p.err("frontmatter: top level must be a mapping".to_string());
            Mapping::new()
        }
        Err(e) => {
            p.err(format!("frontmatter: invalid YAML — {e}"));
            Mapping::new()
        }
    }
}

// ── Helpers ──────────────────────────────────────────────────────────────────

/// Coerce a value to a list: a sequence stays; absent/null → empty; a scalar
/// becomes a one-element list (mirrors the Python `_as_list`).
fn as_list(v: Option<&Value>) -> Vec<Value> {
    match v {
        None | Some(Value::Null) => Vec::new(),
        Some(Value::Sequence(seq)) => seq.clone(),
        Some(other) => vec![other.clone()],
    }
}

/// A compact display of a YAML scalar for error messages (strings are quoted).
fn yaml_display(v: &Value) -> String {
    match v {
        Value::String(s) => quote_for_diagnostic(s),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
        Value::Null => "null".to_string(),
        Value::Sequence(_) => "<list>".to_string(),
        Value::Mapping(_) => "<map>".to_string(),
        Value::Tagged(t) => yaml_display(&t.value),
    }
}

/// Quote a user-controlled string for safe embedding in a warning/error message.
///
/// Diagnostics interleave user-controlled text (unknown field keys, rejected enum
/// values, package/tap/path strings) into a single line that lands in the §10
/// error envelope and the JSONL log. Wrapping such a value in bare single quotes
/// (`'{s}'`) lets a value carrying a quote, newline, or control character forge a
/// second diagnostic line or corrupt the log — a log-injection vector. JSON string
/// encoding escapes `"`, `\`, newlines, and C0 control characters (and leaves
/// ordinary text readable), so `foo` renders as `"foo"` and a hostile
/// `a"\ninjected` renders as `"a\"\ninjected"` on one intact line. Infallible:
/// serializing a string to JSON never fails.
fn quote_for_diagnostic(s: &str) -> String {
    serde_json::Value::String(s.to_owned()).to_string()
}

/// Whether `rel` is a relative path that stays inside the repo — no absolute
/// path, no `../` escape — the fragment-dir floor. Lexical, so the path need not
/// exist. The check is purely on `rel`'s own component depth, so it holds
/// whether the repo root is absolute or relative (notably `--repo-root .`,
/// where `repo_root` normalizes to an empty path): a `..` is an escape the
/// moment it would pop above the repo root, exactly the Python
/// `_path_inside_repo` verdict (which rejects any `rel` that normalizes to an
/// escaping path). Joining `rel` onto a relative root and testing containment —
/// the previous approach — silently accepted `../etc` under a `.` root, because
/// an empty normalized root is a prefix of every path.
fn path_inside_repo(rel: &str) -> bool {
    let mut depth: usize = 0;
    for comp in Path::new(rel).components() {
        match comp {
            Component::CurDir => {}
            Component::Normal(_) => depth += 1,
            Component::ParentDir => {
                // An escape above the repo root the instant depth would go < 0.
                if depth == 0 {
                    return false;
                }
                depth -= 1;
            }
            // An absolute path (or a Windows drive prefix) never stays inside a
            // relative repo root.
            Component::RootDir | Component::Prefix(_) => return false,
        }
    }
    true
}

/// Which mapping the [`capture_unknown_fields`] scan is running over — scopes the
/// forward-compat warning text and error messages. An enum (rather than a bare
/// string prefix) so a new call site cannot silently pass a mis-spaced label and
/// produce `unknown distributionfield(s)`.
#[derive(Clone, Copy)]
enum CaptureScope {
    /// The top-level frontmatter mapping ([`KNOWN_KEYS`]).
    TopLevel,
    /// The nested `distribution` block ([`KNOWN_DISTRIBUTION_KEYS`]).
    Distribution,
}

impl CaptureScope {
    /// The infix woven into the warning/error text — `""` for the top level,
    /// `"distribution "` for the block — so a message reads `unknown field(s) …`
    /// vs `unknown distribution field(s) …`.
    fn label(self) -> &'static str {
        match self {
            Self::TopLevel => "",
            Self::Distribution => "distribution ",
        }
    }
}

/// Scan a YAML mapping for keys outside `known` and preserve them under a
/// forward-compat `extra_fields` map, warning once when any were captured. The
/// single implementation behind BOTH the top-level ([`KNOWN_KEYS`]) and nested
/// `distribution` ([`KNOWN_DISTRIBUTION_KEYS`]) scans, so the two cannot drift
/// (the nested warning once silently omitted `schema_version`).
///
/// The guarantee is that an unknown **string** key is never dropped, never
/// double-captured, and round-trips predictably:
/// - A string key not in `known` is captured verbatim.
/// - A known string key is skipped (parsed as its field, not double-captured).
/// - The reserved canonical-output key `extra_fields` (in `known`) is not
///   re-captured into a nested `extra_fields.extra_fields`; instead its mapping
///   contents are **merged back** into the returned map (see
///   [`merge_reserved_extra_fields`]) so a hand-authored — or, defensively, a
///   re-fed canonical — `extra_fields` block round-trips losslessly rather than
///   being silently dropped. A key present both in that block and as a sibling
///   unknown field is an ambiguity error, not a silent overwrite.
///
/// Non-string keys (`42:`, `true:`, a list/map key — legal YAML) are a **structural
/// error**, not silently coerced: they can never be a forward-compatible schema
/// field (canonical JSON object keys are strings), and coercing them through the
/// display formatter would collapse distinct keys onto the same string (`42` and
/// `"42"`; every list key onto `<list>`) and silently drop a value — the opposite
/// of the never-drop intent. Rejecting keeps the invariant vacuously (an invalid
/// contract's output is never consumed) and matches the normalizer's
/// error-collection style.
fn capture_unknown_fields(
    m: &Mapping,
    known: &[&str],
    scope: CaptureScope,
    schema_version: u32,
    p: &mut Problems,
) -> serde_json::Map<String, serde_json::Value> {
    let label = scope.label();
    let mut extra_fields = serde_json::Map::new();
    // Merge an explicit `extra_fields` block first (reserved metadata key), so a
    // sibling unknown key colliding with it is detected below rather than
    // silently overwriting it.
    if let Some(v) = m.get("extra_fields") {
        merge_reserved_extra_fields(v, scope, &mut extra_fields, p);
    }
    for (k, v) in m {
        match k {
            Value::String(key) => {
                if known.contains(&key.as_str()) {
                    continue;
                }
                if extra_fields.contains_key(key) {
                    p.err(format!(
                        "{label}field '{key}' appears both as an unknown top-level key and inside \
                         the reserved '{label}extra_fields' block — refusing to drop either value; \
                         remove one"
                    ));
                } else {
                    extra_fields.insert(key.clone(), yaml_to_json(v));
                }
            }
            other => p.err(format!(
                "{label}field key {} must be a string — a non-string key is not a \
                 forward-compatible schema shape and cannot be preserved losslessly (distinct \
                 non-string keys collapse onto the same JSON key)",
                yaml_display(other)
            )),
        }
    }
    if !extra_fields.is_empty() {
        // serde_json::Map is ordered (BTreeMap, no `preserve_order`) → keys already
        // sorted. Each key is a user-controlled map key, so JSON-encode it (rather
        // than bare single-quoting) to keep a hostile key from forging a diagnostic
        // line — see [`quote_for_diagnostic`].
        let keys = extra_fields
            .keys()
            .map(|k| quote_for_diagnostic(k))
            .collect::<Vec<_>>()
            .join(", ");
        p.warn(format!(
            "unknown {label}field(s) preserved under schema_version {schema_version} \
             (forward-compat): [{keys}]"
        ));
    }
    extra_fields
}

/// Merge the contents of a reserved `extra_fields` block (a hand-authored, or
/// defensively a re-fed canonical, mapping under the reserved `extra_fields` key)
/// into `out`, upholding the never-drop invariant for that block rather than
/// silently discarding it now that the key is reserved in `known`. A non-mapping
/// value, or a non-string key inside it, is a structural error (same rationale as
/// the sibling scan in [`capture_unknown_fields`]). Sibling-key collisions are
/// detected back in the caller, after this has seeded `out`.
fn merge_reserved_extra_fields(
    v: &Value,
    scope: CaptureScope,
    out: &mut serde_json::Map<String, serde_json::Value>,
    p: &mut Problems,
) {
    let label = scope.label();
    match v {
        Value::Null => {}
        Value::Mapping(inner) => {
            for (k, val) in inner {
                match k {
                    Value::String(key) => {
                        out.insert(key.clone(), yaml_to_json(val));
                    }
                    other => p.err(format!(
                        "reserved '{label}extra_fields' block has a non-string key {} — its keys \
                         must be strings",
                        yaml_display(other)
                    )),
                }
            }
        }
        other => p.err(format!(
            "reserved '{label}extra_fields' must be a mapping when present, got {}",
            yaml_display(other)
        )),
    }
}

/// Convert an arbitrary YAML value to JSON, for `extra_fields` preservation.
fn yaml_to_json(v: &Value) -> serde_json::Value {
    use serde_json::Value as J;
    match v {
        Value::Null => J::Null,
        Value::Bool(b) => J::Bool(*b),
        Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                J::from(i)
            } else if let Some(u) = n.as_u64() {
                J::from(u)
            } else if let Some(f) = n.as_f64() {
                serde_json::Number::from_f64(f).map_or(J::Null, J::Number)
            } else {
                J::Null
            }
        }
        Value::String(s) => J::String(s.clone()),
        Value::Sequence(seq) => J::Array(seq.iter().map(yaml_to_json).collect()),
        Value::Mapping(m) => {
            let mut obj = serde_json::Map::new();
            for (k, val) in m {
                let key = match k {
                    Value::String(s) => s.clone(),
                    other => yaml_display(other),
                };
                obj.insert(key, yaml_to_json(val));
            }
            J::Object(obj)
        }
        Value::Tagged(t) => yaml_to_json(&t.value),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;

    /// A fake `Fs`: `normalize_str` never `read`s, so only the directory set
    /// matters (for the fragment-dir advisory check).
    struct FakeFs {
        dirs: HashSet<PathBuf>,
    }

    impl FakeFs {
        fn empty() -> Self {
            Self {
                dirs: HashSet::new(),
            }
        }

        fn with_dirs<const N: usize>(dirs: [&str; N]) -> Self {
            Self {
                dirs: dirs.iter().map(PathBuf::from).collect(),
            }
        }
    }

    impl Fs for FakeFs {
        fn read(&self, _path: &Path) -> io::Result<Vec<u8>> {
            Err(io::Error::from(io::ErrorKind::NotFound))
        }
        fn exists(&self, path: &Path) -> bool {
            self.dirs.contains(path)
        }
        fn is_dir(&self, path: &Path) -> bool {
            self.dirs.contains(path)
        }
        fn is_file(&self, _path: &Path) -> bool {
            // The contract normalizer models only directories (fragment-dir).
            false
        }
        fn read_dir(&self, _dir: &Path) -> io::Result<Vec<String>> {
            // The contract normalizer never lists directories.
            Ok(Vec::new())
        }
    }

    fn repo() -> &'static Path {
        Path::new("/repo")
    }

    fn norm(text: &str) -> Normalized {
        normalize_str(text, repo(), &FakeFs::empty())
    }

    fn norm_with(text: &str, fs: &dyn Fs) -> Normalized {
        normalize_str(text, repo(), fs)
    }

    fn assert_error_contains(n: &Normalized, needle: &str) {
        assert!(
            !n.is_valid(),
            "expected invalid, got clean normalize: {:?}",
            n.contract
        );
        assert!(
            n.problems.errors.iter().any(|e| e.contains(needle)),
            "no error contained {needle:?}; errors were {:?}",
            n.problems.errors
        );
    }

    const MINIMAL: &str = "---\nstatus: approved\nmaturity: mvp\n---\n";

    #[test]
    fn materializes_all_defaults() {
        let c = norm(MINIMAL).contract;
        // Pinned to the literal (not KNOWN_SCHEMA_VERSION) so a future bump is an
        // explicit, visible test change rather than silently tracking the constant.
        assert_eq!(c.schema_version, 2);
        assert_eq!(c.status, Status::Approved);
        assert_eq!(c.maturity, Maturity::Mvp);
        assert!(c.ecosystems.is_empty());
        assert!(c.targets.is_empty());
        assert_eq!(c.versioning, VersioningBase::Semver);
        assert_eq!(c.versioning_pattern, None);
        assert_eq!(c.changelog.mode, ChangelogMode::Curated);
        assert_eq!(c.changelog.source, ChangelogSource::Manual);
        assert_eq!(c.changelog.fragment_dir, DEFAULT_FRAGMENT_DIR);
        assert!(!c.conventional_commits);
        assert_eq!(c.release.model, ReleaseModel::Gated);
        assert_eq!(c.release.layout, ReleaseLayout::Single);
        assert_eq!(c.contribution_provenance, ContributionProvenance::None);
        assert_eq!(c.provenance_level, ProvenanceLevel::None);
        assert_eq!(c.dependency_bot, DependencyBot::Dependabot); // mvp default
        assert_eq!(c.license, "MIT");
        assert_eq!(c.docs_site, DocsSite::None);
        // mvp, no publishable target → [ci, license].
        assert_eq!(c.health_badges, vec![HealthBadge::Ci, HealthBadge::License]);
        assert!(c.extra_fields.is_empty());
    }

    #[test]
    fn spike_defaults_no_bot_no_ci_badge() {
        let c = norm("---\nstatus: approved\nmaturity: spike\n---\n").contract;
        assert_eq!(c.dependency_bot, DependencyBot::None);
        assert_eq!(c.health_badges, vec![HealthBadge::License]);
    }

    #[test]
    fn maturity_is_required() {
        assert_error_contains(
            &norm("---\nstatus: approved\n---\n"),
            "maturity is required",
        );
    }

    #[test]
    fn expands_targets_from_ecosystems() {
        let c = norm("---\nstatus: approved\nmaturity: mvp\necosystems: [python]\n---\n").contract;
        assert_eq!(c.targets.len(), 1);
        assert_eq!(c.targets[0].ecosystem, Ecosystem::Python);
        assert_eq!(c.targets[0].package, None);
        assert_eq!(c.targets[0].registry, Registry::Pypi);
        assert_eq!(c.targets[0].adapter, Adapter::GhActionPypiPublish);
    }

    /// Option B (publish-target-none): an explicit empty `targets: []` is the
    /// author's authoritative "never publish" and is honored as an empty set —
    /// NOT re-expanded into the ecosystem default. This is the whole fix: a
    /// version-tracked repo with a registry ecosystem but no publish must be
    /// expressible.
    #[test]
    fn explicit_empty_targets_is_honored_not_expanded() {
        let n =
            norm("---\nstatus: approved\nmaturity: mvp\necosystems: [rust]\ntargets: []\n---\n");
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        let c = n.contract;
        // The rust ecosystem is still recorded …
        assert_eq!(c.ecosystems, vec![Ecosystem::Rust]);
        // … but NO crates.io target is force-expanded: the empty set is honored.
        assert!(
            c.targets.is_empty(),
            "explicit targets:[] must stay empty, got {:?}",
            c.targets
        );
    }

    /// The counterpart to the above: OMITTING `targets` keeps the unchanged
    /// ecosystem-default expansion. Absent ≠ explicit-empty.
    #[test]
    fn omitted_targets_still_expands_to_ecosystem_default() {
        let c = norm("---\nstatus: approved\nmaturity: mvp\necosystems: [rust]\n---\n").contract;
        assert_eq!(c.targets.len(), 1);
        assert_eq!(c.targets[0].ecosystem, Ecosystem::Rust);
        assert_eq!(c.targets[0].registry, Registry::CratesIo);
        assert_eq!(c.targets[0].adapter, Adapter::CargoPublish);
    }

    /// A YAML `targets:` with a null value (not a list) is treated as *absent*,
    /// not as an explicit empty set — it still expands. Only a genuine empty
    /// sequence `[]` is the authoritative "never publish".
    #[test]
    fn null_targets_expands_like_omitted() {
        let c = norm("---\nstatus: approved\nmaturity: mvp\necosystems: [rust]\ntargets:\n---\n")
            .contract;
        assert_eq!(c.targets.len(), 1);
        assert_eq!(c.targets[0].registry, Registry::CratesIo);
    }

    /// An empty-targets contract round-trips through canonical JSON unchanged:
    /// `targets` serializes as an empty array `[]` (faithfully reporting the
    /// never-publish intent, not omitting or defaulting it), and re-feeding that
    /// canonical `targets` value back through the normalizer preserves the empty
    /// set — the intent survives a normalize→serialize→normalize cycle.
    #[test]
    fn empty_targets_round_trips_through_canonical_json() {
        let n =
            norm("---\nstatus: approved\nmaturity: mvp\necosystems: [rust]\ntargets: []\n---\n");
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        let json = serde_json::to_value(&n.contract).unwrap();
        // The canonical output faithfully reports the empty set as `[]`.
        assert_eq!(json["targets"], serde_json::json!([]));

        // Re-feed the canonical `targets` value as frontmatter; the empty set is
        // preserved (still no expansion), proving the round-trip is stable.
        let targets_yaml = serde_yaml::to_string(&json["targets"]).unwrap();
        let refed = format!(
            "---\nstatus: approved\nmaturity: mvp\necosystems: [rust]\ntargets: {}\n---\n",
            targets_yaml.trim()
        );
        let n2 = norm(&refed);
        assert!(n2.is_valid(), "errors: {:?}", n2.problems.errors);
        assert_eq!(n2.contract.targets, n.contract.targets);
        assert!(n2.contract.targets.is_empty());
    }

    /// Cross-field: an explicit empty `targets: []` skips the registry-license
    /// floor (no target → no registry that requires an SPDX license), while a
    /// genuinely invalid license is still caught by its OWN check. Locks in that
    /// the `!targets.is_empty()` gate on the floor keeps honoring an empty set.
    #[test]
    fn explicit_empty_targets_skips_registry_license_floor() {
        let n = norm(
            "---\nstatus: approved\nmaturity: mvp\necosystems: [rust]\ntargets: []\n\
             license: not-a-real-spdx-id\n---\n",
        );
        // The bad license is still invalid on its own …
        assert!(!n.is_valid());
        // … but the registry-requires-license FLOOR must NOT fire — there is no
        // registry target to trigger it.
        assert!(
            !n.problems
                .errors
                .iter()
                .any(|e| e.contains("floor: a target has a registry")),
            "registry-license floor fired despite empty targets: {:?}",
            n.problems.errors
        );
    }

    /// Cross-field: forcing a `registry` health badge while declaring `targets: []`
    /// is a floor error — the badge has no producer (no registry to publish to).
    /// The empty set is honored, and the badge/target consistency floor still
    /// guards against a badge with nothing behind it.
    #[test]
    fn registry_badge_with_explicit_empty_targets_fails() {
        let n = norm(
            "---\nstatus: approved\nmaturity: mvp\necosystems: [rust]\ntargets: []\n\
             health_badges: [registry, license]\n---\n",
        );
        assert_error_contains(&n, "health_badge 'registry' has no producer");
    }

    /// The expansion-skip is independent of the `ecosystems` list: an explicit
    /// `targets: []` with NO ecosystems is still an honored empty set (and, like
    /// the minimal contract, defaults its badges to [ci, license] — no registry
    /// badge without a target).
    #[test]
    fn explicit_empty_targets_with_no_ecosystems() {
        let n = norm("---\nstatus: approved\nmaturity: mvp\ntargets: []\n---\n");
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(n.contract.targets.is_empty());
        assert_eq!(
            n.contract.health_badges,
            vec![HealthBadge::Ci, HealthBadge::License]
        );
    }

    #[test]
    fn node_monorepo_adapter_is_changesets() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [node]\n\
                    release:\n  model: gated\n  layout: monorepo\n---\n";
        let c = norm(text).contract;
        assert_eq!(c.targets[0].adapter, Adapter::Changesets);
    }

    #[test]
    fn ecosystems_dedup_to_canonical_order() {
        let c =
            norm("---\nstatus: approved\nmaturity: mvp\necosystems: [python, rust, python]\n---\n")
                .contract;
        assert_eq!(c.ecosystems, vec![Ecosystem::Rust, Ecosystem::Python]);
    }

    #[test]
    fn calver_splits_base_and_pattern() {
        let c = norm(
            "---\nstatus: approved\nmaturity: mvp\nversioning: \"calver:YYYY.MM.MICRO\"\n---\n",
        )
        .contract;
        assert_eq!(c.versioning, VersioningBase::Calver);
        assert_eq!(c.versioning_pattern.as_deref(), Some("YYYY.MM.MICRO"));
    }

    #[test]
    fn bare_calver_is_rejected() {
        assert_error_contains(
            &norm("---\nstatus: approved\nmaturity: mvp\nversioning: calver\n---\n"),
            "must carry its pattern",
        );
    }

    #[test]
    fn floor_auto_on_spike() {
        let text = "---\nstatus: approved\nmaturity: spike\n\
                    release:\n  model: auto\n  layout: single\nhealth_badges: [license]\n---\n";
        assert_error_contains(&norm(text), "release.model 'auto' is not allowed");
    }

    #[test]
    fn floor_slsa_l3_production_only() {
        assert_error_contains(
            &norm("---\nstatus: approved\nmaturity: mvp\nprovenance_level: slsa-l3\n---\n"),
            "slsa-l3' is production-only",
        );
    }

    #[test]
    fn floor_registry_requires_valid_license() {
        let text = "---\nstatus: approved\nmaturity: mvp\necosystems: [rust]\n\
                    license: Proprietary-Acme\nhealth_badges: [ci, registry, license]\n---\n";
        let n = norm(text);
        // Both the SPDX-validity error and the registry-needs-license floor fire.
        assert_error_contains(&n, "not a valid SPDX expression");
        assert!(n
            .problems
            .errors
            .iter()
            .any(|e| e.contains("floor: a target has a registry")));
    }

    #[test]
    fn floor_badge_without_producer() {
        let text = "---\nstatus: approved\nmaturity: mvp\necosystems: [python]\n\
                    health_badges: [ci, coverage]\n---\n";
        assert_error_contains(&norm(text), "health_badge 'coverage' has no producer");
    }

    #[test]
    fn floor_schema_version_too_new() {
        assert_error_contains(
            &norm("---\nschema_version: 99\nstatus: approved\nmaturity: mvp\n---\n"),
            "exceeds what this tool knows",
        );
    }

    #[test]
    fn floor_fragment_dir_escape() {
        let text = "---\nstatus: approved\nmaturity: mvp\n\
                    changelog:\n  mode: fragment\n  source: manual\n  fragment_dir: /etc\n---\n";
        assert_error_contains(&norm(text), "must be a relative path inside the repo");
    }

    #[test]
    fn floor_fragment_dir_escape_relative_root() {
        // Regression: with a *relative* repo root (the CLI's `--repo-root .`),
        // a `../`-escaping fragment_dir must still be rejected. The earlier
        // join-then-contain check accepted it because a `.` root normalizes to
        // an empty path that prefixes everything.
        let text = "---\nstatus: approved\nmaturity: mvp\n\
                    changelog:\n  mode: fragment\n  source: manual\n  fragment_dir: ../etc\n---\n";
        let n = normalize_str(text, Path::new("."), &FakeFs::empty());
        assert_error_contains(&n, "must be a relative path inside the repo");
    }

    #[test]
    fn path_inside_repo_verdicts() {
        // Inside — plain and `.`/`..`-collapsing relative paths that stay in.
        assert!(path_inside_repo("changelog/fragments"));
        assert!(path_inside_repo("./changelog/fragments"));
        assert!(path_inside_repo("a/../fragments"));
        assert!(path_inside_repo("")); // the repo root itself
                                       // Escapes — absolute, leading `..`, and mid-path `..` that pops out.
        assert!(!path_inside_repo("/etc"));
        assert!(!path_inside_repo("../etc"));
        assert!(!path_inside_repo("a/../../etc"));
    }

    #[test]
    fn unknown_fields_preserved_and_warned() {
        let text =
            "---\nstatus: approved\nmaturity: mvp\nroadmap_url: https://example.com/x\n---\n";
        let n = norm(text);
        assert!(n.is_valid());
        assert_eq!(
            n.contract
                .extra_fields
                .get("roadmap_url")
                .and_then(|v| v.as_str()),
            Some("https://example.com/x")
        );
        assert!(n
            .problems
            .warnings
            .iter()
            .any(|w| w.contains("roadmap_url") && w.contains("forward-compat")));
    }

    #[test]
    fn duplicate_key_is_rejected() {
        assert_error_contains(
            &norm("---\nstatus: approved\nstatus: draft\nmaturity: mvp\n---\n"),
            "invalid YAML",
        );
    }

    #[test]
    fn missing_frontmatter_is_rejected() {
        assert_error_contains(&norm("no frontmatter here\n"), "frontmatter missing");
    }

    #[test]
    fn unclosed_frontmatter_is_rejected() {
        assert_error_contains(&norm("---\nstatus: approved\n"), "frontmatter not closed");
    }

    #[test]
    fn invalid_enum_records_error_and_continues() {
        // A bad status AND a bad maturity: both surface (multi-error collection).
        let n = norm("---\nstatus: bogus\nmaturity: alsobogus\n---\n");
        assert!(n.problems.errors.iter().any(|e| e.contains("status")));
        assert!(n.problems.errors.iter().any(|e| e.contains("maturity")));
    }

    #[test]
    fn fragment_dir_present_suppresses_advisory() {
        let text = "---\nstatus: approved\nmaturity: mvp\necosystems: [rust]\n\
                    changelog:\n  mode: fragment\n  source: manual\n---\n";
        // The default fragment dir exists → no advisory warning.
        let fs = FakeFs::with_dirs(["/repo/changelog/fragments"]);
        let n = norm_with(text, &fs);
        assert!(n.is_valid());
        assert!(
            !n.problems
                .warnings
                .iter()
                .any(|w| w.contains("does not exist yet")),
            "advisory should be suppressed when the dir exists: {:?}",
            n.problems.warnings
        );
    }

    #[test]
    fn serializes_to_schema_v4_shape() {
        let json =
            serde_json::to_value(&norm("---\nstatus: approved\nmaturity: mvp\n---\n").contract)
                .unwrap();
        // Spot-check the §4 top-level keys that consumers read.
        for key in [
            "schema_version",
            "status",
            "maturity",
            "ecosystems",
            "targets",
            "distributions",
            "versioning",
            "versioning_pattern",
            "changelog",
            "conventional_commits",
            "release",
            "contribution_provenance",
            "provenance_level",
            "dependency_bot",
            "health_badges",
            "license",
            "docs_site",
            "warnings",
        ] {
            assert!(json.get(key).is_some(), "missing §4 key {key}");
        }
        assert!(json["versioning_pattern"].is_null());
        // A registry-only contract carries an explicit empty `distributions: []` —
        // the collection is always a JSON array (v2 canonical shape).
        assert_eq!(json["distributions"], serde_json::json!([]));
        // An EMPTY `extra_fields` is OMITTED from canonical JSON (Option A,
        // `skip_serializing_if`): a contract with no unknown keys carries no
        // `extra_fields` key at all. It reappears only when populated — see
        // [`empty_extra_fields_absent_populated_present`].
        assert!(
            json.get("extra_fields").is_none(),
            "empty extra_fields must be absent, got {:?}",
            json.get("extra_fields")
        );
    }

    /// Option A (omit-when-empty), asserted SYMMETRICALLY on both the top-level
    /// [`Contract::extra_fields`] and the nested [`Distribution::extra_fields`]:
    /// an empty map is ABSENT from canonical JSON, a populated map is PRESENT and
    /// byte-for-shape unchanged from before the `skip_serializing_if`.
    #[test]
    fn empty_extra_fields_absent_populated_present() {
        // Empty (both levels): a contract with a distribution but no unknown keys.
        let empty = serde_json::to_value(
            norm(
                "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                 distribution:\n  adapter: cargo-dist\n---\n",
            )
            .contract,
        )
        .unwrap();
        assert!(
            empty.get("extra_fields").is_none(),
            "empty top-level extra_fields must be absent"
        );
        assert!(
            empty["distributions"][0].get("extra_fields").is_none(),
            "empty nested extra_fields must be absent"
        );

        // Populated (both levels): an unknown top-level key and an unknown
        // distribution key are preserved and PRESENT.
        let populated = serde_json::to_value(
            norm(
                "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                 roadmap_url: https://example.com/roadmap\n\
                 distribution:\n  adapter: cargo-dist\n  future_x: 1\n---\n",
            )
            .contract,
        )
        .unwrap();
        assert_eq!(
            populated["extra_fields"]["roadmap_url"],
            "https://example.com/roadmap"
        );
        assert_eq!(populated["distributions"][0]["extra_fields"]["future_x"], 1);
    }

    // ── distribution (cargo-dist binary layer) ───────────────────────────────

    /// A registry-only contract has no distribution: it normalizes clean and
    /// `distributions` is empty.
    #[test]
    fn registry_only_contract_has_no_distribution() {
        let c = norm("---\nstatus: approved\nmaturity: mvp\necosystems: [rust]\n---\n").contract;
        assert!(c.distributions.is_empty());
        assert_eq!(c.targets.len(), 1);
        assert_eq!(c.targets[0].registry, Registry::CratesIo);
    }

    /// A cargo-dist repo: a `distribution` block (binaries + shell/Homebrew
    /// installers + a tap) coexisting with a crates.io registry target.
    #[test]
    fn cargo_dist_distribution_coexists_with_registry() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    targets:\n  - {ecosystem: rust, package: issuectl, registry: crates.io, adapter: cargo-publish}\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [shell, homebrew]\n  \
                    homebrew_tap: jarimustonen/homebrew-issuectl\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        let c = n.contract;
        // The registry publish is still a Target.
        assert_eq!(c.targets.len(), 1);
        assert_eq!(c.targets[0].registry, Registry::CratesIo);
        assert_eq!(c.targets[0].adapter, Adapter::CargoPublish);
        // The binary layer is the Distribution block.
        let d = c
            .distributions
            .into_iter()
            .next()
            .expect("distribution present");
        assert_eq!(d.adapter, DistributionAdapter::CargoDist);
        assert!(d.gh_releases); // default true
        assert_eq!(d.installers, vec![Installer::Shell, Installer::Homebrew]);
        assert_eq!(
            d.homebrew_tap.as_deref(),
            Some("jarimustonen/homebrew-issuectl")
        );
    }

    /// Round-trip: the serialized JSON shape a downstream `/oss-*` member reads.
    #[test]
    fn distribution_json_round_trip_shape() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  gh_releases: true\n  \
                    installers: [shell, homebrew]\n  homebrew_tap: jarimustonen/homebrew-issuectl\n---\n";
        let json = serde_json::to_value(&norm(text).contract).unwrap();
        let d = &json["distributions"][0];
        assert_eq!(d["adapter"], "cargo-dist");
        assert_eq!(d["gh_releases"], true);
        assert_eq!(d["installers"], serde_json::json!(["shell", "homebrew"]));
        assert_eq!(d["homebrew_tap"], "jarimustonen/homebrew-issuectl");
        // A bare (singular) block carries a `null` association key.
        assert!(d["package"].is_null());
    }

    // ── homebrew cross-field consistency floors (truth table) ────────────────

    /// Build a production contract exercising the three homebrew signals: a
    /// configured `tap`, an `installer` producer (a `homebrew` installer), and a
    /// `tap_target` producer (a `homebrew`-registry target with adapter
    /// `homebrew-tap`). A crates.io target is always present so the contract has a
    /// licensed publishable target.
    fn hb_case(tap: bool, installer: bool, tap_target: bool) -> String {
        let mut fm = String::from(
            "---\nstatus: approved\nmaturity: production\necosystems: [rust]\ntargets:\n  \
             - {ecosystem: rust, package: ossctl, registry: crates.io, adapter: cargo-publish}\n",
        );
        if tap_target {
            fm.push_str(
                "  - {ecosystem: rust, package: ossctl, registry: homebrew, adapter: homebrew-tap}\n",
            );
        }
        // A distribution block exists whenever we need to express an installer
        // producer or a configured tap; otherwise the contract is registry-only.
        if installer || tap {
            fm.push_str("distribution:\n  adapter: cargo-dist\n");
            if installer {
                fm.push_str("  installers: [homebrew]\n");
            } else {
                fm.push_str("  installers: [shell]\n");
            }
            if tap {
                fm.push_str("  homebrew_tap: owner/tap\n");
            }
        }
        fm.push_str("---\n");
        fm
    }

    /// The full 8-row truth table (tap × installer-producer × tap-target-producer).
    /// Each row asserts the accept/reject verdict; the floor/advisory messages are
    /// pinned in the focused tests below.
    #[test]
    fn homebrew_truth_table_all_eight_rows() {
        // (tap, installer, tap_target, expect_valid)
        let rows = [
            (false, false, false, true), // 1: nothing homebrew → clean
            (false, false, true, false), // 2: tap-target, no tap → missing-tap floor
            (false, true, false, false), // 3: installer, no tap → per-block floor
            (false, true, true, false),  // 4: both producers, no tap → floors
            (true, false, false, true),  // 5: tap, no producer → dead-tap advisory (valid)
            (true, false, true, true),   // 6: tap + tap-target → well-formed (ossctl's case)
            (true, true, false, true),   // 7: tap + installer → well-formed (cargo-dist)
            (true, true, true, false),   // 8: tap + both producers → double-publish floor
        ];
        for (tap, installer, tap_target, expect_valid) in rows {
            let n = norm(&hb_case(tap, installer, tap_target));
            assert_eq!(
                n.is_valid(),
                expect_valid,
                "row (tap={tap}, installer={installer}, tap_target={tap_target}) expected \
                 valid={expect_valid}; errors were {:?}",
                n.problems.errors
            );
        }
    }

    /// Row 2: a `homebrew-tap` target with no tap anywhere is a hard error (the
    /// target-side counterpart of the per-block installer-without-tap floor).
    #[test]
    fn homebrew_tap_target_without_tap_is_a_floor() {
        assert_error_contains(
            &norm(&hb_case(false, false, true)),
            "generates a formula but no distribution sets homebrew_tap",
        );
    }

    /// Row 8: an installer producer AND a `homebrew-tap` target both push a formula
    /// to the tap — the double-publish collision is a hard error.
    #[test]
    fn homebrew_double_publish_is_a_floor() {
        assert_error_contains(
            &norm(&hb_case(true, true, true)),
            "they would collide; keep exactly one homebrew formula producer",
        );
    }

    /// Row 5: a configured tap with neither producer is dead config — an advisory
    /// warning, and the contract still normalizes clean.
    #[test]
    fn homebrew_dead_tap_is_an_advisory_not_a_floor() {
        let n = norm(&hb_case(true, false, false));
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            n.problems
                .warnings
                .iter()
                .any(|w| w.contains("the tap will never be updated")),
            "expected dead-tap advisory, warnings were {:?}",
            n.problems.warnings
        );
    }

    /// Row 6: a `homebrew-tap` target with a configured tap and no installer
    /// producer is the well-formed case (ossctl's own shape) — clean, no advisory.
    #[test]
    fn homebrew_tap_target_with_tap_is_clean() {
        let n = norm(&hb_case(true, false, true));
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            !n.problems
                .warnings
                .iter()
                .any(|w| w.contains("the tap will never be updated")),
            "unexpected dead-tap advisory: {:?}",
            n.problems.warnings
        );
    }

    /// registry/adapter compatibility: a `homebrew`-registry target with a
    /// non-homebrew adapter (here the ecosystem default via an explicit `manual`)
    /// is a hard error — it has no homebrew formula path.
    #[test]
    fn homebrew_registry_requires_homebrew_adapter() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\ntargets:\n  \
                    - {ecosystem: rust, package: ossctl, registry: homebrew, adapter: manual}\n\
                    distribution:\n  adapter: cargo-dist\n  homebrew_tap: owner/tap\n---\n";
        assert_error_contains(
            &norm(text),
            "requires adapter 'homebrew-tap' (personal tap) or 'homebrew-core'",
        );
    }

    /// A `homebrew-core` target is a valid homebrew adapter and needs NO personal
    /// tap (it bumps the central formula) — it is neither a missing-tap floor nor a
    /// dead-tap advisory, and does not collide with a `homebrew` installer.
    #[test]
    fn homebrew_core_target_needs_no_tap() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\ntargets:\n  \
                    - {ecosystem: rust, package: ossctl, registry: crates.io, adapter: cargo-publish}\n  \
                    - {ecosystem: rust, package: ossctl, registry: homebrew, adapter: homebrew-core}\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
    }

    /// registry/adapter compat, OMITTED adapter: a `homebrew`-registry target with
    /// no adapter resolves to the ecosystem default (`cargo-publish` for rust),
    /// which is non-homebrew — so it hits the same floor. The normalizer never
    /// registry-defaults a homebrew target to `homebrew-tap` (that would silently
    /// choose personal-tap publication over a homebrew-core PR); the author must
    /// spell the adapter. This locks the omitted-adapter path, not just explicit
    /// `manual`.
    #[test]
    fn homebrew_registry_omitted_adapter_is_a_floor() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\ntargets:\n  \
                    - {ecosystem: rust, package: ossctl, registry: homebrew}\n---\n";
        assert_error_contains(
            &norm(text),
            "requires adapter 'homebrew-tap' (personal tap) or 'homebrew-core'",
        );
    }

    /// The homebrew cross-field check reads the plural `distributions:` (Vec) path,
    /// not only the singular back-compat mapping: a one-entry `distributions:` list
    /// carrying the tap satisfies a `homebrew-tap` target (row 6 via the Vec shape).
    #[test]
    fn homebrew_tap_target_satisfied_via_plural_distributions() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\ntargets:\n  \
                    - {ecosystem: rust, package: ossctl, registry: crates.io, adapter: cargo-publish}\n  \
                    - {ecosystem: rust, package: ossctl, registry: homebrew, adapter: homebrew-tap}\n\
                    distributions:\n  \
                    - {package: ossctl, adapter: cargo-dist, installers: [shell], homebrew_tap: owner/tap}\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            !n.problems
                .warnings
                .iter()
                .any(|w| w.contains("the tap will never be updated")),
            "unexpected dead-tap advisory: {:?}",
            n.problems.warnings
        );
    }

    // ── monorepo: Vec<Distribution> + per-package association ─────────────────

    /// Back-compat: a bare singular `distribution:` mapping deserializes as a
    /// one-element `distributions` list with a `null` package — the v1 author
    /// changes nothing.
    #[test]
    fn singular_distribution_parses_as_one_element_list() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n---\n";
        let c = norm(text).contract;
        assert_eq!(c.distributions.len(), 1);
        assert_eq!(c.distributions[0].package, None);
        assert_eq!(c.distributions[0].adapter, DistributionAdapter::CargoDist);
    }

    /// A monorepo: a plural `distributions:` sequence, each entry tagged with the
    /// package it builds, parses with the per-package association preserved in
    /// order (each distribution keeps its own installers/tap).
    #[test]
    fn plural_distributions_parse_with_per_package_association() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    targets:\n  - {ecosystem: rust, package: alpha, registry: crates.io}\n  \
                    - {ecosystem: rust, package: beta, registry: crates.io}\n\
                    distributions:\n  - {package: alpha, adapter: cargo-dist, installers: [shell]}\n  \
                    - {package: beta, adapter: cargo-dist, installers: [homebrew], homebrew_tap: owner/tap}\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        let d = n.contract.distributions;
        assert_eq!(d.len(), 2);
        assert_eq!(d[0].package.as_deref(), Some("alpha"));
        assert_eq!(d[0].installers, vec![Installer::Shell]);
        assert_eq!(d[1].package.as_deref(), Some("beta"));
        assert_eq!(d[1].homebrew_tap.as_deref(), Some("owner/tap"));
    }

    /// Canonical JSON round-trips for BOTH shapes: the emitted `distributions`
    /// array re-feeds as YAML frontmatter and normalizes to the same list — the
    /// single (bare `distribution:`) and the monorepo (`distributions:`) cases.
    #[test]
    fn distributions_canonical_json_round_trip() {
        for text in [
            "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
             distribution:\n  adapter: cargo-dist\n  installers: [shell]\n---\n",
            "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
             targets:\n  - {ecosystem: rust, package: a, registry: crates.io}\n  \
             - {ecosystem: rust, package: b, registry: crates.io}\n\
             distributions:\n  - {package: a, adapter: cargo-dist}\n  \
             - {package: b, adapter: goreleaser}\n---\n",
        ] {
            let first = norm(text).contract;
            assert!(!first.distributions.is_empty());
            // Re-feed the canonical JSON as the frontmatter of a fresh document.
            let json = serde_json::to_value(&first).unwrap();
            let refed = format!("---\n{}---\n", serde_yaml::to_string(&json).unwrap());
            let second = norm(&refed).contract;
            assert_eq!(
                first.distributions, second.distributions,
                "round-trip drift for: {text}"
            );
        }
    }

    /// Declaring BOTH `distribution:` and `distributions:` is ambiguous → error.
    #[test]
    fn both_distribution_keys_is_an_error() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n\
                    distributions:\n  - {package: a, adapter: cargo-dist}\n---\n";
        assert_error_contains(&norm(text), "not both");
    }

    /// A monorepo (≥2 distributions) with an entry missing `package` → floor error
    /// (the entries would be indistinguishable).
    #[test]
    fn multi_distribution_missing_package_is_a_floor_error() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    targets:\n  - {ecosystem: rust, package: a, registry: crates.io}\n\
                    distributions:\n  - {package: a, adapter: cargo-dist}\n  \
                    - {adapter: cargo-dist}\n---\n";
        assert_error_contains(&norm(text), "must name the package it builds");
    }

    /// A monorepo with a duplicate `package` across distributions → floor error.
    #[test]
    fn multi_distribution_duplicate_package_is_a_floor_error() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distributions:\n  - {package: dup, adapter: cargo-dist}\n  \
                    - {package: dup, adapter: goreleaser}\n---\n";
        assert_error_contains(&norm(text), "distinct package");
    }

    /// A v1 document (explicit `schema_version: 1`, singular `distribution:`)
    /// normalizes to the v2 canonical shape AND is re-labeled `schema_version: 2` —
    /// never a v2 body stamped with a v1 number. The tool reads v1, emits v2.
    #[test]
    fn v1_document_is_relabeled_to_current_schema_version_on_emit() {
        let text = "---\nschema_version: 1\nstatus: approved\nmaturity: production\n\
                    ecosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        // Emitted version is the current one, not the declared 1.
        assert_eq!(n.contract.schema_version, 2);
        let json = serde_json::to_value(&n.contract).unwrap();
        assert_eq!(json["schema_version"], 2);
        // …and the shape is the v2 `distributions` array (the singular key parsed).
        assert_eq!(json["distributions"].as_array().map(Vec::len), Some(1));
    }

    /// A whitespace-padded `package` is trimmed before storing — so `"  alpha "`
    /// and `"alpha"` are the SAME package to the uniqueness floor and association,
    /// not two distinct ones that would slip past the dup-check.
    #[test]
    fn distribution_package_is_trimmed() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distributions:\n  - {package: '  alpha ', adapter: cargo-dist}\n  \
                    - {package: alpha, adapter: goreleaser}\n---\n";
        // The two trimmed packages collide → the duplicate-package floor fires.
        assert_error_contains(&norm(text), "distinct package");
    }

    /// A single distribution MAY carry a `package` (no floor below the ≥2
    /// threshold) — the association key is optional, not forbidden, for one block.
    #[test]
    fn single_distribution_may_carry_a_package() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    targets:\n  - {ecosystem: rust, package: solo, registry: crates.io}\n\
                    distributions:\n  - {package: solo, adapter: cargo-dist}\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert_eq!(n.contract.distributions[0].package.as_deref(), Some("solo"));
    }

    /// Forward-compat: an unknown key inside the `distribution` block is preserved
    /// under `distribution.extra_fields` (not dropped) and survives a
    /// parse→serialize round-trip, mirroring the top-level `extra_fields` capture.
    /// A warning reports it once; the known distribution keys are unaffected.
    #[test]
    fn distribution_unknown_subkey_preserved_and_warned() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  gh_releases: true\n  \
                    future_signing: {enabled: true, kms_key: alias/oss}\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        let d = n
            .contract
            .clone()
            .distributions
            .into_iter()
            .next()
            .expect("distribution present");
        // The unknown sub-key is captured, with its nested value intact.
        assert_eq!(
            d.extra_fields
                .get("future_signing")
                .and_then(|v| v.get("kms_key"))
                .and_then(|v| v.as_str()),
            Some("alias/oss")
        );
        // Known keys are untouched by the capture.
        assert_eq!(d.adapter, DistributionAdapter::CargoDist);
        assert!(d.gh_releases);
        // It round-trips through the serialized JSON downstream members read.
        let json = serde_json::to_value(&n.contract).unwrap();
        assert_eq!(
            json["distributions"][0]["extra_fields"]["future_signing"]["enabled"],
            serde_json::json!(true)
        );
        // Reported once, scoped to the block, naming the key.
        assert!(
            n.problems.warnings.iter().any(|w| {
                w.contains("unknown distribution field(s) preserved")
                    && w.contains("future_signing")
            }),
            "expected a scoped forward-compat warning: {:?}",
            n.problems.warnings
        );
    }

    // ── installer ↔ platform cross-check (warning, not a floor) ──────────────

    /// `installers: [msi]` with no Windows triple in `platforms` warns — the MSI
    /// installer points at a binary the release never builds. Still valid (warning,
    /// not error): the contract is internally consistent, just wasteful.
    #[test]
    fn msi_installer_without_windows_platform_warns() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [msi]\n  \
                    platforms: [x86_64-apple-darwin, x86_64-unknown-linux-musl]\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            n.problems
                .warnings
                .iter()
                .any(|w| w.contains("includes 'msi'") && w.contains("no Windows")),
            "expected an msi/Windows cross-check warning: {:?}",
            n.problems.warnings
        );
    }

    /// `installers: [msi]` WITH a Windows triple present → no cross-check warning.
    #[test]
    fn msi_installer_with_windows_platform_no_warning() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [msi]\n  \
                    platforms: [x86_64-pc-windows-msvc]\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            !n.problems.warnings.iter().any(|w| w.contains("'msi'")),
            "unexpected msi cross-check warning: {:?}",
            n.problems.warnings
        );
    }

    /// `installers: [homebrew]` with NEITHER a macOS nor a Linux triple warns —
    /// the generated formula has nothing to install. (A Windows-only platform set
    /// is the only way to strand a `homebrew` installer, since Homebrew serves
    /// both macOS and Linux.)
    #[test]
    fn homebrew_installer_without_darwin_or_linux_warns() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [homebrew]\n  \
                    homebrew_tap: jarimustonen/homebrew-issuectl\n  \
                    platforms: [x86_64-pc-windows-msvc]\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            n.problems
                .warnings
                .iter()
                .any(|w| w.contains("includes 'homebrew'") && w.contains("nothing to install")),
            "expected a homebrew/(macOS|Linux) cross-check warning: {:?}",
            n.problems.warnings
        );
    }

    /// `installers: [homebrew]` is satisfied by a LINUX triple alone (Linuxbrew) —
    /// no darwin triple required. The chosen interpretation: homebrew needs macOS
    /// OR Linux, so a Linux-only platform set is coherent, not a warning.
    #[test]
    fn homebrew_installer_with_linux_only_no_warning() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [homebrew]\n  \
                    homebrew_tap: jarimustonen/homebrew-issuectl\n  \
                    platforms: [x86_64-unknown-linux-musl]\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            !n.problems.warnings.iter().any(|w| w.contains("'homebrew'")),
            "unexpected homebrew cross-check warning for a Linux-only set: {:?}",
            n.problems.warnings
        );
    }

    /// npm and shell installers are OS-agnostic: even a platform set that would
    /// strand an msi (no Windows) never warns for them.
    #[test]
    fn npm_and_shell_installers_never_cross_check_warn() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust, node]\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [shell, npm]\n  \
                    platforms: [x86_64-apple-darwin]\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            !n.problems
                .warnings
                .iter()
                .any(|w| w.contains("nothing to install")),
            "OS-agnostic installers must not cross-check warn: {:?}",
            n.problems.warnings
        );
    }

    /// A coherent installer/platform set (msi + Windows, homebrew + darwin) emits
    /// no cross-check warning.
    #[test]
    fn coherent_installer_platform_set_no_warning() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [homebrew, msi]\n  \
                    homebrew_tap: jarimustonen/homebrew-issuectl\n  \
                    platforms: [aarch64-apple-darwin, x86_64-pc-windows-msvc]\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            !n.problems
                .warnings
                .iter()
                .any(|w| w.contains("nothing to install")),
            "coherent set must not warn: {:?}",
            n.problems.warnings
        );
    }

    /// ossctl's own contract shape — installers `[shell, powershell]` with a
    /// platform set spanning Windows + macOS + Linux — produces no cross-check
    /// warning (both installers are agnostic here, and every OS is covered anyway).
    #[test]
    fn ossctl_own_contract_shape_no_cross_check_warning() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [shell, powershell]\n  \
                    platforms: [aarch64-apple-darwin, x86_64-apple-darwin, \
                    x86_64-unknown-linux-musl, aarch64-unknown-linux-musl, \
                    x86_64-pc-windows-msvc]\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            !n.problems
                .warnings
                .iter()
                .any(|w| w.contains("nothing to install")),
            "ossctl's own shape must not cross-check warn: {:?}",
            n.problems.warnings
        );
    }

    /// `installers: [msi]` with `platforms` OMITTED warns: the default set
    /// (macOS + Linux) carries no Windows triple, so the MSI installs nothing.
    /// This is the common footgun — the author added msi but never listed a
    /// Windows target.
    #[test]
    fn msi_installer_with_defaulted_platforms_warns() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [msi]\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            n.problems
                .warnings
                .iter()
                .any(|w| w.contains("includes 'msi'") && w.contains("no Windows")),
            "expected an msi/Windows warning against the defaulted platform set: {:?}",
            n.problems.warnings
        );
    }

    /// `installers: [msi]` is satisfied by a `*-windows-gnu` triple just as by
    /// `*-windows-msvc` — both target the Windows OS. No warning.
    #[test]
    fn msi_installer_with_windows_gnu_no_warning() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [msi]\n  \
                    platforms: [x86_64-pc-windows-gnu]\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            !n.problems.warnings.iter().any(|w| w.contains("'msi'")),
            "windows-gnu must satisfy msi: {:?}",
            n.problems.warnings
        );
    }

    /// `installers: [homebrew]` with an ANDROID-only platform set warns: Android
    /// triples (`aarch64-linux-android`) carry `linux` in the *vendor* slot but an
    /// `android` OS component — Homebrew/Linuxbrew does not serve Android, so the
    /// formula has nothing to install. Regression guard for the positional
    /// `triple_os` OS-component match (vs a naive any-component `== "linux"`).
    #[test]
    fn homebrew_installer_with_android_only_warns() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [homebrew]\n  \
                    homebrew_tap: jarimustonen/homebrew-issuectl\n  \
                    platforms: [aarch64-linux-android]\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            n.problems
                .warnings
                .iter()
                .any(|w| w.contains("includes 'homebrew'") && w.contains("nothing to install")),
            "Android-only must strand a homebrew installer: {:?}",
            n.problems.warnings
        );
    }

    /// `installers: [homebrew]` with an APPLE-iOS-only set warns: `*-apple-ios`
    /// carries an `ios` OS component, not `darwin`, so it is not a macOS target and
    /// Homebrew serves neither iOS nor (here) Linux.
    #[test]
    fn homebrew_installer_with_apple_ios_only_warns() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [homebrew]\n  \
                    homebrew_tap: jarimustonen/homebrew-issuectl\n  \
                    platforms: [aarch64-apple-ios]\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            n.problems
                .warnings
                .iter()
                .any(|w| w.contains("includes 'homebrew'") && w.contains("nothing to install")),
            "apple-ios must not satisfy homebrew's macOS need: {:?}",
            n.problems.warnings
        );
    }

    /// `installers: [homebrew]` with a macOS-only set (no Linux) is coherent — the
    /// isolated darwin case, distinct from the Linux-only test above.
    #[test]
    fn homebrew_installer_with_macos_only_no_warning() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [homebrew]\n  \
                    homebrew_tap: jarimustonen/homebrew-issuectl\n  \
                    platforms: [aarch64-apple-darwin]\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            !n.problems.warnings.iter().any(|w| w.contains("'homebrew'")),
            "macOS-only must satisfy homebrew: {:?}",
            n.problems.warnings
        );
    }

    /// Two stranded installers → two independent warnings. A wasm-only platform
    /// set has no OS component any installer supports, so both `msi` and `homebrew`
    /// warn (exactly once each — the installer list is de-duped and canonically
    /// ordered).
    #[test]
    fn both_installers_stranded_warn_once_each() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [homebrew, msi]\n  \
                    homebrew_tap: jarimustonen/homebrew-issuectl\n  \
                    platforms: [wasm32-unknown-unknown]\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        let msi = n
            .problems
            .warnings
            .iter()
            .filter(|w| w.contains("includes 'msi'"))
            .count();
        let brew = n
            .problems
            .warnings
            .iter()
            .filter(|w| w.contains("includes 'homebrew'"))
            .count();
        assert_eq!((msi, brew), (1, 1), "warnings: {:?}", n.problems.warnings);
    }

    /// A malformed triple that happens to contain an OS keyword must NOT drive the
    /// cross-check: the block has a parse error (uppercase triple), so the advisory
    /// is gated off entirely. Otherwise the misspelled `x86_64-PC-WINDOWS-MSVC`
    /// would silently "satisfy" msi and the warning would flip once the author
    /// fixed the typo.
    #[test]
    fn malformed_platform_triple_gates_off_cross_check() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [msi]\n  \
                    platforms: [x86_64-PC-WINDOWS-MSVC]\n---\n";
        let n = norm(text);
        // The uppercase triple is a hard error → the document is invalid …
        assert!(!n.is_valid(), "expected a malformed-triple error");
        // … and the cross-check emitted no (misleading) installer/platform warning.
        assert!(
            !n.problems
                .warnings
                .iter()
                .any(|w| w.contains("nothing to install")),
            "cross-check must be gated off while platforms has errors: {:?}",
            n.problems.warnings
        );
    }

    /// A distribution block setting EVERY known key carries an empty
    /// `extra_fields` map and emits no forward-compat warning — the additive field
    /// is shape-neutral for existing contracts. Exercising all of
    /// `KNOWN_DISTRIBUTION_KEYS` guards against the allowlist drifting out of sync
    /// with the struct (a new known key wrongly captured as "unknown").
    #[test]
    fn distribution_all_known_keys_has_empty_extra_fields() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  gh_releases: true\n  \
                    installers: [shell, homebrew]\n  homebrew_tap: owner/tap\n  \
                    platforms: [x86_64-unknown-linux-musl]\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        let d = n
            .contract
            .distributions
            .into_iter()
            .next()
            .expect("distribution present");
        assert!(d.extra_fields.is_empty());
        assert!(
            !n.problems
                .warnings
                .iter()
                .any(|w| w.contains("unknown distribution field(s) preserved")),
            "no forward-compat warning for an all-known-keys block: {:?}",
            n.problems.warnings
        );
    }

    /// Top-level and nested `extra_fields` capture are independent: a contract
    /// with BOTH an unknown top-level key AND an unknown distribution sub-key
    /// populates both maps and warns once for each, with the correct
    /// `schema_version` in each message.
    #[test]
    fn distribution_and_top_level_extra_fields_coexist() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    roadmap_url: https://example.com/x\n\
                    distribution:\n  adapter: cargo-dist\n  future_x: 1\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        let c = n.contract.clone();
        assert!(c.extra_fields.contains_key("roadmap_url"));
        let d = c
            .distributions
            .into_iter()
            .next()
            .expect("distribution present");
        assert_eq!(d.extra_fields.get("future_x"), Some(&serde_json::json!(1)));
        // Two independent forward-compat warnings, each naming schema_version 2
        // (the contract omits schema_version → defaults to KNOWN_SCHEMA_VERSION).
        let fc: Vec<&String> = n
            .problems
            .warnings
            .iter()
            .filter(|w| w.contains("forward-compat") && w.contains("schema_version 2"))
            .collect();
        assert_eq!(fc.len(), 2, "expected two versioned warnings: {fc:?}");
    }

    // ── extra_fields capture hardening ───────────────────────────────────────

    /// A non-string top-level mapping key (`42:`, legal YAML) is a STRUCTURAL
    /// error, not silently coerced/dropped: distinct non-string keys collapse onto
    /// the same JSON key (`42` and `"42"`; every list key onto `<list>`), so
    /// preserving them losslessly is impossible — the normalizer rejects instead,
    /// keeping the never-drop invariant vacuously.
    #[test]
    fn non_string_top_level_key_rejected() {
        let n = norm("---\nstatus: approved\nmaturity: mvp\n42: answer\n---\n");
        assert_error_contains(&n, "must be a string");
        assert!(
            n.problems.errors.iter().any(|e| e.contains("42")),
            "error should name the offending key: {:?}",
            n.problems.errors
        );
    }

    /// The nested `distribution` scan rejects the same way, with the block scope in
    /// the message.
    #[test]
    fn non_string_distribution_key_rejected() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  true: enabled\n---\n";
        let n = norm(text);
        assert_error_contains(&n, "must be a string");
        assert!(
            n.problems
                .errors
                .iter()
                .any(|e| e.contains("distribution field key")),
            "error should be scoped to the distribution block: {:?}",
            n.problems.errors
        );
    }

    /// A known key placed normally is parsed as its field and NOT double-captured
    /// into `extra_fields` — the dedupe guarantee (a key is never both a known
    /// field and an extra field).
    #[test]
    fn known_key_not_double_captured() {
        let n = norm("---\nstatus: approved\nmaturity: production\necosystems: [rust]\n---\n");
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(!n.contract.extra_fields.contains_key("ecosystems"));
        assert!(!n.contract.extra_fields.contains_key("status"));
        assert!(n.contract.extra_fields.is_empty());
    }

    /// The reserved `extra_fields` metadata key is not re-captured into a nested
    /// `extra_fields.extra_fields`; its mapping contents are MERGED back, so a
    /// hand-authored (or defensively re-fed canonical) block round-trips losslessly
    /// rather than being silently dropped. The derived `warnings` key is ignored
    /// (regenerated), not preserved — it is not user contract data.
    #[test]
    fn reserved_extra_fields_block_merged_warnings_ignored() {
        let text = "---\nstatus: approved\nmaturity: mvp\n\
                    extra_fields:\n  foo: 1\nwarnings:\n  - a prior note\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        // `foo` is preserved (merged), not nested and not dropped.
        assert_eq!(
            n.contract.extra_fields.get("foo"),
            Some(&serde_json::json!(1))
        );
        assert!(!n.contract.extra_fields.contains_key("extra_fields"));
        // The stale input `warnings` list is not resurrected into the output.
        assert!(
            !n.contract
                .warnings
                .iter()
                .any(|w| w.contains("a prior note")),
            "input warnings must be regenerated, not preserved: {:?}",
            n.contract.warnings
        );
    }

    /// The nested analogue: `distribution.extra_fields` is merged back, not nested
    /// and not dropped.
    #[test]
    fn distribution_reserved_extra_fields_block_merged() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  extra_fields:\n    foo: 1\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        let d = n
            .contract
            .distributions
            .into_iter()
            .next()
            .expect("distribution present");
        assert_eq!(d.extra_fields.get("foo"), Some(&serde_json::json!(1)));
        assert!(!d.extra_fields.contains_key("extra_fields"));
    }

    /// Idempotence: normalizing, serializing the canonical `extra_fields` map, and
    /// re-feeding it as an `extra_fields` block yields the identical map — the
    /// round-trip the reserve+merge design guarantees (no nesting, no loss).
    #[test]
    fn extra_fields_round_trip_is_idempotent() {
        let first = norm("---\nstatus: approved\nmaturity: mvp\nroadmap_url: https://x/y\n---\n");
        assert!(first.is_valid(), "errors: {:?}", first.problems.errors);
        assert_eq!(first.contract.extra_fields.len(), 1);
        // Feed the captured extra_fields back under the reserved key.
        let inner = serde_yaml::to_string(&first.contract.extra_fields).unwrap();
        let indented = inner
            .lines()
            .map(|l| format!("  {l}"))
            .collect::<Vec<_>>()
            .join("\n");
        let text =
            format!("---\nstatus: approved\nmaturity: mvp\nextra_fields:\n{indented}\n---\n");
        let second = norm(&text);
        assert!(second.is_valid(), "errors: {:?}", second.problems.errors);
        assert_eq!(second.contract.extra_fields, first.contract.extra_fields);
    }

    /// A key present BOTH inside the reserved `extra_fields` block AND as a sibling
    /// unknown top-level key is an ambiguity error — never a silent overwrite of
    /// either value (dedupe: a key resolves to exactly one source).
    #[test]
    fn extra_fields_block_sibling_collision_is_error() {
        let text = "---\nstatus: approved\nmaturity: mvp\n\
                    extra_fields:\n  dup: 1\ndup: 2\n---\n";
        let n = norm(text);
        assert_error_contains(&n, "appears both");
    }

    /// A reserved `extra_fields` value that is not a mapping is a structural error
    /// (it can only carry preserved key/value pairs).
    #[test]
    fn reserved_extra_fields_non_mapping_is_error() {
        let n = norm("---\nstatus: approved\nmaturity: mvp\nextra_fields: nonsense\n---\n");
        assert_error_contains(&n, "must be a mapping");
    }

    /// A contract setting EVERY parsed top-level known key carries an empty
    /// `extra_fields` and emits no forward-compat warning — the top-level analogue
    /// of `distribution_all_known_keys_has_empty_extra_fields`, guarding
    /// [`KNOWN_KEYS`] against drifting out of sync with the [`Contract`] struct (a
    /// new field whose key is missing here would be wrongly captured as unknown).
    #[test]
    fn top_level_all_known_keys_has_empty_extra_fields() {
        let text = "---\nschema_version: 1\nstatus: approved\nmaturity: production\n\
                    ecosystems: [rust]\n\
                    targets:\n  - {ecosystem: rust, package: x, registry: crates.io, adapter: cargo-publish}\n\
                    distribution:\n  adapter: cargo-dist\n\
                    versioning: semver\n\
                    changelog:\n  mode: curated\n  source: manual\n\
                    conventional_commits: false\n\
                    release:\n  model: gated\n  layout: single\n\
                    contribution_provenance: none\n\
                    provenance_level: none\n\
                    dependency_bot: dependabot\n\
                    health_badges: [ci, registry, license]\n\
                    license: MIT\n\
                    docs_site: none\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            n.contract.extra_fields.is_empty(),
            "unexpected extra_fields (KNOWN_KEYS drift?): {:?}",
            n.contract.extra_fields
        );
        assert!(
            !n.problems
                .warnings
                .iter()
                .any(|w| w.contains("forward-compat")),
            "no forward-compat warning for an all-known-keys contract: {:?}",
            n.problems.warnings
        );
    }

    /// Installers de-dup into canonical order regardless of source order.
    #[test]
    fn distribution_installers_dedup_canonical_order() {
        let text = "---\nstatus: approved\nmaturity: mvp\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [homebrew, shell, homebrew]\n  \
                    homebrew_tap: owner/tap\n---\n";
        let d = norm(text)
            .contract
            .distributions
            .into_iter()
            .next()
            .unwrap();
        assert_eq!(d.installers, vec![Installer::Shell, Installer::Homebrew]);
    }

    /// A `homebrew` installer without a tap is a floor error.
    #[test]
    fn distribution_homebrew_installer_requires_tap() {
        let text = "---\nstatus: approved\nmaturity: mvp\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [shell, homebrew]\n---\n";
        assert_error_contains(
            &norm(text),
            "includes 'homebrew' but no distribution.homebrew_tap",
        );
    }

    /// A malformed tap slug (not `owner/repo`) is rejected AND, because the
    /// invalid value substitutes `None`, the homebrew-needs-tap floor still fires
    /// — a present-but-invalid tap must not slip a `homebrew` installer through.
    #[test]
    fn distribution_bad_tap_slug_rejected() {
        let text = "---\nstatus: approved\nmaturity: mvp\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [homebrew]\n  \
                    homebrew_tap: not-a-slug\n---\n";
        let n = norm(text);
        assert_error_contains(&n, "must be an 'owner/repo' slug");
        assert!(
            n.problems
                .errors
                .iter()
                .any(|e| e.contains("includes 'homebrew' but no distribution.homebrew_tap")),
            "the tap floor must still fire on an invalid (→None) tap: {:?}",
            n.problems.errors
        );
        // The malformed slug never leaks into the built block.
        assert_eq!(
            n.contract
                .distributions
                .into_iter()
                .next()
                .unwrap()
                .homebrew_tap,
            None
        );
    }

    /// An unknown installer flavor surfaces an error listing the valid set.
    #[test]
    fn distribution_bad_installer_rejected() {
        let text = "---\nstatus: approved\nmaturity: mvp\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [snap]\n---\n";
        assert_error_contains(&norm(text), "distribution.installers");
    }

    /// `adapter` is required when a distribution block is present — a bare
    /// `distribution: {}` must not silently claim cargo-dist ownership.
    #[test]
    fn distribution_adapter_is_required() {
        assert_error_contains(
            &norm("---\nstatus: approved\nmaturity: mvp\ndistribution: {}\n---\n"),
            "distribution.adapter is required",
        );
    }

    /// A distribution block ships public binaries — forbidden at maturity 'spike'
    /// (mirrors the `release.model: auto`-on-spike floor).
    #[test]
    fn distribution_forbidden_on_spike() {
        let text = "---\nstatus: approved\nmaturity: spike\n\
                    distribution:\n  adapter: cargo-dist\n---\n";
        assert_error_contains(&norm(text), "not allowed on maturity 'spike'");
    }

    /// A `homebrew_tap` set with neither a `homebrew` installer nor a
    /// `homebrew`-registry target is dead config — a warning, not a floor (the
    /// contract is still valid). This is the genuinely-orphaned tap: no consumer
    /// exists, so the tap is truly never updated.
    #[test]
    fn distribution_tap_without_installer_warns() {
        let text = "---\nstatus: approved\nmaturity: mvp\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [shell]\n  \
                    homebrew_tap: owner/tap\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        assert!(
            n.problems
                .warnings
                .iter()
                .any(|w| w.contains("no formula is generated, so the tap will never be updated")),
            "expected dead-tap warning: {:?}",
            n.problems.warnings
        );
    }

    /// A `homebrew_tap` set with NO `homebrew` installer but WITH a
    /// `homebrew`-registry target (the release engine's homebrew-tap adapter, which
    /// pushes the formula in its `dist` phase) is NOT dead config — the tap IS
    /// updated by the engine, so the dead-config warning must NOT fire. This is
    /// ossctl's own (correct) contract shape.
    #[test]
    fn distribution_tap_with_homebrew_target_no_warning() {
        let text = "---\nstatus: approved\nmaturity: mvp\necosystems: [rust]\n\
                    targets:\n  \
                    - {ecosystem: rust, package: ossctl, registry: crates.io, adapter: cargo-publish}\n  \
                    - {ecosystem: rust, package: ossctl, registry: homebrew, adapter: homebrew-tap}\n\
                    distribution:\n  adapter: cargo-dist\n  installers: [shell]\n  \
                    homebrew_tap: owner/tap\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        // Stronger than a negative substring match: the whole contract is clean,
        // so it must produce NO warnings at all — this also catches any reworded
        // dead-tap advisory that a substring check would miss.
        assert!(
            n.problems.warnings.is_empty(),
            "homebrew-target contract must not warn: {:?}",
            n.problems.warnings
        );
    }

    /// A goreleaser distribution with no installers and no tap is valid — the
    /// block is minimal and forward-compatible.
    #[test]
    fn distribution_goreleaser_minimal_is_valid() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [go]\n\
                    distribution:\n  adapter: goreleaser\n  gh_releases: true\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        let d = n.contract.distributions.into_iter().next().unwrap();
        assert_eq!(d.adapter, DistributionAdapter::Goreleaser);
        assert!(d.installers.is_empty());
        assert_eq!(d.homebrew_tap, None);
    }

    /// A non-mapping `distribution` value is a structural error.
    #[test]
    fn distribution_non_mapping_rejected() {
        assert_error_contains(
            &norm("---\nstatus: approved\nmaturity: mvp\ndistribution: [nope]\n---\n"),
            "distribution must be a mapping",
        );
    }

    // ── distribution.platforms (cross-platform target set) ───────────────────

    /// Helper: does a platform list contain any Linux triple? The cross-platform
    /// install requirement is "at least one Linux triple", inspected via the OS
    /// component of the triple (exactly how `audit` will read this field).
    fn has_linux(platforms: &[String]) -> bool {
        platforms.iter().any(|t| t.contains("-linux"))
    }

    /// Omitted `platforms` → the cross-platform default (macOS + Linux). The
    /// KEYSTONE assertion: the DEFAULT covers Linux, so every distribution that
    /// omits the field does (an explicit set is the author's own choice, which the
    /// cross-platform `audit` — not this normalizer — checks).
    #[test]
    fn distribution_platforms_default_is_cross_platform() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n---\n";
        let d = norm(text)
            .contract
            .distributions
            .into_iter()
            .next()
            .expect("distribution present");
        assert_eq!(
            d.platforms,
            vec![
                "aarch64-apple-darwin",
                "x86_64-apple-darwin",
                "aarch64-unknown-linux-musl",
                "x86_64-unknown-linux-musl",
            ]
        );
        assert!(
            has_linux(&d.platforms),
            "the default set MUST contain a Linux triple: {:?}",
            d.platforms
        );
    }

    /// An explicit `platforms` list round-trips through normalization and the
    /// serialized JSON downstream members read, order + values preserved.
    #[test]
    fn distribution_platforms_explicit_round_trips() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  \
                    platforms: [x86_64-unknown-linux-gnu, x86_64-pc-windows-msvc]\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        let d = n.contract.clone().distributions.into_iter().next().unwrap();
        assert_eq!(
            d.platforms,
            vec!["x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"]
        );
        let json = serde_json::to_value(&n.contract).unwrap();
        assert_eq!(
            json["distributions"][0]["platforms"],
            serde_json::json!(["x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"])
        );
    }

    /// An explicit empty `platforms: []` is a hard error — NOT silently defaulted.
    /// Only an omitted/null field yields the cross-platform default; an empty list
    /// is a mistake (a distribution with no platforms builds nothing) and, if
    /// silently defaulted, would surprise the author and erase the intent the
    /// cross-platform audit needs to see.
    #[test]
    fn distribution_platforms_empty_is_rejected() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  platforms: []\n---\n";
        assert_error_contains(&norm(text), "empty list — omit the key");
    }

    /// Duplicate triples de-duplicate, preserving first-seen order.
    #[test]
    fn distribution_platforms_dedup_preserves_order() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  \
                    platforms: [aarch64-apple-darwin, x86_64-apple-darwin, aarch64-apple-darwin]\n---\n";
        let d = norm(text)
            .contract
            .distributions
            .into_iter()
            .next()
            .unwrap();
        assert_eq!(
            d.platforms,
            vec!["aarch64-apple-darwin", "x86_64-apple-darwin"]
        );
    }

    /// A malformed triple is rejected with a message naming the field.
    #[test]
    fn distribution_platforms_bad_triple_rejected() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  platforms: [not_a_triple]\n---\n";
        assert_error_contains(&norm(text), "is not a well-formed target-triple");
    }

    /// A non-string entry (a nested list) is rejected structurally.
    #[test]
    fn distribution_platforms_non_string_entry_rejected() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  platforms: [[nope]]\n---\n";
        assert_error_contains(&norm(text), "each entry must be a target-triple string");
    }

    /// A `platforms` value that is not a list is a structural error.
    #[test]
    fn distribution_platforms_non_list_rejected() {
        let text = "---\nstatus: approved\nmaturity: production\necosystems: [rust]\n\
                    distribution:\n  adapter: cargo-dist\n  platforms: x86_64-apple-darwin\n---\n";
        assert_error_contains(&norm(text), "must be a list of target-triple strings");
    }

    /// Regression: a registry-only contract (no distribution block at all) is
    /// wholly unaffected by the additive `platforms` field — no distribution, so
    /// no `platforms` in the emitted shape.
    #[test]
    fn registry_only_contract_unaffected_by_platforms() {
        let json = serde_json::to_value(
            &norm("---\nstatus: approved\nmaturity: mvp\necosystems: [rust]\n---\n").contract,
        )
        .unwrap();
        assert_eq!(json["distributions"], serde_json::json!([]));
    }

    #[test]
    fn looks_like_target_triple_verdicts() {
        // Standard triples across arch/vendor/os/env shapes.
        assert!(looks_like_target_triple("aarch64-apple-darwin"));
        assert!(looks_like_target_triple("x86_64-apple-darwin"));
        assert!(looks_like_target_triple("x86_64-unknown-linux-musl"));
        assert!(looks_like_target_triple("x86_64-unknown-linux-gnu"));
        assert!(looks_like_target_triple("x86_64-pc-windows-msvc"));
        assert!(looks_like_target_triple("armv7-unknown-linux-gnueabihf"));
        assert!(looks_like_target_triple("wasm32-wasi"));
        // Real dotted arch names must pass (regression: the `.` was rejected).
        assert!(looks_like_target_triple("thumbv8m.main-none-eabi"));
        assert!(looks_like_target_triple("thumbv8m.base-none-eabi"));
        // Rejects: too few/many components, empty parts, case, punctuation.
        assert!(!looks_like_target_triple("linux"));
        assert!(!looks_like_target_triple("a-b-c-d-e"));
        assert!(!looks_like_target_triple("x86_64--linux"));
        assert!(!looks_like_target_triple("-apple-darwin"));
        assert!(!looks_like_target_triple("X86_64-apple-darwin"));
        assert!(!looks_like_target_triple("x86_64-apple-darwin;rm"));
        assert!(!looks_like_target_triple("x86_64 apple darwin"));
        assert!(!looks_like_target_triple(""));
        // Structural-only: nonsense that happens to be well-formed IS accepted —
        // the toolchain, not the contract, is the authority on buildability.
        assert!(looks_like_target_triple("aa-bb"));
    }

    #[test]
    fn is_tap_slug_verdicts() {
        // Valid GitHub-style slugs.
        assert!(is_tap_slug("owner/repo"));
        assert!(is_tap_slug("jarimustonen/homebrew-issuectl"));
        assert!(is_tap_slug("Owner_1/repo.rb"));
        // Structural rejects.
        assert!(!is_tap_slug("no-slash"));
        assert!(!is_tap_slug("/repo"));
        assert!(!is_tap_slug("owner/"));
        assert!(!is_tap_slug("owner/repo/extra"));
        assert!(!is_tap_slug("owner / repo"));
        // Strict-charset rejects: path traversal, punctuation, injection chars.
        assert!(!is_tap_slug("owner/.."));
        assert!(!is_tap_slug("../repo"));
        assert!(!is_tap_slug("owner/repo;rm -rf"));
        assert!(!is_tap_slug("owner/@repo"));
        assert!(!is_tap_slug("ownér/repo"));
    }

    /// `quote_for_diagnostic` JSON-encodes: quotes/backslashes/newlines/control
    /// chars are escaped, ordinary text stays readable.
    #[test]
    fn quote_for_diagnostic_escapes_hostile_input() {
        assert_eq!(quote_for_diagnostic("foo"), "\"foo\"");
        assert_eq!(quote_for_diagnostic("a\"b"), "\"a\\\"b\"");
        assert_eq!(quote_for_diagnostic("a\nb"), "\"a\\nb\"");
        assert_eq!(quote_for_diagnostic("a\tb"), "\"a\\tb\"");
        // A bare C0 control char (0x01) escapes to , never a raw byte.
        assert_eq!(quote_for_diagnostic("\u{1}"), "\"\\u0001\"");
    }

    /// Log-injection hardening: a user-controlled unknown-field KEY carrying a
    /// quote, newline, and control char cannot forge a diagnostic line or emit a
    /// raw control char — it is JSON-encoded onto a single intact line.
    #[test]
    fn unknown_field_key_is_escaped_in_warning() {
        // The key is `evil"key` + newline + a forged-looking line + a control char.
        // Quoted in YAML so the literal quote/newline/control byte are the KEY text.
        let text =
            "---\nstatus: approved\nmaturity: mvp\n\"evil\\\"key\\nforged: line\\u0001\": 1\n---\n";
        let n = norm(text);
        assert!(n.is_valid(), "errors: {:?}", n.problems.errors);
        let warning = n
            .problems
            .warnings
            .iter()
            .find(|w| w.contains("unknown field(s) preserved"))
            .expect("expected an unknown-field warning");
        // The raw quote/newline/control char never appear unescaped in the message:
        // no forged second line, no bare control byte.
        assert!(
            !warning.contains('\n'),
            "warning must stay on one line: {warning:?}"
        );
        assert!(
            !warning.contains('\u{1}'),
            "warning must not carry a raw control char: {warning:?}"
        );
        assert!(
            !warning.contains("evil\"key"),
            "the raw unescaped key must not appear: {warning:?}"
        );
        // The escaped JSON form is present (quote → \", newline → \n, ctrl → ).
        assert!(
            warning.contains("\\\"") && warning.contains("\\n") && warning.contains("\\u0001"),
            "the key must be JSON-escaped: {warning:?}"
        );
    }

    /// The same hardening on a user-controlled VALUE routed through `yaml_display`
    /// (an invalid enum): a newline in the rejected value cannot forge an error
    /// line.
    #[test]
    fn invalid_enum_value_is_escaped_in_error() {
        let text = "---\nstatus: approved\nmaturity: \"mvp\\nforged: line\"\n---\n";
        let n = norm(text);
        assert_error_contains(&n, "maturity");
        let err = n
            .problems
            .errors
            .iter()
            .find(|e| e.contains("maturity") && e.contains("invalid"))
            .expect("expected a maturity-invalid error");
        assert!(!err.contains('\n'), "error must stay on one line: {err:?}");
        assert!(
            err.contains("\\n"),
            "the rejected value's newline must be escaped: {err:?}"
        );
    }
}