compose-lens 0.1.14

Loss-aware parsing, processing, validation, and rendering of Compose projects
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
//! Source-aware native values from a merged and optionally profile-selected Compose project.

use crate::diagnostic::{Diagnostic, DiagnosticCode, DiagnosticLabel, Severity};
use crate::merge::{
    EntrySyntax, MergeProvenance, MergedEntry, MergedProject, MergedScalarKind, MergedValue, MergedValueKind,
};
use crate::model::{
    BindOptions, BooleanValue, CAP_ADD_DUPLICATE_ITEM, CAP_DROP_DUPLICATE_ITEM, CapabilityAddItem, CapabilityDropItem,
    Command, ComposeScalar, ConfigDefinition, DEVICE_EXPECTED_FORM, DEVICE_EXPECTED_STRING, DependencyCondition,
    Entrypoint, EnvironmentFileFormat, EnvironmentFileFormatKind, HealthcheckDuration, HealthcheckRetries,
    HealthcheckTest, HealthcheckTestKind, HostAddress, Hostname, HostnameKind, ImageReference, Ipam, IpamConfig,
    KeyValueEntry, Labels, LimitValue, Located, LongPort, LongVolumeMount, MEM_LIMIT_AMBIGUOUS_ZERO,
    MEM_LIMIT_EXPECTED_VALUE, MEM_LIMIT_PROVIDER_DEPENDENT_STRING, MEM_LIMIT_SCHEMA_NUMBER, MemLimit, MemLimitKind,
    MemLimitScalarKind, MountType, NetworkDefinition, PIDS_LIMIT_AMBIGUOUS_ZERO, PidsLimit, PidsLimitKind, Port,
    PullPolicy, RestartPolicy, SHM_SIZE_AMBIGUOUS_ZERO, SHM_SIZE_EXPECTED_VALUE, SHM_SIZE_PROVIDER_DEPENDENT_NUMBER,
    SHM_SIZE_PROVIDER_DEPENDENT_STRING, SYSCTLS_DUPLICATE_ITEM, SYSCTLS_EMPTY_KEY, SYSCTLS_EXPECTED_FORM,
    SYSCTLS_EXPECTED_SCALAR, SYSCTLS_EXPECTED_STRING, SecretDefinition, SelinuxRelabel, ServiceNetwork,
    ServiceNetworks, ShmSize, ShmSizeKind, ShmSizeScalarKind, ShortDevice, ShortExtraHost, ShortPort, ShortVolumeMount,
    StopGracePeriod, TMPFS_EXPECTED_FORM, TMPFS_EXPECTED_STRING, TMPFS_PROVIDER_DEPENDENT, TmpfsItem, TmpfsItemKind,
    ULIMIT_INVALID_NAME, ULIMIT_INVALID_VALUE, ULIMIT_MISSING_RANGE_MEMBER, UserNamespaceMode, UserSpec,
    VolumeDefinition, VolumeMount, valid_ulimit_name,
};
use crate::profiles::ProfileSelection;
use crate::resolution::{SELECTION_PROJECT_MISMATCH, service_in_scope};
use crate::source::{SourceId, SourceSpan};
use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};

/// A value in the merged project has an unexpected mapping, sequence, scalar, or null form.
pub const PROJECT_EXPECTED_FORM: DiagnosticCode = DiagnosticCode::new("compose.project.expected-form");

/// A required field is absent from a merged native value.
pub const PROJECT_MISSING_FIELD: DiagnosticCode = DiagnosticCode::new("compose.project.missing-field");

/// A scalar cannot be represented by the requested native value type.
pub const PROJECT_INVALID_VALUE: DiagnosticCode = DiagnosticCode::new("compose.project.invalid-value");

/// A typed value together with every source span that contributed to it during merging.
#[derive(Clone, PartialEq, Eq)]
pub struct ProjectValue<T> {
    value: T,
    provenance: MergeProvenance,
    sensitive: bool,
}

impl<T: fmt::Debug> fmt::Debug for ProjectValue<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = formatter.debug_struct("ProjectValue");
        if self.sensitive {
            debug.field("value", &"<redacted>");
        } else {
            debug.field("value", &self.value);
        }
        debug
            .field("provenance", &self.provenance)
            .field("sensitive", &self.sensitive)
            .finish()
    }
}

impl<T> ProjectValue<T> {
    fn new(value: T, source: &MergedValue) -> Self {
        Self {
            value,
            provenance: source.provenance().clone(),
            sensitive: source.is_sensitive(),
        }
    }

    /// Returns the typed effective value.
    #[must_use]
    pub const fn value(&self) -> &T {
        &self.value
    }

    /// Returns the merge operation and contributing spans in processing order.
    #[must_use]
    pub const fn provenance(&self) -> &MergeProvenance {
        &self.provenance
    }

    /// Returns the most recent source contributing to this value.
    #[must_use]
    pub fn effective_source(&self) -> Option<SourceSpan> {
        self.provenance.effective_source()
    }

    /// Reports whether this value contains sensitive interpolation output.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.sensitive
    }

    /// Removes the provenance wrapper and returns the typed value.
    #[must_use]
    pub fn into_value(self) -> T {
        self.value
    }
}

/// A merged mapping key and every location at which that key was authored.
#[derive(Clone, PartialEq, Eq)]
pub struct ProjectKey {
    value: String,
    sources: Vec<SourceSpan>,
    sensitive: bool,
}

impl fmt::Debug for ProjectKey {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ProjectKey")
            .field("value", &if self.sensitive { "<redacted>" } else { &self.value })
            .field("sources", &self.sources)
            .field("sensitive", &self.sensitive)
            .finish()
    }
}

impl ProjectKey {
    fn from_entry(entry: &MergedEntry) -> Self {
        Self {
            value: entry.key().to_owned(),
            sources: entry.key_sources().to_vec(),
            sensitive: entry.is_key_sensitive(),
        }
    }

    fn from_value(value: String, source: &MergedValue) -> Self {
        Self {
            value,
            sources: source.provenance().sources().to_vec(),
            sensitive: source.is_sensitive(),
        }
    }

    /// Returns the semantic key text.
    #[must_use]
    pub fn value(&self) -> &str {
        &self.value
    }

    /// Returns authored key locations in merge order.
    #[must_use]
    pub fn sources(&self) -> &[SourceSpan] {
        &self.sources
    }

    /// Returns the effective key location.
    #[must_use]
    pub fn effective_source(&self) -> Option<SourceSpan> {
        self.sources.last().copied()
    }

    /// Reports whether interpolation inserted sensitive content into this semantic key.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.sensitive
    }
}

/// One effective service dependency with source-aware long-form options.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectServiceDependency {
    service: ProjectKey,
    condition: Option<ProjectValue<DependencyCondition>>,
    restart: Option<ProjectValue<BooleanValue>>,
    required: Option<ProjectValue<BooleanValue>>,
    unmodeled_fields: Vec<ProjectFieldReference>,
}

impl ProjectServiceDependency {
    /// Returns the referenced service name and all contributing name locations.
    #[must_use]
    pub const fn service(&self) -> &ProjectKey {
        &self.service
    }

    /// Returns the explicitly authored readiness condition.
    #[must_use]
    pub const fn condition(&self) -> Option<&ProjectValue<DependencyCondition>> {
        self.condition.as_ref()
    }

    /// Returns whether Compose-controlled dependency updates restart this service.
    #[must_use]
    pub const fn restart(&self) -> Option<&ProjectValue<BooleanValue>> {
        self.restart.as_ref()
    }

    /// Returns whether the dependency is required.
    #[must_use]
    pub const fn required(&self) -> Option<&ProjectValue<BooleanValue>> {
        self.required.as_ref()
    }

    /// Returns retained long-form fields outside the typed dependency boundary.
    #[must_use]
    pub fn unmodeled_fields(&self) -> &[ProjectFieldReference] {
        &self.unmodeled_fields
    }
}

/// Effective service dependencies with the short or long Compose form retained.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProjectDependsOn {
    /// A sequence of service names using Compose defaults.
    Short(Vec<ProjectValue<ProjectServiceDependency>>),
    /// A mapping of service names to dependency options.
    Long(Vec<ProjectValue<ProjectServiceDependency>>),
}

impl ProjectDependsOn {
    /// Returns dependencies in effective merge order.
    #[must_use]
    pub fn services(&self) -> &[ProjectValue<ProjectServiceDependency>] {
        match self {
            Self::Short(services) | Self::Long(services) => services,
        }
    }

    /// Reports whether the effective field uses long mapping syntax.
    #[must_use]
    pub const fn is_long(&self) -> bool {
        matches!(self, Self::Long(_))
    }
}

/// A field retained by the merged tree but outside the first native project-view boundary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectFieldReference {
    path: Vec<String>,
    key: ProjectKey,
    provenance: MergeProvenance,
    extension: bool,
    sensitive: bool,
}

impl ProjectFieldReference {
    /// Returns the semantic path including the field name.
    #[must_use]
    pub fn path(&self) -> &[String] {
        &self.path
    }

    /// Returns the retained mapping key and all of its source locations.
    #[must_use]
    pub const fn key(&self) -> &ProjectKey {
        &self.key
    }

    /// Returns the field value's complete merge provenance.
    #[must_use]
    pub const fn provenance(&self) -> &MergeProvenance {
        &self.provenance
    }

    /// Reports whether the field name starts with `x-`.
    #[must_use]
    pub const fn is_extension(&self) -> bool {
        self.extension
    }

    /// Reports whether the retained value contains sensitive interpolation output.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.sensitive
    }
}

/// One effective environment variable after field-specific multi-file merging.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectEnvironmentEntry {
    name: ProjectKey,
    value: ProjectValue<ComposeScalar>,
    syntax: EntrySyntax,
}

impl ProjectEnvironmentEntry {
    /// Returns the variable name and its contributing key spans.
    #[must_use]
    pub const fn name(&self) -> &ProjectKey {
        &self.name
    }

    /// Returns the effective scalar, including a distinct host-environment null value.
    #[must_use]
    pub const fn value(&self) -> &ProjectValue<ComposeScalar> {
        &self.value
    }

    /// Returns the most recent mapping or list syntax contributing this entry.
    #[must_use]
    pub const fn syntax(&self) -> EntrySyntax {
        self.syntax
    }
}

/// A normalized-by-key environment view that retains each entry's authored syntax form.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectEnvironment {
    entries: Vec<ProjectEnvironmentEntry>,
}

/// One effective service environment-file entry with syntax and item provenance retained.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProjectEnvironmentFile {
    /// Scalar path syntax.
    Short(String),
    /// Mapping syntax with field-level provenance.
    Long(Box<ProjectLongEnvironmentFile>),
}

/// Effective long-syntax service environment-file options.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectLongEnvironmentFile {
    path: Option<ProjectValue<String>>,
    required: Option<ProjectValue<BooleanValue>>,
    format: Option<ProjectValue<EnvironmentFileFormat>>,
    unmodeled_fields: Vec<ProjectFieldReference>,
}

impl ProjectLongEnvironmentFile {
    /// Returns the required environment-file path.
    #[must_use]
    pub const fn path(&self) -> Option<&ProjectValue<String>> {
        self.path.as_ref()
    }

    /// Returns the explicit required-file choice; absence means Compose's default `true`.
    #[must_use]
    pub const fn required(&self) -> Option<&ProjectValue<BooleanValue>> {
        self.required.as_ref()
    }

    /// Returns the explicit parser format; absence means Compose's default format.
    #[must_use]
    pub const fn format(&self) -> Option<&ProjectValue<EnvironmentFileFormat>> {
        self.format.as_ref()
    }

    /// Returns retained long-form fields outside the typed project-view boundary.
    #[must_use]
    pub fn unmodeled_fields(&self) -> &[ProjectFieldReference] {
        &self.unmodeled_fields
    }
}

/// One effective service metadata label after field-specific multi-file merging.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectLabelEntry {
    name: ProjectKey,
    value: ProjectValue<ComposeScalar>,
    syntax: EntrySyntax,
}

impl ProjectLabelEntry {
    /// Returns the label name and its contributing key spans.
    #[must_use]
    pub const fn name(&self) -> &ProjectKey {
        &self.name
    }

    /// Returns the effective label scalar.
    ///
    /// A key-only list entry has an explicit empty-string value while retaining
    /// [`EntrySyntax::ListKeyOnly`] as its authored form.
    #[must_use]
    pub const fn value(&self) -> &ProjectValue<ComposeScalar> {
        &self.value
    }

    /// Returns the most recent mapping or list syntax contributing this entry.
    #[must_use]
    pub const fn syntax(&self) -> EntrySyntax {
        self.syntax
    }
}

/// A normalized-by-key service-label view retaining each entry's effective syntax.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectLabels {
    entries: Vec<ProjectLabelEntry>,
}

impl ProjectLabels {
    /// Returns labels in effective merge order.
    #[must_use]
    pub fn entries(&self) -> &[ProjectLabelEntry] {
        &self.entries
    }

    /// Finds an effective label by name.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&ProjectLabelEntry> {
        self.entries.iter().find(|entry| entry.name.value == name)
    }
}

/// One effective hostname-to-address mapping after field-specific project merging.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectExtraHost {
    hostname: ProjectKey,
    address: ProjectValue<HostAddress>,
    syntax: EntrySyntax,
}

impl ProjectExtraHost {
    /// Returns the hostname and every contributing source location.
    #[must_use]
    pub const fn hostname(&self) -> &ProjectKey {
        &self.hostname
    }

    /// Returns the raw-preserving IP address or implementation token.
    #[must_use]
    pub const fn address(&self) -> &ProjectValue<HostAddress> {
        &self.address
    }

    /// Returns the most recent mapping or list syntax contributing this entry.
    #[must_use]
    pub const fn syntax(&self) -> EntrySyntax {
        self.syntax
    }
}

/// Ordered effective `extra_hosts` entries with field and item provenance.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectExtraHosts {
    entries: Vec<ProjectExtraHost>,
}

impl ProjectExtraHosts {
    /// Returns host mappings in effective merge order.
    #[must_use]
    pub fn entries(&self) -> &[ProjectExtraHost] {
        &self.entries
    }
}

impl ProjectEnvironment {
    /// Returns environment variables in effective merge order.
    #[must_use]
    pub fn entries(&self) -> &[ProjectEnvironmentEntry] {
        &self.entries
    }

    /// Finds an effective environment variable by name.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&ProjectEnvironmentEntry> {
        self.entries.iter().find(|entry| entry.name.value == name)
    }
}

/// One effective service health check with field-level merge provenance.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectHealthcheck {
    test: Option<ProjectValue<HealthcheckTest>>,
    interval: Option<ProjectValue<HealthcheckDuration>>,
    timeout: Option<ProjectValue<HealthcheckDuration>>,
    retries: Option<ProjectValue<HealthcheckRetries>>,
    start_period: Option<ProjectValue<HealthcheckDuration>>,
    start_interval: Option<ProjectValue<HealthcheckDuration>>,
    disable: Option<ProjectValue<BooleanValue>>,
    unmodeled_fields: Vec<ProjectFieldReference>,
}

/// Effective long-form service config or secret grant with field-level merge provenance.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectLongGrant {
    source: Option<ProjectValue<String>>,
    target: Option<ProjectValue<String>>,
    uid: Option<ProjectValue<String>>,
    gid: Option<ProjectValue<String>>,
    mode: Option<ProjectValue<String>>,
    unmodeled_fields: Vec<ProjectFieldReference>,
}

impl ProjectLongGrant {
    /// Returns the referenced top-level resource name.
    #[must_use]
    pub const fn source(&self) -> Option<&ProjectValue<String>> {
        self.source.as_ref()
    }

    /// Returns the requested container path or name.
    #[must_use]
    pub const fn target(&self) -> Option<&ProjectValue<String>> {
        self.target.as_ref()
    }

    /// Returns the requested container user-ID spelling.
    #[must_use]
    pub const fn uid(&self) -> Option<&ProjectValue<String>> {
        self.uid.as_ref()
    }

    /// Returns the requested container group-ID spelling.
    #[must_use]
    pub const fn gid(&self) -> Option<&ProjectValue<String>> {
        self.gid.as_ref()
    }

    /// Returns the requested permission-mode spelling.
    #[must_use]
    pub const fn mode(&self) -> Option<&ProjectValue<String>> {
        self.mode.as_ref()
    }

    /// Returns retained long-form fields outside the typed project-view boundary.
    #[must_use]
    pub fn unmodeled_fields(&self) -> &[ProjectFieldReference] {
        &self.unmodeled_fields
    }
}

/// One effective service config or secret grant with its Compose syntax form retained.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProjectGrant {
    /// Resource-name short syntax.
    Short(String),
    /// Mapping-based long syntax.
    Long(Box<ProjectLongGrant>),
}

/// Effective long-form service device with nested merge provenance retained.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectLongDevice {
    source: Option<ProjectValue<String>>,
    target: Option<ProjectValue<String>>,
    permissions: Option<ProjectValue<String>>,
    extension_fields: Vec<ProjectFieldReference>,
    unknown_fields: Vec<ProjectFieldReference>,
}

impl ProjectLongDevice {
    /// Returns the required raw source when it was valid and present.
    #[must_use]
    pub const fn source(&self) -> Option<&ProjectValue<String>> {
        self.source.as_ref()
    }

    /// Returns the optional raw target without path interpretation.
    #[must_use]
    pub const fn target(&self) -> Option<&ProjectValue<String>> {
        self.target.as_ref()
    }

    /// Returns the optional raw permissions string without validating runtime meaning.
    #[must_use]
    pub const fn permissions(&self) -> Option<&ProjectValue<String>> {
        self.permissions.as_ref()
    }

    /// Returns retained `x-` options with their complete source evidence.
    #[must_use]
    pub fn extension_fields(&self) -> &[ProjectFieldReference] {
        &self.extension_fields
    }

    /// Returns unrecognized long-form options with their complete source evidence.
    #[must_use]
    pub fn unknown_fields(&self) -> &[ProjectFieldReference] {
        &self.unknown_fields
    }
}

/// One effective service device with short and long syntax kept distinct.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProjectDevice {
    /// A raw short scalar, including path, CDI, deferred, and opaque spellings.
    Short(ShortDevice),
    /// A mapping-form device whose nested values retain their own provenance.
    Long(ProjectLongDevice),
}

impl ProjectHealthcheck {
    /// Returns the effective health command without collapsing scalar and list forms.
    #[must_use]
    pub const fn test(&self) -> Option<&ProjectValue<HealthcheckTest>> {
        self.test.as_ref()
    }

    /// Returns the effective regular-check interval.
    #[must_use]
    pub const fn interval(&self) -> Option<&ProjectValue<HealthcheckDuration>> {
        self.interval.as_ref()
    }

    /// Returns the effective per-check timeout.
    #[must_use]
    pub const fn timeout(&self) -> Option<&ProjectValue<HealthcheckDuration>> {
        self.timeout.as_ref()
    }

    /// Returns the effective unhealthy retry count.
    #[must_use]
    pub const fn retries(&self) -> Option<&ProjectValue<HealthcheckRetries>> {
        self.retries.as_ref()
    }

    /// Returns the effective startup grace period.
    #[must_use]
    pub const fn start_period(&self) -> Option<&ProjectValue<HealthcheckDuration>> {
        self.start_period.as_ref()
    }

    /// Returns the effective interval used during the startup grace period.
    #[must_use]
    pub const fn start_interval(&self) -> Option<&ProjectValue<HealthcheckDuration>> {
        self.start_interval.as_ref()
    }

    /// Returns whether the image health check is explicitly disabled.
    #[must_use]
    pub const fn disable(&self) -> Option<&ProjectValue<BooleanValue>> {
        self.disable.as_ref()
    }

    /// Reports whether the effective definition explicitly disables health checks.
    #[must_use]
    pub fn is_disabled(&self) -> bool {
        matches!(
            self.disable.as_ref().map(ProjectValue::value),
            Some(BooleanValue::Literal(true))
        ) || matches!(
            self.test.as_ref().and_then(|test| test.value().kind()),
            Some(HealthcheckTestKind::None)
        )
    }

    /// Returns retained health-check fields outside the typed project-view boundary.
    #[must_use]
    pub fn unmodeled_fields(&self) -> &[ProjectFieldReference] {
        &self.unmodeled_fields
    }
}

/// Effective service-level `tmpfs` syntax with per-item merge provenance retained.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProjectTmpfs {
    /// One effective scalar declaration.
    Scalar(ProjectValue<TmpfsItem>),
    /// One effective list, including an explicit empty or reset list.
    List(Vec<ProjectValue<TmpfsItem>>),
}

/// One effective ulimit scalar with authored spelling and YAML scalar kind retained.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectUlimitScalar {
    authored: String,
    value: LimitValue,
    kind: MergedScalarKind,
}

impl ProjectUlimitScalar {
    /// Returns the exact authored scalar spelling before optional interpolation.
    #[must_use]
    pub fn authored(&self) -> &str {
        &self.authored
    }

    /// Returns the classified effective spelling after optional interpolation.
    #[must_use]
    pub const fn value(&self) -> &LimitValue {
        &self.value
    }

    /// Returns whether the authored YAML scalar was a string or number.
    #[must_use]
    pub const fn kind(&self) -> MergedScalarKind {
        self.kind
    }
}

/// Effective long-syntax ulimit members with independent merge provenance.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectUlimitRange {
    soft: Option<ProjectValue<ProjectUlimitScalar>>,
    hard: Option<ProjectValue<ProjectUlimitScalar>>,
    unmodeled_fields: Vec<ProjectFieldReference>,
}

impl ProjectUlimitRange {
    /// Returns the effective soft limit, or `None` when the required member was omitted or malformed.
    #[must_use]
    pub const fn soft(&self) -> Option<&ProjectValue<ProjectUlimitScalar>> {
        self.soft.as_ref()
    }

    /// Returns the effective hard limit, or `None` when the required member was omitted or malformed.
    #[must_use]
    pub const fn hard(&self) -> Option<&ProjectValue<ProjectUlimitScalar>> {
        self.hard.as_ref()
    }

    /// Returns retained range fields outside the `soft` and `hard` boundary.
    #[must_use]
    pub fn unmodeled_fields(&self) -> &[ProjectFieldReference] {
        &self.unmodeled_fields
    }
}

/// The effective single or soft/hard form of one named ulimit.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProjectUlimitValue {
    /// One scalar applies to both the soft and hard limit.
    Single(ProjectValue<ProjectUlimitScalar>),
    /// Soft and hard members remain independently source-aware.
    Range(ProjectUlimitRange),
}

/// One ordered effective named ulimit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectUlimit {
    name: ProjectKey,
    value: ProjectUlimitValue,
}

impl ProjectUlimit {
    /// Returns the lowercase limit name and every authored key location.
    #[must_use]
    pub const fn name(&self) -> &ProjectKey {
        &self.name
    }

    /// Returns the effective single or soft/hard form.
    #[must_use]
    pub const fn value(&self) -> &ProjectUlimitValue {
        &self.value
    }
}

/// Effective service `ulimits`, including an explicitly empty or reset mapping.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectUlimits {
    entries: Vec<ProjectValue<ProjectUlimit>>,
}

impl ProjectUlimits {
    /// Returns named limits in effective mapping order.
    #[must_use]
    pub fn entries(&self) -> &[ProjectValue<ProjectUlimit>] {
        &self.entries
    }

    /// Reports whether the effective mapping is explicitly empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

/// One effective mapping-form service sysctl with key and scalar-value provenance.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectSysctl {
    name: ProjectKey,
    value: ProjectValue<ComposeScalar>,
}

impl ProjectSysctl {
    /// Returns the exact sysctl name and every authored key location.
    #[must_use]
    pub const fn name(&self) -> &ProjectKey {
        &self.name
    }

    /// Returns the exact scalar kind and spelling with complete merge provenance.
    #[must_use]
    pub const fn value(&self) -> &ProjectValue<ComposeScalar> {
        &self.value
    }
}

/// Effective service `sysctls` with mapping/list form and per-entry provenance retained.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProjectSysctls {
    /// Ordered mapping entries merged by exact key.
    Map(Vec<ProjectValue<ProjectSysctl>>),
    /// Ordered list items appended without implicit deduplication.
    List(Vec<ProjectValue<String>>),
}

/// One selected service with the native fields needed by the first conversion boundary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectService {
    name: ProjectKey,
    provenance: MergeProvenance,
    hostname: Option<ProjectValue<Hostname>>,
    container_name: Option<ProjectValue<String>>,
    image: Option<ProjectValue<ImageReference>>,
    entrypoint: Option<ProjectValue<Entrypoint>>,
    command: Option<ProjectValue<Command>>,
    init: Option<ProjectValue<BooleanValue>>,
    environment: Option<ProjectValue<ProjectEnvironment>>,
    environment_files: Option<ProjectValue<Vec<ProjectValue<ProjectEnvironmentFile>>>>,
    labels: Option<ProjectValue<ProjectLabels>>,
    extra_hosts: Option<ProjectValue<ProjectExtraHosts>>,
    user: Option<ProjectValue<UserSpec>>,
    userns_mode: Option<ProjectValue<UserNamespaceMode>>,
    group_add: Option<ProjectValue<Vec<ProjectValue<String>>>>,
    cap_add: Option<ProjectValue<Vec<ProjectValue<CapabilityAddItem>>>>,
    cap_drop: Option<ProjectValue<Vec<ProjectValue<CapabilityDropItem>>>>,
    devices: Option<ProjectValue<Vec<ProjectValue<ProjectDevice>>>>,
    working_dir: Option<ProjectValue<String>>,
    read_only: Option<ProjectValue<BooleanValue>>,
    pids_limit: Option<ProjectValue<PidsLimit>>,
    shm_size: Option<ProjectValue<ShmSize>>,
    mem_limit: Option<ProjectValue<MemLimit>>,
    tmpfs: Option<ProjectValue<ProjectTmpfs>>,
    sysctls: Option<ProjectValue<ProjectSysctls>>,
    ulimits: Option<ProjectValue<ProjectUlimits>>,
    pull_policy: Option<ProjectValue<PullPolicy>>,
    restart: Option<ProjectValue<RestartPolicy>>,
    stop_signal: Option<ProjectValue<String>>,
    stop_grace_period: Option<ProjectValue<StopGracePeriod>>,
    healthcheck: Option<ProjectValue<ProjectHealthcheck>>,
    depends_on: Option<ProjectValue<ProjectDependsOn>>,
    ports: Option<ProjectValue<Vec<ProjectValue<Port>>>>,
    volumes: Option<ProjectValue<Vec<ProjectValue<VolumeMount>>>>,
    configs: Option<ProjectValue<Vec<ProjectValue<ProjectGrant>>>>,
    secrets: Option<ProjectValue<Vec<ProjectValue<ProjectGrant>>>>,
    networks: Option<ProjectValue<ServiceNetworks>>,
    profiles: Option<ProjectValue<Vec<ProjectValue<String>>>>,
    unmodeled_fields: Vec<ProjectFieldReference>,
}

impl ProjectService {
    fn from_entry(entry: &MergedEntry) -> Self {
        Self {
            name: ProjectKey::from_entry(entry),
            provenance: entry.value().provenance().clone(),
            hostname: None,
            container_name: None,
            image: None,
            entrypoint: None,
            command: None,
            init: None,
            environment: None,
            environment_files: None,
            labels: None,
            extra_hosts: None,
            user: None,
            userns_mode: None,
            group_add: None,
            cap_add: None,
            cap_drop: None,
            devices: None,
            working_dir: None,
            read_only: None,
            pids_limit: None,
            shm_size: None,
            mem_limit: None,
            tmpfs: None,
            sysctls: None,
            ulimits: None,
            pull_policy: None,
            restart: None,
            stop_signal: None,
            stop_grace_period: None,
            healthcheck: None,
            depends_on: None,
            ports: None,
            volumes: None,
            configs: None,
            secrets: None,
            networks: None,
            profiles: None,
            unmodeled_fields: Vec::new(),
        }
    }

    /// Returns the service name and all contributing key spans.
    #[must_use]
    pub const fn name(&self) -> &ProjectKey {
        &self.name
    }

    /// Returns provenance for the complete effective service mapping.
    #[must_use]
    pub const fn provenance(&self) -> &MergeProvenance {
        &self.provenance
    }

    /// Returns the effective raw-preserving service hostname.
    #[must_use]
    pub const fn hostname(&self) -> Option<&ProjectValue<Hostname>> {
        self.hostname.as_ref()
    }

    /// Returns the effective explicit runtime container name.
    #[must_use]
    pub const fn container_name(&self) -> Option<&ProjectValue<String>> {
        self.container_name.as_ref()
    }

    /// Returns the effective image reference.
    #[must_use]
    pub const fn image(&self) -> Option<&ProjectValue<ImageReference>> {
        self.image.as_ref()
    }

    /// Returns the effective entrypoint without normalizing scalar and list forms.
    #[must_use]
    pub const fn entrypoint(&self) -> Option<&ProjectValue<Entrypoint>> {
        self.entrypoint.as_ref()
    }

    /// Returns the effective command without normalizing scalar and list forms.
    #[must_use]
    pub const fn command(&self) -> Option<&ProjectValue<Command>> {
        self.command.as_ref()
    }

    /// Returns the effective platform-specific init-process choice.
    #[must_use]
    pub const fn init(&self) -> Option<&ProjectValue<BooleanValue>> {
        self.init.as_ref()
    }

    /// Returns environment entries normalized by key with per-entry syntax retained.
    #[must_use]
    pub const fn environment(&self) -> Option<&ProjectValue<ProjectEnvironment>> {
        self.environment.as_ref()
    }

    /// Returns effective service environment files in merge order with per-item provenance.
    #[must_use]
    pub const fn environment_files(&self) -> Option<&ProjectValue<Vec<ProjectValue<ProjectEnvironmentFile>>>> {
        self.environment_files.as_ref()
    }

    /// Returns effective service labels normalized by key with entry syntax retained.
    #[must_use]
    pub const fn labels(&self) -> Option<&ProjectValue<ProjectLabels>> {
        self.labels.as_ref()
    }

    /// Returns effective service host mappings with per-entry provenance and syntax.
    #[must_use]
    pub const fn extra_hosts(&self) -> Option<&ProjectValue<ProjectExtraHosts>> {
        self.extra_hosts.as_ref()
    }

    /// Returns the effective container user and optional group spelling.
    #[must_use]
    pub const fn user(&self) -> Option<&ProjectValue<UserSpec>> {
        self.user.as_ref()
    }

    /// Returns the effective user-namespace mode.
    #[must_use]
    pub const fn userns_mode(&self) -> Option<&ProjectValue<UserNamespaceMode>> {
        self.userns_mode.as_ref()
    }

    /// Returns supplementary groups in effective merge order.
    #[must_use]
    pub const fn group_add(&self) -> Option<&ProjectValue<Vec<ProjectValue<String>>>> {
        self.group_add.as_ref()
    }

    /// Returns the effective capability-add sequence with full field and per-item provenance.
    ///
    /// `None` means the field was omitted; `Some` with an empty vector means it was explicitly
    /// configured empty or reset.
    #[must_use]
    pub const fn cap_add(&self) -> Option<&ProjectValue<Vec<ProjectValue<CapabilityAddItem>>>> {
        self.cap_add.as_ref()
    }

    /// Returns the effective capability-drop sequence with full field and per-item provenance.
    ///
    /// `None` means the field was omitted; `Some` with an empty vector means it was explicitly
    /// configured empty or reset.
    #[must_use]
    pub const fn cap_drop(&self) -> Option<&ProjectValue<Vec<ProjectValue<CapabilityDropItem>>>> {
        self.cap_drop.as_ref()
    }

    /// Returns effective ordered mixed short/long service devices with complete provenance.
    ///
    /// `None` means omission; `Some` with an empty vector means an explicit empty sequence or reset.
    #[must_use]
    pub const fn devices(&self) -> Option<&ProjectValue<Vec<ProjectValue<ProjectDevice>>>> {
        self.devices.as_ref()
    }

    /// Returns the effective container working-directory override.
    #[must_use]
    pub const fn working_dir(&self) -> Option<&ProjectValue<String>> {
        self.working_dir.as_ref()
    }

    /// Returns the effective read-only root-filesystem choice.
    #[must_use]
    pub const fn read_only(&self) -> Option<&ProjectValue<BooleanValue>> {
        self.read_only.as_ref()
    }

    /// Returns the effective raw-preserving service PID limit.
    #[must_use]
    pub const fn pids_limit(&self) -> Option<&ProjectValue<PidsLimit>> {
        self.pids_limit.as_ref()
    }

    /// Returns the effective raw-preserving service shared-memory size.
    #[must_use]
    pub const fn shm_size(&self) -> Option<&ProjectValue<ShmSize>> {
        self.shm_size.as_ref()
    }

    /// Returns the effective raw-preserving service memory limit.
    #[must_use]
    pub const fn mem_limit(&self) -> Option<&ProjectValue<MemLimit>> {
        self.mem_limit.as_ref()
    }

    /// Returns effective service-level temporary filesystems with source form and provenance.
    #[must_use]
    pub const fn tmpfs(&self) -> Option<&ProjectValue<ProjectTmpfs>> {
        self.tmpfs.as_ref()
    }

    /// Returns effective service sysctls with source form and per-entry provenance.
    #[must_use]
    pub const fn sysctls(&self) -> Option<&ProjectValue<ProjectSysctls>> {
        self.sysctls.as_ref()
    }

    /// Returns effective ordered service limits with nested and field-level merge provenance.
    ///
    /// `None` means the field was omitted; an empty mapping remains present and can carry reset or
    /// override provenance.
    #[must_use]
    pub const fn ulimits(&self) -> Option<&ProjectValue<ProjectUlimits>> {
        self.ulimits.as_ref()
    }

    /// Returns the effective raw-preserving service image pull policy.
    #[must_use]
    pub const fn pull_policy(&self) -> Option<&ProjectValue<PullPolicy>> {
        self.pull_policy.as_ref()
    }

    /// Returns the effective service-level container restart policy.
    #[must_use]
    pub const fn restart(&self) -> Option<&ProjectValue<RestartPolicy>> {
        self.restart.as_ref()
    }

    /// Returns the effective explicitly authored service stop signal.
    #[must_use]
    pub const fn stop_signal(&self) -> Option<&ProjectValue<String>> {
        self.stop_signal.as_ref()
    }

    /// Returns the effective raw-preserving service stop grace period.
    #[must_use]
    pub const fn stop_grace_period(&self) -> Option<&ProjectValue<StopGracePeriod>> {
        self.stop_grace_period.as_ref()
    }

    /// Returns the effective health check with per-field merge provenance.
    #[must_use]
    pub const fn healthcheck(&self) -> Option<&ProjectValue<ProjectHealthcheck>> {
        self.healthcheck.as_ref()
    }

    /// Returns effective service dependencies with authored form and field-level provenance.
    #[must_use]
    pub const fn depends_on(&self) -> Option<&ProjectValue<ProjectDependsOn>> {
        self.depends_on.as_ref()
    }

    /// Returns the effective port collection and per-item provenance.
    #[must_use]
    pub const fn ports(&self) -> Option<&ProjectValue<Vec<ProjectValue<Port>>>> {
        self.ports.as_ref()
    }

    /// Returns the effective volume-mount collection and per-item provenance.
    #[must_use]
    pub const fn volumes(&self) -> Option<&ProjectValue<Vec<ProjectValue<VolumeMount>>>> {
        self.volumes.as_ref()
    }

    /// Returns effective service config grants with syntax and field-level provenance retained.
    #[must_use]
    pub const fn configs(&self) -> Option<&ProjectValue<Vec<ProjectValue<ProjectGrant>>>> {
        self.configs.as_ref()
    }

    /// Returns effective service secret grants with syntax and field-level provenance retained.
    #[must_use]
    pub const fn secrets(&self) -> Option<&ProjectValue<Vec<ProjectValue<ProjectGrant>>>> {
        self.secrets.as_ref()
    }

    /// Returns effective network attachments with short and long forms retained.
    #[must_use]
    pub const fn networks(&self) -> Option<&ProjectValue<ServiceNetworks>> {
        self.networks.as_ref()
    }

    /// Returns effective profile names and their individual provenance.
    #[must_use]
    pub const fn profiles(&self) -> Option<&ProjectValue<Vec<ProjectValue<String>>>> {
        self.profiles.as_ref()
    }

    /// Returns fields retained outside this initial native project-view boundary.
    #[must_use]
    pub fn unmodeled_fields(&self) -> &[ProjectFieldReference] {
        &self.unmodeled_fields
    }
}

/// One named top-level resource with key and definition provenance kept separately.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectResource<T> {
    name: ProjectKey,
    definition: ProjectValue<T>,
}

impl<T> ProjectResource<T> {
    /// Returns the model name and all authored key locations.
    #[must_use]
    pub const fn name(&self) -> &ProjectKey {
        &self.name
    }

    /// Returns the native effective definition and its merge provenance.
    #[must_use]
    pub const fn definition(&self) -> &ProjectValue<T> {
        &self.definition
    }
}

/// The native consumer view of one merged and optionally profile-selected Compose project.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectView {
    source_ids: Vec<SourceId>,
    base_directory: PathBuf,
    provenance: MergeProvenance,
    name: Option<ProjectValue<String>>,
    services: Vec<ProjectService>,
    networks: Vec<ProjectResource<NetworkDefinition>>,
    volumes: Vec<ProjectResource<VolumeDefinition>>,
    configs: Vec<ProjectResource<ConfigDefinition>>,
    secrets: Vec<ProjectResource<SecretDefinition>>,
    unmodeled_fields: Vec<ProjectFieldReference>,
}

impl ProjectView {
    /// Returns source documents in merge order.
    #[must_use]
    pub fn source_ids(&self) -> &[SourceId] {
        &self.source_ids
    }

    /// Returns the project directory inherited from the first loaded document.
    #[must_use]
    pub fn base_directory(&self) -> &Path {
        &self.base_directory
    }

    /// Returns provenance for the complete merged root.
    #[must_use]
    pub const fn provenance(&self) -> &MergeProvenance {
        &self.provenance
    }

    /// Returns the effective explicit project name.
    #[must_use]
    pub const fn name(&self) -> Option<&ProjectValue<String>> {
        self.name.as_ref()
    }

    /// Returns profile-active services in merged order.
    #[must_use]
    pub fn services(&self) -> &[ProjectService] {
        &self.services
    }

    /// Finds one profile-active service.
    #[must_use]
    pub fn service(&self, name: &str) -> Option<&ProjectService> {
        self.services.iter().find(|service| service.name.value == name)
    }

    /// Returns effective top-level network definitions.
    #[must_use]
    pub fn networks(&self) -> &[ProjectResource<NetworkDefinition>] {
        &self.networks
    }

    /// Returns effective top-level volume definitions.
    #[must_use]
    pub fn volumes(&self) -> &[ProjectResource<VolumeDefinition>] {
        &self.volumes
    }

    /// Returns effective top-level config definitions.
    #[must_use]
    pub fn configs(&self) -> &[ProjectResource<ConfigDefinition>] {
        &self.configs
    }

    /// Returns effective top-level secret definitions.
    #[must_use]
    pub fn secrets(&self) -> &[ProjectResource<SecretDefinition>] {
        &self.secrets
    }

    /// Returns root fields retained outside this initial native project-view boundary.
    #[must_use]
    pub fn unmodeled_fields(&self) -> &[ProjectFieldReference] {
        &self.unmodeled_fields
    }
}

/// Recoverable result of building a typed merged project view.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectViewResult {
    view: Option<ProjectView>,
    diagnostics: Vec<Diagnostic>,
}

impl ProjectViewResult {
    /// Returns the typed view when the profile selection belongs to the project.
    #[must_use]
    pub const fn view(&self) -> Option<&ProjectView> {
        self.view.as_ref()
    }

    /// Returns project-view diagnostics in traversal order.
    #[must_use]
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }

    /// Reports whether a view exists and contains no error diagnostics.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        self.view.is_some()
            && self
                .diagnostics
                .iter()
                .all(|diagnostic| diagnostic.severity() != Severity::Error)
    }

    /// Separates the view and diagnostics.
    #[must_use]
    pub fn into_parts(self) -> (Option<ProjectView>, Vec<Diagnostic>) {
        (self.view, self.diagnostics)
    }
}

/// Builds native values directly from a merged project without canonical rendering or reparsing.
///
/// A matching selection filters inactive services. Omitting it includes every service. The
/// operation performs no file, environment, provider, or runtime access.
#[must_use]
pub fn build_project_view(project: &MergedProject, selection: Option<&ProfileSelection>) -> ProjectViewResult {
    if selection.is_some_and(|selection| !selection.belongs_to(project)) {
        return ProjectViewResult {
            view: None,
            diagnostics: vec![Diagnostic::new(
                SELECTION_PROJECT_MISMATCH,
                Severity::Error,
                "profile selection does not belong to the merged project",
            )],
        };
    }

    Builder::new(project, selection).build()
}

struct Builder<'a> {
    project: &'a MergedProject,
    selection: Option<&'a ProfileSelection>,
    diagnostics: Vec<Diagnostic>,
    root_unmodeled: Vec<ProjectFieldReference>,
    pending_unmodeled: Vec<ProjectFieldReference>,
}

impl<'a> Builder<'a> {
    const fn new(project: &'a MergedProject, selection: Option<&'a ProfileSelection>) -> Self {
        Self {
            project,
            selection,
            diagnostics: Vec::new(),
            root_unmodeled: Vec::new(),
            pending_unmodeled: Vec::new(),
        }
    }

    fn build(mut self) -> ProjectViewResult {
        let root = self.project.root();
        let entries = root.as_mapping().unwrap_or_default();
        let mut name = None;
        let mut services = Vec::new();
        let mut networks = Vec::new();
        let mut volumes = Vec::new();
        let mut configs = Vec::new();
        let mut secrets = Vec::new();

        for entry in entries {
            match entry.key() {
                "name" => name = self.project_string(entry.value(), "project name"),
                "services" => services = self.services(entry.value()),
                "networks" => networks = self.network_definitions(entry.value()),
                "volumes" => volumes = self.volume_definitions(entry.value()),
                "configs" => configs = self.config_definitions(entry.value()),
                "secrets" => secrets = self.secret_definitions(entry.value()),
                _ => self.record_root_unmodeled(&[], entry),
            }
        }

        ProjectViewResult {
            view: Some(ProjectView {
                source_ids: self.project.source_ids().to_vec(),
                base_directory: self.project.base_directory().to_path_buf(),
                provenance: root.provenance().clone(),
                name,
                services,
                networks,
                volumes,
                configs,
                secrets,
                unmodeled_fields: self.root_unmodeled,
            }),
            diagnostics: self.diagnostics,
        }
    }

    fn services(&mut self, value: &MergedValue) -> Vec<ProjectService> {
        let Some(entries) = self.mapping(value, "services must be a mapping") else {
            return Vec::new();
        };
        let selection = self.selection;
        let mut services = Vec::new();
        for entry in entries {
            if service_in_scope(selection, entry.key()) {
                services.extend(self.service(entry));
            }
        }
        services
    }

    fn service(&mut self, entry: &MergedEntry) -> Option<ProjectService> {
        let pending_start = self.pending_unmodeled.len();
        let value = entry.value();
        let fields = self.mapping(value, "service definition must be a mapping")?;
        let mut service = ProjectService::from_entry(entry);
        let path = ["services".to_owned(), entry.key().to_owned()];

        for field in fields {
            match field.key() {
                "hostname" => service.hostname = self.hostname(field.value()),
                "container_name" => {
                    service.container_name = self.project_string(field.value(), "service container name");
                }
                "image" => {
                    service.image = self
                        .project_string(field.value(), "service image")
                        .map(|value| ProjectValue {
                            value: ImageReference::parse(value.value),
                            provenance: value.provenance,
                            sensitive: value.sensitive,
                        });
                }
                "entrypoint" => service.entrypoint = self.entrypoint(field.value()),
                "command" => service.command = self.command(field.value()),
                "init" => {
                    service.init = self
                        .located_boolean(field.value(), "service init must be a boolean")
                        .map(|value| ProjectValue::new(value.into_value(), field.value()));
                }
                "environment" => service.environment = self.environment(field.value()),
                "env_file" => service.environment_files = self.environment_files(field.value(), &path),
                "labels" => service.labels = self.service_labels(field.value()),
                "extra_hosts" => service.extra_hosts = self.extra_hosts(field.value()),
                "user" => service.user = self.user(field.value()),
                "userns_mode" => service.userns_mode = self.userns_mode(field.value()),
                "group_add" => {
                    service.group_add = self.string_collection(field.value(), "group_add must be a sequence");
                }
                "cap_add" => service.cap_add = self.capability_add(field.value()),
                "cap_drop" => service.cap_drop = self.capability_drop(field.value()),
                "devices" => service.devices = self.devices(field.value(), &path),
                "working_dir" => service.working_dir = self.project_string(field.value(), "service working directory"),
                "read_only" => {
                    service.read_only = self
                        .located_boolean(field.value(), "service read_only must be a boolean")
                        .map(|value| ProjectValue::new(value.into_value(), field.value()));
                }
                "pids_limit" => service.pids_limit = self.pids_limit(field.value()),
                "shm_size" => service.shm_size = self.shm_size(field.value()),
                "mem_limit" => service.mem_limit = self.mem_limit(field.value()),
                "tmpfs" => service.tmpfs = self.tmpfs(field.value()),
                "sysctls" => service.sysctls = self.sysctls(field.value()),
                "ulimits" => service.ulimits = self.ulimits(field.value(), &path),
                "pull_policy" => service.pull_policy = self.pull_policy(field.value()),
                "restart" => service.restart = self.restart_policy(field.value()),
                "stop_signal" => {
                    service.stop_signal = self.project_string(field.value(), "service stop signal");
                }
                "stop_grace_period" => {
                    service.stop_grace_period = self.stop_grace_period(field.value());
                }
                "healthcheck" => service.healthcheck = self.healthcheck(field.value(), &path),
                "depends_on" => service.depends_on = self.depends_on(field.value(), &path),
                "ports" => service.ports = self.ports(field.value(), &path),
                "volumes" => service.volumes = self.volumes(field.value(), &path),
                "configs" => service.configs = self.grants(field.value(), &path, "config"),
                "secrets" => service.secrets = self.grants(field.value(), &path, "secret"),
                "networks" => service.networks = self.service_networks(field.value(), &path),
                "profiles" => service.profiles = self.string_collection(field.value(), "profiles must be a sequence"),
                _ => service.unmodeled_fields.push(field_reference(&path, field)),
            }
        }
        service
            .unmodeled_fields
            .extend(self.pending_unmodeled.drain(pending_start..));
        Some(service)
    }

    fn hostname(&mut self, value: &MergedValue) -> Option<ProjectValue<Hostname>> {
        let scalar = match value.kind() {
            MergedValueKind::Scalar(scalar) if scalar.kind() == MergedScalarKind::String => scalar,
            _ => {
                self.expected(value, "hostname must be a YAML string scalar");
                return None;
            }
        };
        let hostname = Hostname::parse(Located::new(scalar.value().to_owned(), effective_span(value)));
        if hostname.kind() == &HostnameKind::Invalid {
            self.invalid(
                effective_span(value),
                "hostname must be an ASCII RFC-1123 name of 1 to 253 characters with dot-separated labels of 1 to 63 alphanumeric or hyphen characters; each label must start and end alphanumeric",
            );
        }
        Some(ProjectValue::new(hostname, value))
    }

    fn restart_policy(&mut self, value: &MergedValue) -> Option<ProjectValue<RestartPolicy>> {
        let policy = RestartPolicy::parse(self.located_string(value, "restart must be a non-null scalar")?);
        if !policy.is_valid() {
            self.invalid(
                effective_span(value),
                "restart must be `no`, `always`, `on-failure[:max-retries]`, or `unless-stopped`",
            );
        }
        Some(ProjectValue::new(policy, value))
    }

    fn pids_limit(&mut self, value: &MergedValue) -> Option<ProjectValue<PidsLimit>> {
        let scalar = match value.kind() {
            MergedValueKind::Scalar(scalar) if scalar.kind() != MergedScalarKind::Boolean => scalar,
            _ => {
                self.expected(value, "pids_limit must be a number or string scalar");
                return None;
            }
        };
        let limit = PidsLimit::parse(Located::new(scalar.value().to_owned(), effective_span(value)));
        match limit.kind() {
            PidsLimitKind::Zero => self.diagnostics.push(
                Diagnostic::new(
                    PIDS_LIMIT_AMBIGUOUS_ZERO,
                    Severity::Warning,
                    "pids_limit zero is preserved as an ambiguous and unportable native state",
                )
                .with_label(DiagnosticLabel::primary(
                    effective_span(value),
                    "ambiguous zero PID limit",
                )),
            ),
            PidsLimitKind::Other => self.invalid(
                effective_span(value),
                "pids_limit must be `-1`, a positive integral decimal, or interpolation",
            ),
            _ => {}
        }
        Some(ProjectValue::new(limit, value))
    }

    fn shm_size(&mut self, value: &MergedValue) -> Option<ProjectValue<ShmSize>> {
        let scalar = match value.kind() {
            MergedValueKind::Scalar(scalar) if scalar.kind() == MergedScalarKind::Number => {
                (scalar, ShmSizeScalarKind::Number)
            }
            MergedValueKind::Scalar(scalar) if scalar.kind() == MergedScalarKind::String => {
                (scalar, ShmSizeScalarKind::String)
            }
            _ => {
                self.diagnostics.push(
                    Diagnostic::new(
                        SHM_SIZE_EXPECTED_VALUE,
                        Severity::Error,
                        "shm_size must be a YAML number or string scalar",
                    )
                    .with_label(DiagnosticLabel::primary(
                        effective_span(value),
                        "unexpected shared-memory-size form",
                    )),
                );
                return None;
            }
        };
        let size = ShmSize::parse(
            Located::new(scalar.0.value().to_owned(), effective_span(value)),
            scalar.1,
        );
        let (code, message, label, note) = match size.kind() {
            ShmSizeKind::Zero { .. } => (
                SHM_SIZE_AMBIGUOUS_ZERO,
                "shm_size zero is preserved because Compose does not define its semantics",
                "ambiguous zero shared-memory size",
                "choose a positive size with an explicit documented lowercase unit",
            ),
            ShmSizeKind::ProviderDependentNumber => (
                SHM_SIZE_PROVIDER_DEPENDENT_NUMBER,
                "numeric shm_size is schema-accepted but lacks a documented explicit unit",
                "provider-dependent numeric shared-memory size",
                "use a positive quoted value with `b`, `k`, `kb`, `m`, `mb`, `g`, or `gb` for portable intent",
            ),
            ShmSizeKind::ProviderDependentString => (
                SHM_SIZE_PROVIDER_DEPENDENT_STRING,
                "string shm_size is schema-accepted but falls outside the documented lowercase suffix family",
                "provider-dependent string shared-memory size",
                "use an explicit lowercase `b`, `k`, `kb`, `m`, `mb`, `g`, or `gb` suffix when that is the intended unit",
            ),
            ShmSizeKind::Documented { .. } | ShmSizeKind::Expression => {
                return Some(ProjectValue::new(size, value));
            }
        };
        self.diagnostics.push(
            Diagnostic::new(code, Severity::Warning, message)
                .with_label(DiagnosticLabel::primary(effective_span(value), label))
                .with_note(note),
        );
        Some(ProjectValue::new(size, value))
    }

    fn mem_limit(&mut self, value: &MergedValue) -> Option<ProjectValue<MemLimit>> {
        let scalar = match value.kind() {
            MergedValueKind::Scalar(scalar) if scalar.kind() == MergedScalarKind::Number => {
                (scalar, MemLimitScalarKind::Number)
            }
            MergedValueKind::Scalar(scalar) if scalar.kind() == MergedScalarKind::String => {
                (scalar, MemLimitScalarKind::String)
            }
            _ => {
                self.diagnostics.push(
                    Diagnostic::new(
                        MEM_LIMIT_EXPECTED_VALUE,
                        Severity::Error,
                        "mem_limit must be a YAML number or string scalar",
                    )
                    .with_label(DiagnosticLabel::primary(
                        effective_span(value),
                        "unexpected memory-limit form",
                    )),
                );
                return None;
            }
        };
        let limit = MemLimit::parse(
            Located::new(scalar.0.value().to_owned(), effective_span(value)),
            scalar.1,
        );
        let (code, message, label, note) = match limit.kind() {
            MemLimitKind::Zero { .. } => (
                MEM_LIMIT_AMBIGUOUS_ZERO,
                "mem_limit zero is preserved without inferring portable runtime behavior",
                "ambiguous zero memory limit",
                "choose a positive size with an explicit documented lowercase unit",
            ),
            MemLimitKind::SchemaNumber => (
                MEM_LIMIT_SCHEMA_NUMBER,
                "numeric mem_limit is schema-accepted but lacks a documented explicit unit",
                "schema-only numeric memory limit",
                "use a positive quoted value with `b`, `k`, `kb`, `m`, `mb`, `g`, or `gb` for explicit intent",
            ),
            MemLimitKind::ProviderDependentString => (
                MEM_LIMIT_PROVIDER_DEPENDENT_STRING,
                "string mem_limit is schema-accepted but falls outside the documented lowercase suffix family",
                "provider-dependent string memory limit",
                "use an explicit lowercase `b`, `k`, `kb`, `m`, `mb`, `g`, or `gb` suffix when that is the intended unit",
            ),
            MemLimitKind::Documented { .. } | MemLimitKind::Expression => {
                return Some(ProjectValue::new(limit, value));
            }
        };
        self.diagnostics.push(
            Diagnostic::new(code, Severity::Warning, message)
                .with_label(DiagnosticLabel::primary(effective_span(value), label))
                .with_note(note),
        );
        Some(ProjectValue::new(limit, value))
    }

    fn tmpfs(&mut self, value: &MergedValue) -> Option<ProjectValue<ProjectTmpfs>> {
        let form = match value.kind() {
            MergedValueKind::Scalar(scalar) if scalar.kind() == MergedScalarKind::String => {
                let item = self.tmpfs_item(value, scalar.value());
                ProjectTmpfs::Scalar(ProjectValue::new(item, value))
            }
            MergedValueKind::Sequence(values) => {
                let mut items = Vec::new();
                for item_value in values {
                    let MergedValueKind::Scalar(scalar) = item_value.kind() else {
                        self.diagnostics.push(
                            Diagnostic::new(
                                TMPFS_EXPECTED_STRING,
                                Severity::Error,
                                "tmpfs entries must be string scalars",
                            )
                            .with_label(DiagnosticLabel::primary(
                                effective_span(item_value),
                                "unexpected temporary-filesystem list item",
                            )),
                        );
                        continue;
                    };
                    if scalar.kind() != MergedScalarKind::String {
                        self.diagnostics.push(
                            Diagnostic::new(
                                TMPFS_EXPECTED_STRING,
                                Severity::Error,
                                "tmpfs entries must be string scalars",
                            )
                            .with_label(DiagnosticLabel::primary(
                                effective_span(item_value),
                                "unexpected temporary-filesystem list item",
                            )),
                        );
                        continue;
                    }
                    let item = self.tmpfs_item(item_value, scalar.value());
                    items.push(ProjectValue::new(item, item_value));
                }
                ProjectTmpfs::List(items)
            }
            _ => {
                self.diagnostics.push(
                    Diagnostic::new(
                        TMPFS_EXPECTED_FORM,
                        Severity::Error,
                        "tmpfs must be a string scalar or a sequence of string scalars",
                    )
                    .with_label(DiagnosticLabel::primary(
                        effective_span(value),
                        "unexpected service-level temporary-filesystem form",
                    )),
                );
                return None;
            }
        };
        Some(ProjectValue::new(form, value))
    }

    fn tmpfs_item(&mut self, source: &MergedValue, raw: &str) -> TmpfsItem {
        let item = TmpfsItem::parse(Located::new(raw.to_owned(), effective_span(source)));
        if item.kind() == TmpfsItemKind::ProviderDependent {
            self.diagnostics.push(
                Diagnostic::new(
                    TMPFS_PROVIDER_DEPENDENT,
                    Severity::Warning,
                    "tmpfs item is malformed or uses provider- or target-specific options",
                )
                .with_label(DiagnosticLabel::primary(
                    effective_span(source),
                    "provider-dependent temporary-filesystem item",
                ))
                .with_note("use a non-empty path with only non-empty `mode`, `uid`, or `gid` assignments for documented portable syntax"),
            );
        }
        item
    }

    fn sysctls(&mut self, value: &MergedValue) -> Option<ProjectValue<ProjectSysctls>> {
        let form = match value.kind() {
            MergedValueKind::Mapping(entries) => ProjectSysctls::Map(self.sysctls_map(entries)),
            MergedValueKind::Sequence(items) => ProjectSysctls::List(self.sysctls_list(items)),
            _ => {
                self.diagnostics.push(
                    Diagnostic::new(
                        SYSCTLS_EXPECTED_FORM,
                        Severity::Error,
                        "sysctls must be a mapping or a sequence of string scalars",
                    )
                    .with_label(DiagnosticLabel::primary(
                        effective_span(value),
                        "unexpected service sysctls form",
                    )),
                );
                return None;
            }
        };
        Some(ProjectValue::new(form, value))
    }

    fn sysctls_map(&mut self, entries: &[MergedEntry]) -> Vec<ProjectValue<ProjectSysctl>> {
        let mut sysctls = Vec::new();
        for entry in entries {
            if entry.key().is_empty() {
                self.diagnostics.push(
                    Diagnostic::new(
                        SYSCTLS_EMPTY_KEY,
                        Severity::Error,
                        "sysctls mapping keys must not be empty",
                    )
                    .with_label(DiagnosticLabel::primary(entry_span(entry), "empty sysctl name")),
                );
                continue;
            }
            let Some(scalar) = self.sysctl_scalar(entry.value()) else {
                continue;
            };
            let sysctl = ProjectSysctl {
                name: ProjectKey::from_entry(entry),
                value: ProjectValue::new(scalar, entry.value()),
            };
            sysctls.push(ProjectValue::new(sysctl, entry.value()));
        }
        sysctls
    }

    fn sysctl_scalar(&mut self, value: &MergedValue) -> Option<ComposeScalar> {
        match value.kind() {
            MergedValueKind::Null(_) => Some(ComposeScalar::Null),
            MergedValueKind::Scalar(scalar) => Some(match scalar.kind() {
                MergedScalarKind::String => ComposeScalar::String(scalar.value().to_owned()),
                MergedScalarKind::Boolean => ComposeScalar::Boolean(scalar.value().eq_ignore_ascii_case("true")),
                MergedScalarKind::Number => ComposeScalar::Number(scalar.value().to_owned()),
            }),
            _ => {
                self.diagnostics.push(
                    Diagnostic::new(
                        SYSCTLS_EXPECTED_SCALAR,
                        Severity::Error,
                        "sysctls mapping values must be scalar strings, numbers, booleans, or null",
                    )
                    .with_label(DiagnosticLabel::primary(
                        effective_span(value),
                        "non-scalar sysctl value",
                    )),
                );
                None
            }
        }
    }

    fn sysctls_list(&mut self, items: &[MergedValue]) -> Vec<ProjectValue<String>> {
        let mut sysctls = Vec::new();
        let mut seen = BTreeMap::new();
        for item in items {
            let MergedValueKind::Scalar(scalar) = item.kind() else {
                self.invalid_sysctl_list_item(item);
                continue;
            };
            if scalar.kind() != MergedScalarKind::String {
                self.invalid_sysctl_list_item(item);
                continue;
            }
            let span = effective_span(item);
            if let Some(first) = seen.get(scalar.value()) {
                self.diagnostics.push(
                    Diagnostic::new(
                        SYSCTLS_DUPLICATE_ITEM,
                        Severity::Error,
                        "effective sysctls list entries must be unique exact strings",
                    )
                    .with_label(DiagnosticLabel::primary(span, "duplicate sysctl string"))
                    .with_label(DiagnosticLabel::secondary(*first, "first identical string")),
                );
            } else {
                seen.insert(scalar.value().to_owned(), span);
            }
            sysctls.push(ProjectValue::new(scalar.value().to_owned(), item));
        }
        sysctls
    }

    fn invalid_sysctl_list_item(&mut self, value: &MergedValue) {
        self.diagnostics.push(
            Diagnostic::new(
                SYSCTLS_EXPECTED_STRING,
                Severity::Error,
                "sysctls list entries must be YAML string scalars",
            )
            .with_label(DiagnosticLabel::primary(
                effective_span(value),
                "non-string sysctl list item",
            )),
        );
    }

    fn ulimits(&mut self, value: &MergedValue, service_path: &[String]) -> Option<ProjectValue<ProjectUlimits>> {
        let Some(entries) = value.as_mapping() else {
            self.expected(value, "ulimits must be a mapping");
            return None;
        };
        let mut limits = Vec::new();
        let mut path = service_path.to_vec();
        path.push("ulimits".to_owned());
        for entry in entries {
            if !valid_ulimit_name(entry.key()) {
                self.diagnostics.push(
                    Diagnostic::new(
                        ULIMIT_INVALID_NAME,
                        Severity::Error,
                        "ulimit names must contain only lowercase ASCII letters",
                    )
                    .with_label(DiagnosticLabel::primary(entry_span(entry), "invalid ulimit name")),
                );
                self.record_pending_unmodeled(&path, entry);
                continue;
            }
            let Some(limit) = self.ulimit(entry, &path) else {
                self.record_pending_unmodeled(&path, entry);
                continue;
            };
            limits.push(ProjectValue::new(limit, entry.value()));
        }
        Some(ProjectValue::new(ProjectUlimits { entries: limits }, value))
    }

    fn ulimit(&mut self, entry: &MergedEntry, parent_path: &[String]) -> Option<ProjectUlimit> {
        let value = match entry.value().kind() {
            MergedValueKind::Scalar(_) => ProjectUlimitValue::Single(
                self.ulimit_scalar(entry.value())
                    .map(|scalar| ProjectValue::new(scalar, entry.value()))?,
            ),
            MergedValueKind::Mapping(fields) => {
                let mut soft = None;
                let mut hard = None;
                let mut unmodeled_fields = Vec::new();
                let mut range_path = parent_path.to_vec();
                range_path.push(entry.key().to_owned());
                for field in fields {
                    match field.key() {
                        "soft" => {
                            soft = self
                                .ulimit_scalar(field.value())
                                .map(|scalar| ProjectValue::new(scalar, field.value()));
                        }
                        "hard" => {
                            hard = self
                                .ulimit_scalar(field.value())
                                .map(|scalar| ProjectValue::new(scalar, field.value()));
                        }
                        _ => unmodeled_fields.push(field_reference(&range_path, field)),
                    }
                }
                if soft.is_none() {
                    self.diagnostics.push(
                        Diagnostic::new(
                            ULIMIT_MISSING_RANGE_MEMBER,
                            Severity::Error,
                            "ulimit range is missing required `soft`",
                        )
                        .with_label(DiagnosticLabel::primary(
                            effective_span(entry.value()),
                            "missing soft limit",
                        )),
                    );
                }
                if hard.is_none() {
                    self.diagnostics.push(
                        Diagnostic::new(
                            ULIMIT_MISSING_RANGE_MEMBER,
                            Severity::Error,
                            "ulimit range is missing required `hard`",
                        )
                        .with_label(DiagnosticLabel::primary(
                            effective_span(entry.value()),
                            "missing hard limit",
                        )),
                    );
                }
                ProjectUlimitValue::Range(ProjectUlimitRange {
                    soft,
                    hard,
                    unmodeled_fields,
                })
            }
            _ => {
                self.expected(
                    entry.value(),
                    "ulimit must be a number/string scalar or a soft/hard mapping",
                );
                return None;
            }
        };
        Some(ProjectUlimit {
            name: ProjectKey::from_entry(entry),
            value,
        })
    }

    fn ulimit_scalar(&mut self, value: &MergedValue) -> Option<ProjectUlimitScalar> {
        let Some(scalar) = value.as_scalar() else {
            self.expected(value, "ulimit values must be number or string scalars");
            return None;
        };
        if !matches!(scalar.kind(), MergedScalarKind::String | MergedScalarKind::Number) {
            self.diagnostics.push(
                Diagnostic::new(
                    ULIMIT_INVALID_VALUE,
                    Severity::Error,
                    "ulimit values must be number or string scalars",
                )
                .with_label(DiagnosticLabel::primary(
                    effective_span(value),
                    "invalid ulimit scalar kind",
                )),
            );
            return None;
        }
        let parsed = LimitValue::parse(scalar.value().to_owned());
        if !parsed.is_valid() {
            self.diagnostics.push(
                Diagnostic::new(
                    ULIMIT_INVALID_VALUE,
                    Severity::Error,
                    "ulimit must be -1, a non-negative integer, or an interpolation expression",
                )
                .with_label(DiagnosticLabel::primary(effective_span(value), "invalid ulimit value")),
            );
        }
        Some(ProjectUlimitScalar {
            authored: scalar.raw().to_owned(),
            value: parsed,
            kind: scalar.kind(),
        })
    }

    fn pull_policy(&mut self, value: &MergedValue) -> Option<ProjectValue<PullPolicy>> {
        let policy = PullPolicy::parse(self.located_string(value, "pull_policy must be a non-null scalar")?);
        if !policy.is_recognized() {
            self.invalid(
                effective_span(value),
                "pull_policy must be a documented Compose policy, the retained `if_not_present` alias, schema-only `refresh`, an `every_` interval matching integer `w`, `d`, `h`, `m`, and `s` components, or interpolation",
            );
        }
        Some(ProjectValue::new(policy, value))
    }

    fn stop_grace_period(&mut self, value: &MergedValue) -> Option<ProjectValue<StopGracePeriod>> {
        let scalar = self.scalar(value, "stop_grace_period must be a non-null scalar")?;
        let period = StopGracePeriod::parse(scalar.value().to_owned());
        if !period.is_valid() {
            self.invalid(
                effective_span(value),
                "stop_grace_period must match the ComposeLens duration policy using `us`, `ms`, `s`, `m`, or `h`, or contain an interpolation marker",
            );
        }
        Some(ProjectValue::new(period, value))
    }

    fn command(&mut self, value: &MergedValue) -> Option<ProjectValue<Command>> {
        let span = effective_span(value);
        let command = match value.kind() {
            MergedValueKind::Null(_) => Command::Null(span),
            MergedValueKind::Scalar(scalar) => Command::String(Located::new(scalar.value().to_owned(), span)),
            MergedValueKind::Sequence(values) => {
                let mut arguments = Vec::new();
                for value in values {
                    arguments.push(self.located_string(value, "command list item must be a scalar")?);
                }
                Command::List {
                    span,
                    values: arguments,
                }
            }
            _ => {
                self.expected(value, "command must be null, a scalar, or a sequence");
                return None;
            }
        };
        Some(ProjectValue::new(command, value))
    }

    fn entrypoint(&mut self, value: &MergedValue) -> Option<ProjectValue<Entrypoint>> {
        let span = effective_span(value);
        let entrypoint = match value.kind() {
            MergedValueKind::Null(_) => Entrypoint::Null(span),
            MergedValueKind::Scalar(scalar) => Entrypoint::String(Located::new(scalar.value().to_owned(), span)),
            MergedValueKind::Sequence(values) => {
                let mut arguments = Vec::new();
                for value in values {
                    arguments.push(self.located_string(value, "entrypoint list item must be a scalar")?);
                }
                Entrypoint::List {
                    span,
                    values: arguments,
                }
            }
            _ => {
                self.expected(value, "entrypoint must be null, a scalar, or a sequence");
                return None;
            }
        };
        Some(ProjectValue::new(entrypoint, value))
    }

    fn user(&mut self, value: &MergedValue) -> Option<ProjectValue<UserSpec>> {
        let raw = self.project_string(value, "service user")?;
        Some(ProjectValue {
            value: UserSpec::parse(Located::new(raw.value, effective_span(value))),
            provenance: raw.provenance,
            sensitive: raw.sensitive,
        })
    }

    fn userns_mode(&mut self, value: &MergedValue) -> Option<ProjectValue<UserNamespaceMode>> {
        let raw = self.project_string(value, "service user namespace mode")?;
        Some(ProjectValue {
            value: UserNamespaceMode::parse(Located::new(raw.value, effective_span(value))),
            provenance: raw.provenance,
            sensitive: raw.sensitive,
        })
    }

    fn environment(&mut self, value: &MergedValue) -> Option<ProjectValue<ProjectEnvironment>> {
        let mut entries = Vec::new();
        match value.kind() {
            MergedValueKind::Mapping(values) => {
                for entry in values {
                    let scalar = self.compose_scalar(entry.value(), "environment value must be a scalar or null")?;
                    entries.push(ProjectEnvironmentEntry {
                        name: ProjectKey::from_entry(entry),
                        value: ProjectValue::new(scalar, entry.value()),
                        syntax: entry.syntax(),
                    });
                }
            }
            MergedValueKind::Sequence(values) => {
                for item in values {
                    let raw = self.located_string(item, "environment list item must be a scalar")?;
                    let (name, scalar, syntax) = raw.value().split_once('=').map_or_else(
                        || (raw.value().clone(), ComposeScalar::Null, EntrySyntax::ListKeyOnly),
                        |(name, value)| {
                            (
                                name.to_owned(),
                                ComposeScalar::String(value.to_owned()),
                                EntrySyntax::ListKeyValue,
                            )
                        },
                    );
                    entries.push(ProjectEnvironmentEntry {
                        name: ProjectKey {
                            value: name,
                            sources: item.provenance().sources().to_vec(),
                            sensitive: item.is_sensitive(),
                        },
                        value: ProjectValue::new(scalar, item),
                        syntax,
                    });
                }
            }
            _ => {
                self.expected(value, "environment must be a mapping or sequence");
                return None;
            }
        }
        Some(ProjectValue::new(ProjectEnvironment { entries }, value))
    }

    fn environment_files(
        &mut self,
        value: &MergedValue,
        service_path: &[String],
    ) -> Option<ProjectValue<Vec<ProjectValue<ProjectEnvironmentFile>>>> {
        let values = match value.kind() {
            MergedValueKind::Scalar(_) => std::slice::from_ref(value),
            MergedValueKind::Sequence(values) => values,
            _ => {
                self.expected(
                    value,
                    "env_file must be a scalar path or sequence of short/long entries",
                );
                return None;
            }
        };
        let mut environment_files = Vec::new();
        for (index, item) in values.iter().enumerate() {
            let mut path = service_path.to_vec();
            path.push("env_file".to_owned());
            path.push(index.to_string());
            let environment_file = match item.kind() {
                MergedValueKind::Scalar(scalar) => ProjectEnvironmentFile::Short(scalar.value().to_owned()),
                MergedValueKind::Mapping(fields) => {
                    ProjectEnvironmentFile::Long(Box::new(self.long_environment_file(item, fields, &path)))
                }
                _ => {
                    self.expected(
                        item,
                        "env_file item must use scalar short syntax or mapping long syntax",
                    );
                    continue;
                }
            };
            environment_files.push(ProjectValue::new(environment_file, item));
        }
        Some(ProjectValue::new(environment_files, value))
    }

    fn long_environment_file(
        &mut self,
        value: &MergedValue,
        fields: &[MergedEntry],
        path: &[String],
    ) -> ProjectLongEnvironmentFile {
        let mut environment_file = ProjectLongEnvironmentFile {
            path: None,
            required: None,
            format: None,
            unmodeled_fields: Vec::new(),
        };
        for field in fields {
            match field.key() {
                "path" => {
                    environment_file.path = self.project_string(field.value(), "environment-file path");
                }
                "required" => {
                    environment_file.required = self
                        .located_boolean(field.value(), "environment-file required option must be a boolean")
                        .map(|value| ProjectValue::new(value.into_value(), field.value()));
                }
                "format" => {
                    environment_file.format = self.environment_file_format(field.value());
                }
                _ => environment_file.unmodeled_fields.push(field_reference(path, field)),
            }
        }
        if environment_file.path.is_none() {
            self.missing(value, "long-syntax environment file is missing `path`");
        }
        environment_file
    }

    fn environment_file_format(&mut self, value: &MergedValue) -> Option<ProjectValue<EnvironmentFileFormat>> {
        let raw = self.project_string(value, "environment-file format")?;
        let format = EnvironmentFileFormat::parse(Located::new(raw.value, effective_span(value)));
        if matches!(format.kind(), EnvironmentFileFormatKind::Other) {
            self.invalid(
                effective_span(value),
                "environment-file format must be `raw` or interpolation",
            );
        }
        Some(ProjectValue {
            value: format,
            provenance: raw.provenance,
            sensitive: raw.sensitive,
        })
    }

    fn service_labels(&mut self, value: &MergedValue) -> Option<ProjectValue<ProjectLabels>> {
        let mut entries = Vec::new();
        match value.kind() {
            MergedValueKind::Mapping(values) => {
                for entry in values {
                    let scalar = if entry.syntax() == EntrySyntax::ListKeyOnly {
                        ComposeScalar::String(String::new())
                    } else {
                        self.compose_scalar(entry.value(), "label value must be a scalar or null")?
                    };
                    entries.push(ProjectLabelEntry {
                        name: ProjectKey::from_entry(entry),
                        value: ProjectValue::new(scalar, entry.value()),
                        syntax: entry.syntax(),
                    });
                }
            }
            MergedValueKind::Sequence(values) => {
                for item in values {
                    let raw = self.located_string(item, "label list item must be a scalar")?;
                    let (name, value, syntax) = raw.value().split_once('=').map_or_else(
                        || (raw.value().clone(), String::new(), EntrySyntax::ListKeyOnly),
                        |(name, value)| (name.to_owned(), value.to_owned(), EntrySyntax::ListKeyValue),
                    );
                    entries.push(ProjectLabelEntry {
                        name: ProjectKey::from_value(name, item),
                        value: ProjectValue::new(ComposeScalar::String(value), item),
                        syntax,
                    });
                }
            }
            _ => {
                self.expected(value, "labels must be a mapping or sequence");
                return None;
            }
        }
        Some(ProjectValue::new(ProjectLabels { entries }, value))
    }

    fn healthcheck(&mut self, value: &MergedValue, parent_path: &[String]) -> Option<ProjectValue<ProjectHealthcheck>> {
        let fields = self.mapping(value, "healthcheck must be a mapping")?;
        let mut healthcheck = ProjectHealthcheck {
            test: None,
            interval: None,
            timeout: None,
            retries: None,
            start_period: None,
            start_interval: None,
            disable: None,
            unmodeled_fields: Vec::new(),
        };
        let mut path = parent_path.to_vec();
        path.push("healthcheck".to_owned());
        for field in fields {
            match field.key() {
                "test" => healthcheck.test = self.healthcheck_test(field.value()),
                "interval" => {
                    healthcheck.interval =
                        self.healthcheck_duration(field.value(), "healthcheck interval must be a scalar");
                }
                "timeout" => {
                    healthcheck.timeout =
                        self.healthcheck_duration(field.value(), "healthcheck timeout must be a scalar");
                }
                "retries" => healthcheck.retries = self.healthcheck_retries(field.value()),
                "start_period" => {
                    healthcheck.start_period =
                        self.healthcheck_duration(field.value(), "healthcheck start_period must be a scalar");
                }
                "start_interval" => {
                    healthcheck.start_interval =
                        self.healthcheck_duration(field.value(), "healthcheck start_interval must be a scalar");
                }
                "disable" => {
                    healthcheck.disable = self
                        .located_boolean(field.value(), "healthcheck disable must be a boolean")
                        .map(|value| ProjectValue::new(value.into_value(), field.value()));
                }
                _ => healthcheck.unmodeled_fields.push(field_reference(&path, field)),
            }
        }
        Some(ProjectValue::new(healthcheck, value))
    }

    fn depends_on(&mut self, value: &MergedValue, parent_path: &[String]) -> Option<ProjectValue<ProjectDependsOn>> {
        let dependencies = match value.kind() {
            MergedValueKind::Sequence(values) => {
                let mut dependencies = Vec::new();
                for value in values {
                    let Some(service) = self.project_string(value, "dependency service name") else {
                        continue;
                    };
                    let dependency = ProjectServiceDependency {
                        service: ProjectKey::from_value(service.value, value),
                        condition: None,
                        restart: None,
                        required: None,
                        unmodeled_fields: Vec::new(),
                    };
                    dependencies.push(ProjectValue::new(dependency, value));
                }
                ProjectDependsOn::Short(dependencies)
            }
            MergedValueKind::Mapping(entries) => {
                let mut dependencies = Vec::new();
                let mut path = parent_path.to_vec();
                path.push("depends_on".to_owned());
                for entry in entries {
                    let mut dependency = ProjectServiceDependency {
                        service: ProjectKey::from_entry(entry),
                        condition: None,
                        restart: None,
                        required: None,
                        unmodeled_fields: Vec::new(),
                    };
                    let fields = match entry.value().kind() {
                        MergedValueKind::Null(_) => &[][..],
                        MergedValueKind::Mapping(fields) => fields.as_slice(),
                        _ => {
                            self.expected(entry.value(), "long dependency options must be a mapping or null");
                            continue;
                        }
                    };
                    let mut dependency_path = path.clone();
                    dependency_path.push(entry.key().to_owned());
                    for field in fields {
                        match field.key() {
                            "condition" => {
                                let Some(condition) = self.project_string(field.value(), "dependency condition") else {
                                    continue;
                                };
                                let parsed = DependencyCondition::parse(condition.value);
                                if !parsed.is_known() {
                                    self.invalid(
                                        effective_span(field.value()),
                                        "dependency condition is not defined by Compose",
                                    );
                                }
                                dependency.condition = Some(ProjectValue {
                                    value: parsed,
                                    provenance: condition.provenance,
                                    sensitive: condition.sensitive,
                                });
                            }
                            "restart" => {
                                dependency.restart = self
                                    .located_boolean(field.value(), "dependency restart must be a boolean")
                                    .map(|value| ProjectValue::new(value.into_value(), field.value()));
                            }
                            "required" => {
                                dependency.required = self
                                    .located_boolean(field.value(), "dependency required must be a boolean")
                                    .map(|value| ProjectValue::new(value.into_value(), field.value()));
                            }
                            _ => dependency
                                .unmodeled_fields
                                .push(field_reference(&dependency_path, field)),
                        }
                    }
                    dependencies.push(ProjectValue::new(dependency, entry.value()));
                }
                ProjectDependsOn::Long(dependencies)
            }
            _ => {
                self.expected(value, "depends_on must be a sequence or mapping");
                return None;
            }
        };
        Some(ProjectValue::new(dependencies, value))
    }

    fn healthcheck_test(&mut self, value: &MergedValue) -> Option<ProjectValue<HealthcheckTest>> {
        let span = effective_span(value);
        let test = match value.kind() {
            MergedValueKind::Scalar(scalar) => HealthcheckTest::String(Located::new(scalar.value().to_owned(), span)),
            MergedValueKind::Sequence(values) => {
                let mut items = Vec::new();
                for value in values {
                    items.push(self.located_string(value, "healthcheck test item must be a scalar")?);
                }
                let kind = items.first().map(|item| HealthcheckTestKind::parse(item.value()));
                HealthcheckTest::List {
                    span,
                    kind,
                    values: items,
                }
            }
            _ => {
                self.expected(value, "healthcheck test must be a scalar or sequence");
                return None;
            }
        };
        Some(ProjectValue::new(test, value))
    }

    fn healthcheck_duration(
        &mut self,
        value: &MergedValue,
        message: &str,
    ) -> Option<ProjectValue<HealthcheckDuration>> {
        let scalar = self.scalar(value, message)?;
        Some(ProjectValue::new(
            HealthcheckDuration::parse(scalar.value().to_owned()),
            value,
        ))
    }

    fn healthcheck_retries(&mut self, value: &MergedValue) -> Option<ProjectValue<HealthcheckRetries>> {
        let scalar = self.scalar(value, "healthcheck retries must be a scalar")?;
        Some(ProjectValue::new(
            HealthcheckRetries::parse(scalar.value().to_owned()),
            value,
        ))
    }

    fn extra_hosts(&mut self, value: &MergedValue) -> Option<ProjectValue<ProjectExtraHosts>> {
        let mut entries = Vec::new();
        match value.kind() {
            MergedValueKind::Mapping(values) => {
                for entry in values {
                    let scalar = self.scalar(entry.value(), "extra_hosts address must be a scalar")?;
                    entries.push(ProjectExtraHost {
                        hostname: ProjectKey::from_entry(entry),
                        address: ProjectValue::new(HostAddress::parse(scalar.value().to_owned()), entry.value()),
                        syntax: EntrySyntax::Mapping,
                    });
                }
            }
            MergedValueKind::Sequence(values) => {
                for item in values {
                    let raw = self.located_string(item, "extra_hosts list item must be a scalar")?;
                    let parsed = ShortExtraHost::parse(raw);
                    let (Some(hostname), Some(address)) = (parsed.hostname(), parsed.address()) else {
                        self.invalid(
                            effective_span(item),
                            "extra_hosts entry must contain a hostname and address",
                        );
                        continue;
                    };
                    entries.push(ProjectExtraHost {
                        hostname: ProjectKey {
                            value: hostname.to_owned(),
                            sources: item.provenance().sources().to_vec(),
                            sensitive: item.is_sensitive(),
                        },
                        address: ProjectValue::new(address.clone(), item),
                        syntax: EntrySyntax::ListKeyValue,
                    });
                }
            }
            _ => {
                self.expected(value, "extra_hosts must be a mapping or sequence");
                return None;
            }
        }
        Some(ProjectValue::new(ProjectExtraHosts { entries }, value))
    }

    fn project_string(&mut self, value: &MergedValue, description: &str) -> Option<ProjectValue<String>> {
        let scalar = self.scalar(value, &format!("{description} must be a non-null scalar"))?;
        Some(ProjectValue::new(scalar.value().to_owned(), value))
    }

    fn string_collection(
        &mut self,
        value: &MergedValue,
        message: &str,
    ) -> Option<ProjectValue<Vec<ProjectValue<String>>>> {
        let Some(values) = value.as_sequence() else {
            self.expected(value, message);
            return None;
        };
        let mut strings = Vec::new();
        for value in values {
            let scalar = self.scalar(value, "sequence item must be a non-null scalar")?;
            strings.push(ProjectValue::new(scalar.value().to_owned(), value));
        }
        Some(ProjectValue::new(strings, value))
    }

    fn capability_drop(&mut self, value: &MergedValue) -> Option<ProjectValue<Vec<ProjectValue<CapabilityDropItem>>>> {
        let Some(values) = value.as_sequence() else {
            self.expected(value, "cap_drop must be a sequence of string scalars");
            return None;
        };
        let mut items = Vec::new();
        let mut seen = BTreeMap::new();
        for item in values {
            let scalar = match item.kind() {
                MergedValueKind::Scalar(scalar) if scalar.kind() == MergedScalarKind::String => scalar,
                _ => {
                    self.expected(item, "cap_drop entries must be string scalars");
                    continue;
                }
            };
            let span = effective_span(item);
            if let Some(first) = seen.get(scalar.value()) {
                self.diagnostics.push(
                    Diagnostic::new(
                        CAP_DROP_DUPLICATE_ITEM,
                        Severity::Error,
                        "cap_drop entries must be unique exact strings",
                    )
                    .with_label(DiagnosticLabel::primary(span, "duplicate capability string"))
                    .with_label(DiagnosticLabel::secondary(*first, "first identical string")),
                );
            } else {
                seen.insert(scalar.value().to_owned(), span);
            }
            let typed = CapabilityDropItem::new(Located::new(scalar.value().to_owned(), span));
            items.push(ProjectValue::new(typed, item));
        }
        Some(ProjectValue::new(items, value))
    }

    fn capability_add(&mut self, value: &MergedValue) -> Option<ProjectValue<Vec<ProjectValue<CapabilityAddItem>>>> {
        let Some(values) = value.as_sequence() else {
            self.expected(value, "cap_add must be a sequence of string scalars");
            return None;
        };
        let mut items = Vec::new();
        let mut seen = BTreeMap::new();
        for item in values {
            let scalar = match item.kind() {
                MergedValueKind::Scalar(scalar) if scalar.kind() == MergedScalarKind::String => scalar,
                _ => {
                    self.expected(item, "cap_add entries must be string scalars");
                    continue;
                }
            };
            let span = effective_span(item);
            if let Some(first) = seen.get(scalar.value()) {
                self.diagnostics.push(
                    Diagnostic::new(
                        CAP_ADD_DUPLICATE_ITEM,
                        Severity::Error,
                        "cap_add entries must be unique exact strings",
                    )
                    .with_label(DiagnosticLabel::primary(span, "duplicate capability string"))
                    .with_label(DiagnosticLabel::secondary(*first, "first identical string")),
                );
            } else {
                seen.insert(scalar.value().to_owned(), span);
            }
            let typed = CapabilityAddItem::new(Located::new(scalar.value().to_owned(), span));
            items.push(ProjectValue::new(typed, item));
        }
        Some(ProjectValue::new(items, value))
    }

    fn devices(
        &mut self,
        value: &MergedValue,
        service_path: &[String],
    ) -> Option<ProjectValue<Vec<ProjectValue<ProjectDevice>>>> {
        let Some(values) = value.as_sequence() else {
            self.expected(value, "service devices must be a sequence");
            return None;
        };
        let mut devices = Vec::new();
        for (index, item) in values.iter().enumerate() {
            let mut path = service_path.to_vec();
            path.push("devices".to_owned());
            path.push(index.to_string());
            let device = match item.kind() {
                MergedValueKind::Scalar(scalar) if scalar.kind() == MergedScalarKind::String => ProjectDevice::Short(
                    ShortDevice::new(Located::new(scalar.value().to_owned(), effective_span(item))),
                ),
                MergedValueKind::Mapping(fields) => ProjectDevice::Long(self.long_device(item, fields, &path)),
                _ => {
                    self.diagnostics.push(
                        Diagnostic::new(
                            DEVICE_EXPECTED_FORM,
                            Severity::Error,
                            "service device must use string short syntax or mapping long syntax",
                        )
                        .with_label(DiagnosticLabel::primary(
                            effective_span(item),
                            "unsupported device form",
                        )),
                    );
                    continue;
                }
            };
            devices.push(ProjectValue::new(device, item));
        }
        Some(ProjectValue::new(devices, value))
    }

    fn long_device(&mut self, value: &MergedValue, fields: &[MergedEntry], path: &[String]) -> ProjectLongDevice {
        let mut device = ProjectLongDevice {
            source: None,
            target: None,
            permissions: None,
            extension_fields: Vec::new(),
            unknown_fields: Vec::new(),
        };
        for field in fields {
            let parsed = match field.key() {
                "source" | "target" | "permissions" => self.device_string(field.value(), field.key()),
                name if name.starts_with("x-") => {
                    device.extension_fields.push(field_reference(path, field));
                    continue;
                }
                _ => {
                    device.unknown_fields.push(field_reference(path, field));
                    continue;
                }
            };
            match field.key() {
                "source" => device.source = parsed,
                "target" => device.target = parsed,
                "permissions" => device.permissions = parsed,
                _ => unreachable!("unrecognized device fields continue before assignment"),
            }
        }
        if device.source.is_none() {
            self.missing(value, "long-syntax device is missing required string `source`");
        }
        device
    }

    fn device_string(&mut self, value: &MergedValue, member: &str) -> Option<ProjectValue<String>> {
        let scalar = match value.kind() {
            MergedValueKind::Scalar(scalar) if scalar.kind() == MergedScalarKind::String => scalar,
            _ => {
                self.diagnostics.push(
                    Diagnostic::new(
                        DEVICE_EXPECTED_STRING,
                        Severity::Error,
                        format!("device {member} must be a string scalar"),
                    )
                    .with_label(DiagnosticLabel::primary(
                        effective_span(value),
                        "unexpected long-device member form",
                    )),
                );
                return None;
            }
        };
        Some(ProjectValue::new(scalar.value().to_owned(), value))
    }

    fn scalar<'value>(
        &mut self,
        value: &'value MergedValue,
        message: &str,
    ) -> Option<&'value crate::merge::MergedScalar> {
        let Some(scalar) = value.as_scalar() else {
            self.expected(value, message);
            return None;
        };
        Some(scalar)
    }

    fn located_string(&mut self, value: &MergedValue, message: &str) -> Option<Located<String>> {
        let scalar = self.scalar(value, message)?;
        Some(Located::new(scalar.value().to_owned(), effective_span(value)))
    }

    fn compose_scalar(&mut self, value: &MergedValue, message: &str) -> Option<ComposeScalar> {
        match value.kind() {
            MergedValueKind::Null(_) => Some(ComposeScalar::Null),
            MergedValueKind::Scalar(scalar) => Some(match scalar.kind() {
                MergedScalarKind::String => ComposeScalar::String(scalar.value().to_owned()),
                MergedScalarKind::Boolean => ComposeScalar::Boolean(scalar.value().eq_ignore_ascii_case("true")),
                MergedScalarKind::Number => ComposeScalar::Number(scalar.value().to_owned()),
            }),
            _ => {
                self.expected(value, message);
                None
            }
        }
    }

    fn mapping<'value>(&mut self, value: &'value MergedValue, message: &str) -> Option<&'value [MergedEntry]> {
        let Some(entries) = value.as_mapping() else {
            self.expected(value, message);
            return None;
        };
        Some(entries)
    }

    fn expected(&mut self, value: &MergedValue, message: &str) {
        self.diagnostics.push(
            Diagnostic::new(PROJECT_EXPECTED_FORM, Severity::Error, message).with_label(DiagnosticLabel::primary(
                effective_span(value),
                "unexpected merged value form",
            )),
        );
    }

    fn missing(&mut self, value: &MergedValue, message: &str) {
        self.diagnostics.push(
            Diagnostic::new(PROJECT_MISSING_FIELD, Severity::Error, message).with_label(DiagnosticLabel::primary(
                effective_span(value),
                "required field is missing",
            )),
        );
    }

    fn invalid(&mut self, span: SourceSpan, message: &str) {
        self.diagnostics.push(
            Diagnostic::new(PROJECT_INVALID_VALUE, Severity::Error, message)
                .with_label(DiagnosticLabel::primary(span, "invalid native value")),
        );
    }

    fn record_root_unmodeled(&mut self, path: &[String], entry: &MergedEntry) {
        self.root_unmodeled.push(field_reference(path, entry));
    }

    fn record_pending_unmodeled(&mut self, path: &[String], entry: &MergedEntry) {
        self.pending_unmodeled.push(field_reference(path, entry));
    }
}

impl Builder<'_> {
    fn ports(&mut self, value: &MergedValue, service_path: &[String]) -> Option<ProjectValue<Vec<ProjectValue<Port>>>> {
        let Some(values) = value.as_sequence() else {
            self.expected(value, "service ports must be a sequence");
            return None;
        };
        let mut ports = Vec::new();
        for (index, item) in values.iter().enumerate() {
            let mut path = service_path.to_vec();
            path.push("ports".to_owned());
            path.push(index.to_string());
            let port = match item.kind() {
                MergedValueKind::Scalar(scalar) => Port::Short(ShortPort::parse(Located::new(
                    scalar.value().to_owned(),
                    effective_span(item),
                ))),
                MergedValueKind::Mapping(fields) => Port::Long(Box::new(self.long_port(item, fields, &path))),
                _ => {
                    self.expected(item, "service port must use scalar short syntax or mapping long syntax");
                    continue;
                }
            };
            ports.push(ProjectValue::new(port, item));
        }
        Some(ProjectValue::new(ports, value))
    }

    fn long_port(&mut self, value: &MergedValue, fields: &[MergedEntry], path: &[String]) -> LongPort {
        let mut port = LongPort::new(effective_span(value));
        let mut has_target = false;
        for field in fields {
            match field.key() {
                "target" => {
                    if let Some(value) = self.located_string(field.value(), "port target must be a scalar") {
                        port.set_target(value);
                        has_target = true;
                    }
                }
                "published" => self
                    .located_string(field.value(), "published port must be a scalar")
                    .into_iter()
                    .for_each(|value| port.set_published(value)),
                "host_ip" => self
                    .located_string(field.value(), "port host_ip must be a scalar")
                    .into_iter()
                    .for_each(|value| port.set_host_ip(value)),
                "protocol" => self
                    .located_string(field.value(), "port protocol must be a scalar")
                    .into_iter()
                    .for_each(|value| port.set_protocol(value)),
                "app_protocol" => self
                    .located_string(field.value(), "port app_protocol must be a scalar")
                    .into_iter()
                    .for_each(|value| port.set_app_protocol(value)),
                "mode" => self
                    .located_string(field.value(), "port mode must be a scalar")
                    .into_iter()
                    .for_each(|value| port.set_mode(value)),
                "name" => self
                    .located_string(field.value(), "port name must be a scalar")
                    .into_iter()
                    .for_each(|value| port.set_name(value)),
                _ => self.record_pending_unmodeled(path, field),
            }
        }
        if !has_target {
            self.missing(value, "long-syntax port is missing `target`");
        }
        port
    }

    fn volumes(
        &mut self,
        value: &MergedValue,
        service_path: &[String],
    ) -> Option<ProjectValue<Vec<ProjectValue<VolumeMount>>>> {
        let Some(values) = value.as_sequence() else {
            self.expected(value, "service volumes must be a sequence");
            return None;
        };
        let mut mounts = Vec::new();
        for (index, item) in values.iter().enumerate() {
            let mut path = service_path.to_vec();
            path.push("volumes".to_owned());
            path.push(index.to_string());
            let mount = match item.kind() {
                MergedValueKind::Scalar(scalar) => VolumeMount::Short(ShortVolumeMount::new(Located::new(
                    scalar.value().to_owned(),
                    effective_span(item),
                ))),
                MergedValueKind::Mapping(fields) => VolumeMount::Long(Box::new(self.long_volume(item, fields, &path))),
                _ => {
                    self.expected(
                        item,
                        "service volume must use scalar short syntax or mapping long syntax",
                    );
                    continue;
                }
            };
            mounts.push(ProjectValue::new(mount, item));
        }
        Some(ProjectValue::new(mounts, value))
    }

    fn long_volume(&mut self, value: &MergedValue, fields: &[MergedEntry], path: &[String]) -> LongVolumeMount {
        let mut mount = LongVolumeMount::new(effective_span(value));
        let mut has_type = false;
        let mut has_target = false;
        for field in fields {
            match field.key() {
                "type" => {
                    if let Some(value) = self.located_string(field.value(), "volume type must be a scalar") {
                        mount.set_mount_type(Located::new(MountType::from_text(value.value().clone()), value.span()));
                        has_type = true;
                    }
                }
                "source" => self
                    .located_string(field.value(), "volume source must be a scalar")
                    .into_iter()
                    .for_each(|value| mount.set_source(value)),
                "target" => {
                    if let Some(value) = self.located_string(field.value(), "volume target must be a scalar") {
                        mount.set_target(value);
                        has_target = true;
                    }
                }
                "read_only" => self
                    .located_boolean(field.value(), "volume read_only must be a boolean")
                    .into_iter()
                    .for_each(|value| mount.set_read_only(value)),
                "bind" => self
                    .bind_options(field.value(), path)
                    .into_iter()
                    .for_each(|value| mount.set_bind(value)),
                _ => self.record_pending_unmodeled(path, field),
            }
        }
        if !has_type {
            self.missing(value, "long-syntax volume is missing `type`");
        }
        if !has_target {
            self.missing(value, "long-syntax volume is missing `target`");
        }
        mount
    }

    fn grants(
        &mut self,
        value: &MergedValue,
        service_path: &[String],
        kind: &str,
    ) -> Option<ProjectValue<Vec<ProjectValue<ProjectGrant>>>> {
        let Some(values) = value.as_sequence() else {
            self.expected(value, &format!("service {kind}s must be a sequence"));
            return None;
        };
        let mut grants = Vec::new();
        for (index, item) in values.iter().enumerate() {
            let mut path = service_path.to_vec();
            path.push(format!("{kind}s"));
            path.push(index.to_string());
            let grant = match item.kind() {
                MergedValueKind::Scalar(scalar) => ProjectGrant::Short(scalar.value().to_owned()),
                MergedValueKind::Mapping(fields) => {
                    ProjectGrant::Long(Box::new(self.long_grant(item, fields, &path, kind)))
                }
                _ => {
                    self.expected(
                        item,
                        &format!("service {kind} must use scalar short syntax or mapping long syntax"),
                    );
                    continue;
                }
            };
            grants.push(ProjectValue::new(grant, item));
        }
        Some(ProjectValue::new(grants, value))
    }

    fn long_grant(
        &mut self,
        value: &MergedValue,
        fields: &[MergedEntry],
        path: &[String],
        kind: &str,
    ) -> ProjectLongGrant {
        let mut grant = ProjectLongGrant {
            source: None,
            target: None,
            uid: None,
            gid: None,
            mode: None,
            unmodeled_fields: Vec::new(),
        };
        for field in fields {
            let parsed = match field.key() {
                "source" => self.project_string(field.value(), &format!("{kind} source")),
                "target" => self.project_string(field.value(), &format!("{kind} target")),
                "uid" => self.project_string(field.value(), &format!("{kind} uid")),
                "gid" => self.project_string(field.value(), &format!("{kind} gid")),
                "mode" => self.project_string(field.value(), &format!("{kind} mode")),
                _ => {
                    grant.unmodeled_fields.push(field_reference(path, field));
                    continue;
                }
            };
            match field.key() {
                "source" => grant.source = parsed,
                "target" => grant.target = parsed,
                "uid" => grant.uid = parsed,
                "gid" => grant.gid = parsed,
                "mode" => grant.mode = parsed,
                _ => unreachable!("unrecognized grant fields continue before assignment"),
            }
        }
        if grant.source.is_none() {
            self.missing(value, &format!("long-syntax {kind} is missing `source`"));
        }
        grant
    }

    fn bind_options(&mut self, value: &MergedValue, parent_path: &[String]) -> Option<BindOptions> {
        let fields = self.mapping(value, "volume bind options must be a mapping")?;
        let mut bind = BindOptions::new(effective_span(value));
        let mut path = parent_path.to_vec();
        path.push("bind".to_owned());
        for field in fields {
            match field.key() {
                "propagation" => self
                    .located_string(field.value(), "bind propagation must be a scalar")
                    .into_iter()
                    .for_each(|value| bind.set_propagation(value)),
                "create_host_path" => self
                    .located_boolean(field.value(), "bind create_host_path must be a boolean")
                    .into_iter()
                    .for_each(|value| bind.set_create_host_path(value)),
                "selinux" => {
                    if let Some(value) = self.located_string(field.value(), "bind SELinux mode must be a scalar") {
                        let mode = match value.value().as_str() {
                            "z" => Some(SelinuxRelabel::Shared),
                            "Z" => Some(SelinuxRelabel::Private),
                            _ => None,
                        };
                        if let Some(mode) = mode {
                            bind.set_selinux(Located::new(mode, value.span()));
                        } else {
                            self.invalid(value.span(), "bind SELinux mode must be `z` or `Z`");
                        }
                    }
                }
                _ => self.record_pending_unmodeled(&path, field),
            }
        }
        Some(bind)
    }

    fn service_networks(
        &mut self,
        value: &MergedValue,
        service_path: &[String],
    ) -> Option<ProjectValue<ServiceNetworks>> {
        let span = effective_span(value);
        let networks = match value.kind() {
            MergedValueKind::Sequence(values) => {
                let mut names = Vec::new();
                for value in values {
                    names.push(self.located_string(value, "service network name must be a scalar")?);
                }
                ServiceNetworks::Short { span, names }
            }
            MergedValueKind::Mapping(entries) => {
                let mut networks = Vec::new();
                for entry in entries {
                    let mut path = service_path.to_vec();
                    path.push("networks".to_owned());
                    path.push(entry.key().to_owned());
                    networks.push(self.service_network(entry, &path)?);
                }
                ServiceNetworks::Long { span, networks }
            }
            _ => {
                self.expected(value, "service networks must be a sequence or mapping");
                return None;
            }
        };
        Some(ProjectValue::new(networks, value))
    }

    fn service_network(&mut self, entry: &MergedEntry, path: &[String]) -> Option<ServiceNetwork> {
        let value = entry.value();
        let span = effective_span(value);
        let mut network = ServiceNetwork::new(Located::new(entry.key().to_owned(), entry_span(entry)), span);
        let fields = match value.kind() {
            MergedValueKind::Null(_) => return Some(network),
            MergedValueKind::Mapping(fields) => fields,
            _ => {
                self.expected(value, "service network attachment must be a mapping or null");
                return None;
            }
        };
        for field in fields {
            match field.key() {
                "aliases" => self
                    .located_string_sequence(field.value(), "network aliases must be a sequence")
                    .into_iter()
                    .for_each(|value| network.set_aliases(value)),
                "interface_name" => self
                    .located_string(field.value(), "network interface_name must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_interface_name(value)),
                "ipv4_address" => self
                    .located_string(field.value(), "network ipv4_address must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_ipv4_address(value)),
                "ipv6_address" => self
                    .located_string(field.value(), "network ipv6_address must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_ipv6_address(value)),
                "link_local_ips" => self
                    .located_string_sequence(field.value(), "link_local_ips must be a sequence")
                    .into_iter()
                    .for_each(|value| network.set_link_local_ips(value)),
                "mac_address" => self
                    .located_string(field.value(), "network mac_address must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_mac_address(value)),
                "driver_opts" => self
                    .key_value_mapping(field.value(), "network driver_opts must be a mapping")
                    .into_iter()
                    .for_each(|value| network.set_driver_opts(value)),
                "gw_priority" => self
                    .located_string(field.value(), "network gw_priority must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_gw_priority(value)),
                "priority" => self
                    .located_string(field.value(), "network priority must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_priority(value)),
                _ => self.record_pending_unmodeled(path, field),
            }
        }
        Some(network)
    }

    fn located_boolean(&mut self, value: &MergedValue, message: &str) -> Option<Located<BooleanValue>> {
        let scalar = self.scalar(value, message)?;
        let boolean = if scalar.kind() == MergedScalarKind::Boolean {
            BooleanValue::Literal(scalar.value().eq_ignore_ascii_case("true"))
        } else if scalar.value().contains('$') {
            BooleanValue::Expression(scalar.value().to_owned())
        } else {
            self.invalid(effective_span(value), message);
            return None;
        };
        Some(Located::new(boolean, effective_span(value)))
    }

    fn located_string_sequence(&mut self, value: &MergedValue, message: &str) -> Option<Vec<Located<String>>> {
        let Some(values) = value.as_sequence() else {
            self.expected(value, message);
            return None;
        };
        let mut strings = Vec::new();
        for value in values {
            strings.push(self.located_string(value, "sequence item must be a scalar")?);
        }
        Some(strings)
    }

    fn key_value_mapping(&mut self, value: &MergedValue, message: &str) -> Option<Vec<KeyValueEntry>> {
        let Some(entries) = value.as_mapping() else {
            self.expected(value, message);
            return None;
        };
        let mut values = Vec::new();
        for entry in entries {
            let scalar = self.compose_scalar(entry.value(), "mapping value must be a scalar or null")?;
            let value_span = effective_span(entry.value());
            values.push(KeyValueEntry::new(
                Located::new(entry.key().to_owned(), entry_span(entry)),
                Located::new(scalar, value_span),
                value_span,
            ));
        }
        Some(values)
    }

    fn network_definitions(&mut self, value: &MergedValue) -> Vec<ProjectResource<NetworkDefinition>> {
        let Some(entries) = self.mapping(value, "top-level networks must be a mapping") else {
            return Vec::new();
        };
        entries
            .iter()
            .filter_map(|entry| {
                let definition = self.network_definition(entry)?;
                Some(ProjectResource {
                    name: ProjectKey::from_entry(entry),
                    definition: ProjectValue::new(definition, entry.value()),
                })
            })
            .collect()
    }

    fn network_definition(&mut self, entry: &MergedEntry) -> Option<NetworkDefinition> {
        let value = entry.value();
        let span = effective_span(value);
        let mut network = NetworkDefinition::new(Located::new(entry.key().to_owned(), entry_span(entry)), span);
        let fields = match value.kind() {
            MergedValueKind::Null(_) => return Some(network),
            MergedValueKind::Mapping(fields) => fields,
            _ => {
                self.expected(value, "network definition must be a mapping or null");
                return None;
            }
        };
        let path = ["networks".to_owned(), entry.key().to_owned()];
        for field in fields {
            match field.key() {
                "driver" => self
                    .located_string(field.value(), "network driver must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_driver(value)),
                "driver_opts" => self
                    .key_value_mapping(field.value(), "network driver_opts must be a mapping")
                    .into_iter()
                    .for_each(|value| network.set_driver_opts(value)),
                "attachable" => self
                    .located_boolean(field.value(), "network attachable must be a boolean")
                    .into_iter()
                    .for_each(|value| network.set_attachable(value)),
                "enable_ipv4" => self
                    .located_boolean(field.value(), "network enable_ipv4 must be a boolean")
                    .into_iter()
                    .for_each(|value| network.set_enable_ipv4(value)),
                "enable_ipv6" => self
                    .located_boolean(field.value(), "network enable_ipv6 must be a boolean")
                    .into_iter()
                    .for_each(|value| network.set_enable_ipv6(value)),
                "external" => self
                    .located_boolean(field.value(), "network external must be a boolean")
                    .into_iter()
                    .for_each(|value| network.set_external(value)),
                "internal" => self
                    .located_boolean(field.value(), "network internal must be a boolean")
                    .into_iter()
                    .for_each(|value| network.set_internal(value)),
                "ipam" => self
                    .ipam(field.value(), &path)
                    .into_iter()
                    .for_each(|value| network.set_ipam(value)),
                "labels" => self
                    .labels(field.value())
                    .into_iter()
                    .for_each(|value| network.set_labels(value)),
                "name" => self
                    .located_string(field.value(), "network custom name must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_custom_name(value)),
                _ => self.record_root_unmodeled(&path, field),
            }
        }
        Some(network)
    }

    fn ipam(&mut self, value: &MergedValue, parent_path: &[String]) -> Option<Ipam> {
        let fields = self.mapping(value, "network IPAM must be a mapping")?;
        let mut ipam = Ipam::new(effective_span(value));
        let mut path = parent_path.to_vec();
        path.push("ipam".to_owned());
        for field in fields {
            match field.key() {
                "driver" => self
                    .located_string(field.value(), "IPAM driver must be a scalar")
                    .into_iter()
                    .for_each(|value| ipam.set_driver(value)),
                "config" => self
                    .ipam_configs(field.value(), &path)
                    .into_iter()
                    .for_each(|value| ipam.set_config(value)),
                "options" => self
                    .key_value_mapping(field.value(), "IPAM options must be a mapping")
                    .into_iter()
                    .for_each(|value| ipam.set_options(value)),
                _ => self.record_root_unmodeled(&path, field),
            }
        }
        Some(ipam)
    }

    fn ipam_configs(&mut self, value: &MergedValue, parent_path: &[String]) -> Option<Vec<IpamConfig>> {
        let Some(values) = value.as_sequence() else {
            self.expected(value, "IPAM config must be a sequence");
            return None;
        };
        let mut configs = Vec::new();
        for (index, value) in values.iter().enumerate() {
            let Some(fields) = value.as_mapping() else {
                self.expected(value, "IPAM config entry must be a mapping");
                continue;
            };
            let mut config = IpamConfig::new(effective_span(value));
            let mut path = parent_path.to_vec();
            path.push("config".to_owned());
            path.push(index.to_string());
            for field in fields {
                match field.key() {
                    "subnet" => self
                        .located_string(field.value(), "IPAM subnet must be a scalar")
                        .into_iter()
                        .for_each(|value| config.set_subnet(value)),
                    "ip_range" => self
                        .located_string(field.value(), "IPAM ip_range must be a scalar")
                        .into_iter()
                        .for_each(|value| config.set_ip_range(value)),
                    "gateway" => self
                        .located_string(field.value(), "IPAM gateway must be a scalar")
                        .into_iter()
                        .for_each(|value| config.set_gateway(value)),
                    "aux_addresses" => self
                        .key_value_mapping(field.value(), "IPAM aux_addresses must be a mapping")
                        .into_iter()
                        .for_each(|value| config.set_aux_addresses(value)),
                    _ => self.record_root_unmodeled(&path, field),
                }
            }
            configs.push(config);
        }
        Some(configs)
    }

    fn volume_definitions(&mut self, value: &MergedValue) -> Vec<ProjectResource<VolumeDefinition>> {
        let Some(entries) = self.mapping(value, "top-level volumes must be a mapping") else {
            return Vec::new();
        };
        entries
            .iter()
            .filter_map(|entry| {
                let definition = self.volume_definition(entry)?;
                Some(ProjectResource {
                    name: ProjectKey::from_entry(entry),
                    definition: ProjectValue::new(definition, entry.value()),
                })
            })
            .collect()
    }

    fn volume_definition(&mut self, entry: &MergedEntry) -> Option<VolumeDefinition> {
        let value = entry.value();
        let span = effective_span(value);
        let mut volume = VolumeDefinition::new(Located::new(entry.key().to_owned(), entry_span(entry)), span);
        let fields = match value.kind() {
            MergedValueKind::Null(_) => return Some(volume),
            MergedValueKind::Mapping(fields) => fields,
            _ => {
                self.expected(value, "volume definition must be a mapping or null");
                return None;
            }
        };
        let path = ["volumes".to_owned(), entry.key().to_owned()];
        for field in fields {
            match field.key() {
                "driver" => self
                    .located_string(field.value(), "volume driver must be a scalar")
                    .into_iter()
                    .for_each(|value| volume.set_driver(value)),
                "driver_opts" => self
                    .key_value_mapping(field.value(), "volume driver_opts must be a mapping")
                    .into_iter()
                    .for_each(|value| volume.set_driver_opts(value)),
                "external" => self
                    .located_boolean(field.value(), "volume external must be a boolean")
                    .into_iter()
                    .for_each(|value| volume.set_external(value)),
                "labels" => self
                    .labels(field.value())
                    .into_iter()
                    .for_each(|value| volume.set_labels(value)),
                "name" => self
                    .located_string(field.value(), "volume custom name must be a scalar")
                    .into_iter()
                    .for_each(|value| volume.set_custom_name(value)),
                _ => self.record_root_unmodeled(&path, field),
            }
        }
        Some(volume)
    }

    fn config_definitions(&mut self, value: &MergedValue) -> Vec<ProjectResource<ConfigDefinition>> {
        let Some(entries) = self.mapping(value, "top-level configs must be a mapping") else {
            return Vec::new();
        };
        entries
            .iter()
            .filter_map(|entry| {
                let definition = self.config_definition(entry)?;
                Some(ProjectResource {
                    name: ProjectKey::from_entry(entry),
                    definition: ProjectValue::new(definition, entry.value()),
                })
            })
            .collect()
    }

    fn config_definition(&mut self, entry: &MergedEntry) -> Option<ConfigDefinition> {
        let value = entry.value();
        let span = effective_span(value);
        let mut config = ConfigDefinition::new(Located::new(entry.key().to_owned(), entry_span(entry)), span);
        let fields = match value.kind() {
            MergedValueKind::Null(_) => return Some(config),
            MergedValueKind::Mapping(fields) => fields,
            _ => {
                self.expected(value, "config definition must be a mapping or null");
                return None;
            }
        };
        let path = ["configs".to_owned(), entry.key().to_owned()];
        for field in fields {
            match field.key() {
                "file" => self
                    .located_string(field.value(), "config file must be a scalar")
                    .into_iter()
                    .for_each(|value| config.set_file(value)),
                "environment" => self
                    .located_string(field.value(), "config environment must be a scalar")
                    .into_iter()
                    .for_each(|value| config.set_environment(value)),
                "content" => self
                    .located_string(field.value(), "config content must be a scalar")
                    .into_iter()
                    .for_each(|value| config.set_content(value)),
                "external" => self
                    .located_boolean(field.value(), "config external must be a boolean")
                    .into_iter()
                    .for_each(|value| config.set_external(value)),
                "name" => self
                    .located_string(field.value(), "config custom name must be a scalar")
                    .into_iter()
                    .for_each(|value| config.set_custom_name(value)),
                _ => self.record_root_unmodeled(&path, field),
            }
        }
        Some(config)
    }

    fn secret_definitions(&mut self, value: &MergedValue) -> Vec<ProjectResource<SecretDefinition>> {
        let Some(entries) = self.mapping(value, "top-level secrets must be a mapping") else {
            return Vec::new();
        };
        entries
            .iter()
            .filter_map(|entry| {
                let definition = self.secret_definition(entry)?;
                Some(ProjectResource {
                    name: ProjectKey::from_entry(entry),
                    definition: ProjectValue::new(definition, entry.value()),
                })
            })
            .collect()
    }

    fn secret_definition(&mut self, entry: &MergedEntry) -> Option<SecretDefinition> {
        let value = entry.value();
        let span = effective_span(value);
        let mut secret = SecretDefinition::new(Located::new(entry.key().to_owned(), entry_span(entry)), span);
        let fields = match value.kind() {
            MergedValueKind::Null(_) => return Some(secret),
            MergedValueKind::Mapping(fields) => fields,
            _ => {
                self.expected(value, "secret definition must be a mapping or null");
                return None;
            }
        };
        let path = ["secrets".to_owned(), entry.key().to_owned()];
        for field in fields {
            match field.key() {
                "file" => self
                    .located_string(field.value(), "secret file must be a scalar")
                    .into_iter()
                    .for_each(|value| secret.set_file(value)),
                "environment" => self
                    .located_string(field.value(), "secret environment must be a scalar")
                    .into_iter()
                    .for_each(|value| secret.set_environment(value)),
                "external" => self
                    .located_boolean(field.value(), "secret external must be a boolean")
                    .into_iter()
                    .for_each(|value| secret.set_external(value)),
                "name" => self
                    .located_string(field.value(), "secret custom name must be a scalar")
                    .into_iter()
                    .for_each(|value| secret.set_custom_name(value)),
                _ => self.record_root_unmodeled(&path, field),
            }
        }
        Some(secret)
    }

    fn labels(&mut self, value: &MergedValue) -> Option<Labels> {
        let span = effective_span(value);
        match value.kind() {
            MergedValueKind::Sequence(_) => self
                .located_string_sequence(value, "labels must be a scalar sequence")
                .map(|values| Labels::List { span, values }),
            MergedValueKind::Mapping(_) => self
                .key_value_mapping(value, "labels must be a scalar mapping")
                .map(|entries| Labels::Map { span, entries }),
            _ => {
                self.expected(value, "labels must be a sequence or mapping");
                None
            }
        }
    }
}

fn field_reference(path: &[String], entry: &MergedEntry) -> ProjectFieldReference {
    let mut complete_path = path.to_vec();
    complete_path.push(entry.key().to_owned());
    ProjectFieldReference {
        path: complete_path,
        key: ProjectKey::from_entry(entry),
        provenance: entry.value().provenance().clone(),
        extension: entry.key().starts_with("x-"),
        sensitive: entry.value().is_sensitive(),
    }
}

fn effective_span(value: &MergedValue) -> SourceSpan {
    value
        .provenance()
        .effective_source()
        .or_else(|| value.provenance().sources().first().copied())
        .unwrap_or_else(|| SourceSpan::from_valid_offsets(SourceId::new(0), 0, 0))
}

fn entry_span(entry: &MergedEntry) -> SourceSpan {
    entry
        .key_sources()
        .last()
        .copied()
        .or_else(|| entry.key_sources().first().copied())
        .unwrap_or_else(|| effective_span(entry.value()))
}