zlayer-types 0.11.13

Shared wire types for the ZLayer platform — API DTOs, OCI image references, and related serde types.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
//! `ZLayer` V1 Service Specification Types
//!
//! This module defines all types for parsing and validating `ZLayer` deployment specs.

mod duration {
    use humantime::format_duration;
    use serde::{Deserialize, Deserializer, Serializer};
    use std::time::Duration;

    #[allow(clippy::ref_option)]
    pub fn serialize<S>(duration: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match duration {
            Some(d) => serializer.serialize_str(&format_duration(*d).to_string()),
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::Error;
        let s: Option<String> = Option::deserialize(deserializer)?;
        match s {
            Some(s) => humantime::parse_duration(&s)
                .map(Some)
                .map_err(|e| D::Error::custom(format!("invalid duration: {e}"))),
            None => Ok(None),
        }
    }

    pub mod option {
        pub use super::*;
    }

    /// Serde module for required (non-Option) Duration fields
    pub mod required {
        use humantime::format_duration;
        use serde::{Deserialize, Deserializer, Serializer};
        use std::time::Duration;

        pub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            serializer.serialize_str(&format_duration(*duration).to_string())
        }

        pub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
        where
            D: Deserializer<'de>,
        {
            use serde::de::Error;
            let s: String = String::deserialize(deserializer)?;
            humantime::parse_duration(&s)
                .map_err(|e| D::Error::custom(format!("invalid duration: {e}")))
        }
    }
}

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use validator::Validate;

/// How service replicas are allocated to nodes
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NodeMode {
    /// Containers placed on any node with capacity (default, bin-packing)
    #[default]
    Shared,
    /// Each replica gets its own dedicated node (1:1 mapping)
    Dedicated,
    /// Service is the ONLY thing on its nodes (no other services)
    Exclusive,
}

/// Service type - determines runtime behavior and scaling model
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ServiceType {
    /// Standard long-running container service
    #[default]
    Standard,
    /// WASM-based HTTP service (wasi:http/incoming-handler)
    WasmHttp,
    /// WASM-based general plugin (zlayer:plugin handler - full host access)
    WasmPlugin,
    /// WASM-based stateless request/response transformer
    WasmTransformer,
    /// WASM-based authenticator plugin (secrets + KV + HTTP)
    WasmAuthenticator,
    /// WASM-based rate limiter (KV + metrics)
    WasmRateLimiter,
    /// WASM-based request/response middleware
    WasmMiddleware,
    /// WASM-based custom router
    WasmRouter,
    /// Run-to-completion job
    Job,
}

/// Storage performance tier
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum StorageTier {
    /// Direct local filesystem (SSD/NVMe) - SQLite-safe, fast fsync
    #[default]
    Local,
    /// bcache-backed tiered storage (SSD cache + slower backend)
    Cached,
    /// NFS/network storage - NOT SQLite-safe (will warn)
    Network,
}

/// Node selection constraints for service placement
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NodeSelector {
    /// Required labels that nodes must have (all must match)
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub labels: HashMap<String, String>,
    /// Preferred labels (soft constraint, nodes with these are preferred)
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub prefer_labels: HashMap<String, String>,
}

/// Operating system a service needs to run on.
///
/// Mirrors the OS half of an OCI platform descriptor. Canonical wire strings
/// match Go's `GOOS` values (e.g. `"linux"`, `"windows"`, `"darwin"`).
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, utoipa::ToSchema,
)]
#[serde(rename_all = "lowercase")]
pub enum OsKind {
    Linux,
    Windows,
    Macos,
}

impl OsKind {
    /// Canonical OCI-style string (`"linux"` / `"windows"` / `"darwin"`).
    /// This is the same convention `Runtime.platform_resolver` uses.
    #[must_use]
    pub const fn as_oci_str(self) -> &'static str {
        match self {
            OsKind::Linux => "linux",
            OsKind::Windows => "windows",
            OsKind::Macos => "darwin",
        }
    }

    /// Detect from `std::env::consts::OS`. Unknown values return `None`.
    #[must_use]
    pub fn from_rust_os(s: &str) -> Option<Self> {
        match s {
            "linux" => Some(Self::Linux),
            "windows" => Some(Self::Windows),
            "macos" => Some(Self::Macos),
            _ => None,
        }
    }

    /// Parse the OCI-canonical OS string as written in an image manifest's
    /// `config.os` field (lowercase: `"linux"` / `"windows"` / `"darwin"`).
    /// Unknown or empty values return `None`.
    ///
    /// This is the inverse of [`Self::as_oci_str`] and is used by the
    /// registry's manifest-OS inspection (see `fetch_image_os`).
    #[must_use]
    pub fn from_oci_str(s: &str) -> Option<Self> {
        match s {
            "linux" => Some(Self::Linux),
            "windows" => Some(Self::Windows),
            "darwin" => Some(Self::Macos),
            _ => None,
        }
    }
}

/// CPU architecture a service needs. Mirrors the arch half of an OCI platform.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, utoipa::ToSchema,
)]
#[serde(rename_all = "lowercase")]
pub enum ArchKind {
    Amd64,
    Arm64,
}

impl ArchKind {
    /// Canonical OCI-style string (`"amd64"` / `"arm64"`).
    #[must_use]
    pub const fn as_oci_str(self) -> &'static str {
        match self {
            ArchKind::Amd64 => "amd64",
            ArchKind::Arm64 => "arm64",
        }
    }

    /// Detect from `std::env::consts::ARCH`. Unknown values return `None`.
    #[must_use]
    pub fn from_rust_arch(s: &str) -> Option<Self> {
        match s {
            "x86_64" => Some(Self::Amd64),
            "aarch64" => Some(Self::Arm64),
            _ => None,
        }
    }
}

/// Platform a service targets. `None` on `ServiceSpec.platform` means
/// "any agent is acceptable" (preserves backward compatibility).
//
// NOTE: no `Copy`. `os_version: Option<String>` rules it out. `OsKind` / `ArchKind`
// are still `Copy`, so field-level borrows stay ergonomic.
#[derive(
    Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, utoipa::ToSchema,
)]
pub struct TargetPlatform {
    pub os: OsKind,
    pub arch: ArchKind,
    /// Optional OS version constraint — primarily for Windows multi-platform
    /// images, where `platform.os.version` in the OCI index distinguishes build
    /// families (e.g. `10.0.26100.*` for Server 2025 / Win11 24H2,
    /// `10.0.20348.*` for Server 2022). When set on a Windows target the
    /// registry platform resolver prefers manifest entries whose `os.version`
    /// matches this value exactly or shares a `major.minor.build` prefix.
    /// Unused on Linux/macOS platforms.
    #[serde(default, rename = "osVersion", skip_serializing_if = "Option::is_none")]
    pub os_version: Option<String>,
}

impl TargetPlatform {
    #[must_use]
    pub const fn new(os: OsKind, arch: ArchKind) -> Self {
        Self {
            os,
            arch,
            os_version: None,
        }
    }

    /// Constrain the platform to a specific `os.version` string.
    ///
    /// Applies to Windows targets: the registry resolver matches manifest
    /// entries whose `platform.os.version` equals this value or starts with it
    /// (treated as a `major.minor.build` prefix). Has no effect on Linux/macOS.
    #[must_use]
    pub fn with_os_version(mut self, v: impl Into<String>) -> Self {
        self.os_version = Some(v.into());
        self
    }

    /// Canonical OCI-style string (`"linux/amd64"`, `"windows/arm64"`).
    ///
    /// Does NOT include `os_version` — use [`Self::as_detailed_str`] when the
    /// version matters (e.g. for error/log messages that need to distinguish
    /// between Windows build families).
    #[must_use]
    pub fn as_oci_str(self) -> String {
        format!("{}/{}", self.os.as_oci_str(), self.arch.as_oci_str())
    }

    /// Like [`Self::as_oci_str`] but appends ` (os.version=…)` when an
    /// `os_version` constraint is set. Intended for diagnostics, not for
    /// matching against manifest entries.
    #[must_use]
    pub fn as_detailed_str(&self) -> String {
        match &self.os_version {
            Some(v) => format!(
                "{}/{} (os.version={v})",
                self.os.as_oci_str(),
                self.arch.as_oci_str()
            ),
            None => format!("{}/{}", self.os.as_oci_str(), self.arch.as_oci_str()),
        }
    }
}

impl std::fmt::Display for TargetPlatform {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}/{}", self.os.as_oci_str(), self.arch.as_oci_str())
    }
}

/// Explicit capability declarations for WASM modules.
/// Controls which host interfaces are linked and available to the component.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
#[allow(clippy::struct_excessive_bools)]
pub struct WasmCapabilities {
    /// Config interface access (zlayer:plugin/config)
    #[serde(default = "default_true")]
    pub config: bool,
    /// Key-value storage access (zlayer:plugin/keyvalue)
    #[serde(default = "default_true")]
    pub keyvalue: bool,
    /// Logging access (zlayer:plugin/logging)
    #[serde(default = "default_true")]
    pub logging: bool,
    /// Secrets access (zlayer:plugin/secrets)
    #[serde(default)]
    pub secrets: bool,
    /// Metrics emission (zlayer:plugin/metrics)
    #[serde(default = "default_true")]
    pub metrics: bool,
    /// HTTP client for outgoing requests (wasi:http/outgoing-handler)
    #[serde(default)]
    pub http_client: bool,
    /// WASI CLI access (args, env, stdio)
    #[serde(default)]
    pub cli: bool,
    /// WASI filesystem access
    #[serde(default)]
    pub filesystem: bool,
    /// WASI sockets access (TCP/UDP)
    #[serde(default)]
    pub sockets: bool,
}

impl Default for WasmCapabilities {
    fn default() -> Self {
        Self {
            config: true,
            keyvalue: true,
            logging: true,
            secrets: false,
            metrics: true,
            http_client: false,
            cli: false,
            filesystem: false,
            sockets: false,
        }
    }
}

/// Pre-opened directory for WASM filesystem access
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct WasmPreopen {
    /// Host path to mount
    pub source: String,
    /// Guest path (visible to WASM module)
    pub target: String,
    /// Read-only access (default: false)
    #[serde(default)]
    pub readonly: bool,
}

/// Comprehensive configuration for all WASM service types.
///
/// Replaces the previous `WasmHttpConfig` with resource limits, capability
/// declarations, networking controls, and storage configuration.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
#[allow(clippy::struct_excessive_bools)]
pub struct WasmConfig {
    // --- Instance Management ---
    /// Minimum number of warm instances to keep ready
    #[serde(default = "default_min_instances")]
    pub min_instances: u32,
    /// Maximum number of instances to scale to
    #[serde(default = "default_max_instances")]
    pub max_instances: u32,
    /// Time before idle instances are terminated
    #[serde(default = "default_idle_timeout", with = "duration::required")]
    pub idle_timeout: std::time::Duration,
    /// Maximum time for a single request
    #[serde(default = "default_request_timeout", with = "duration::required")]
    pub request_timeout: std::time::Duration,

    // --- Resource Limits ---
    /// Maximum linear memory (e.g., "64Mi", "256Mi")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_memory: Option<String>,
    /// Maximum fuel (instruction count limit, 0 = unlimited)
    #[serde(default)]
    pub max_fuel: u64,
    /// Epoch interval for cooperative preemption
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "duration::option"
    )]
    pub epoch_interval: Option<std::time::Duration>,

    // --- Capabilities ---
    /// Explicit capability grants (overrides world defaults when restricting)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<WasmCapabilities>,

    // --- Networking ---
    /// Allow outgoing HTTP requests (default: true)
    #[serde(default = "default_true")]
    pub allow_http_outgoing: bool,
    /// Allowed outgoing HTTP hosts (empty = all allowed)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub allowed_hosts: Vec<String>,
    /// Allow raw TCP sockets (default: false)
    #[serde(default)]
    pub allow_tcp: bool,
    /// Allow raw UDP sockets (default: false)
    #[serde(default)]
    pub allow_udp: bool,

    // --- Storage ---
    /// Pre-opened directories (host path -> guest path)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub preopens: Vec<WasmPreopen>,
    /// Enable KV store access (default: true)
    #[serde(default = "default_true")]
    pub kv_enabled: bool,
    /// KV store namespace (default: service name)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kv_namespace: Option<String>,
    /// KV store max value size in bytes (default: 1MB)
    #[serde(default = "default_kv_max_value_size")]
    pub kv_max_value_size: u64,

    // --- Secrets ---
    /// Secret names accessible to this WASM module
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub secrets: Vec<String>,

    // --- Performance ---
    /// Pre-compile on deploy to reduce cold start (default: true)
    #[serde(default = "default_true")]
    pub precompile: bool,
}

fn default_kv_max_value_size() -> u64 {
    1_048_576 // 1MB
}

impl Default for WasmConfig {
    fn default() -> Self {
        Self {
            min_instances: default_min_instances(),
            max_instances: default_max_instances(),
            idle_timeout: default_idle_timeout(),
            request_timeout: default_request_timeout(),
            max_memory: None,
            max_fuel: 0,
            epoch_interval: None,
            capabilities: None,
            allow_http_outgoing: true,
            allowed_hosts: Vec::new(),
            allow_tcp: false,
            allow_udp: false,
            preopens: Vec::new(),
            kv_enabled: true,
            kv_namespace: None,
            kv_max_value_size: default_kv_max_value_size(),
            secrets: Vec::new(),
            precompile: true,
        }
    }
}

/// Configuration for WASM HTTP services with instance pooling
#[deprecated(note = "Use WasmConfig instead")]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct WasmHttpConfig {
    /// Minimum number of warm instances to keep ready
    #[serde(default = "default_min_instances")]
    pub min_instances: u32,
    /// Maximum number of instances to scale to
    #[serde(default = "default_max_instances")]
    pub max_instances: u32,
    /// Time before idle instances are terminated
    #[serde(default = "default_idle_timeout", with = "duration::required")]
    pub idle_timeout: std::time::Duration,
    /// Maximum time for a single request
    #[serde(default = "default_request_timeout", with = "duration::required")]
    pub request_timeout: std::time::Duration,
}

fn default_min_instances() -> u32 {
    0
}

fn default_max_instances() -> u32 {
    10
}

fn default_idle_timeout() -> std::time::Duration {
    std::time::Duration::from_secs(300)
}

fn default_request_timeout() -> std::time::Duration {
    std::time::Duration::from_secs(30)
}

#[allow(deprecated)]
impl Default for WasmHttpConfig {
    fn default() -> Self {
        Self {
            min_instances: default_min_instances(),
            max_instances: default_max_instances(),
            idle_timeout: default_idle_timeout(),
            request_timeout: default_request_timeout(),
        }
    }
}

#[allow(deprecated)]
impl From<WasmHttpConfig> for WasmConfig {
    fn from(old: WasmHttpConfig) -> Self {
        Self {
            min_instances: old.min_instances,
            max_instances: old.max_instances,
            idle_timeout: old.idle_timeout,
            request_timeout: old.request_timeout,
            ..Default::default()
        }
    }
}

impl ServiceType {
    /// Returns true if this is any WASM service type
    #[must_use]
    pub fn is_wasm(&self) -> bool {
        matches!(
            self,
            ServiceType::WasmHttp
                | ServiceType::WasmPlugin
                | ServiceType::WasmTransformer
                | ServiceType::WasmAuthenticator
                | ServiceType::WasmRateLimiter
                | ServiceType::WasmMiddleware
                | ServiceType::WasmRouter
        )
    }

    /// Returns the default capabilities for this WASM service type.
    /// Returns None for non-WASM types.
    #[must_use]
    pub fn default_wasm_capabilities(&self) -> Option<WasmCapabilities> {
        match self {
            ServiceType::WasmHttp | ServiceType::WasmRouter => Some(WasmCapabilities {
                config: true,
                keyvalue: true,
                logging: true,
                secrets: false,
                metrics: false,
                http_client: true,
                cli: false,
                filesystem: false,
                sockets: false,
            }),
            ServiceType::WasmPlugin => Some(WasmCapabilities {
                config: true,
                keyvalue: true,
                logging: true,
                secrets: true,
                metrics: true,
                http_client: true,
                cli: true,
                filesystem: true,
                sockets: false,
            }),
            ServiceType::WasmTransformer => Some(WasmCapabilities {
                config: false,
                keyvalue: false,
                logging: true,
                secrets: false,
                metrics: false,
                http_client: false,
                cli: true,
                filesystem: false,
                sockets: false,
            }),
            ServiceType::WasmAuthenticator => Some(WasmCapabilities {
                config: true,
                keyvalue: false,
                logging: true,
                secrets: true,
                metrics: false,
                http_client: true,
                cli: false,
                filesystem: false,
                sockets: false,
            }),
            ServiceType::WasmRateLimiter => Some(WasmCapabilities {
                config: true,
                keyvalue: true,
                logging: true,
                secrets: false,
                metrics: true,
                http_client: false,
                cli: true,
                filesystem: false,
                sockets: false,
            }),
            ServiceType::WasmMiddleware => Some(WasmCapabilities {
                config: true,
                keyvalue: false,
                logging: true,
                secrets: false,
                metrics: false,
                http_client: true,
                cli: false,
                filesystem: false,
                sockets: false,
            }),
            _ => None,
        }
    }
}

fn default_api_bind() -> String {
    "0.0.0.0:3669".to_string()
}

/// API server configuration (embedded in deploy/up flows)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ApiSpec {
    /// Enable the API server (default: true)
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Bind address (default: "0.0.0.0:3669")
    #[serde(default = "default_api_bind")]
    pub bind: String,
    /// JWT secret (reads `ZLAYER_JWT_SECRET` env var if not set)
    #[serde(default)]
    pub jwt_secret: Option<String>,
    /// Enable Swagger UI (default: true)
    #[serde(default = "default_true")]
    pub swagger: bool,
}

impl Default for ApiSpec {
    fn default() -> Self {
        Self {
            enabled: true,
            bind: default_api_bind(),
            jwt_secret: None,
            swagger: true,
        }
    }
}

/// Top-level deployment specification
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Validate)]
#[serde(deny_unknown_fields)]
pub struct DeploymentSpec {
    /// Spec version (must be "v1")
    #[validate(custom(function = "crate::spec::validate::validate_version_wrapper"))]
    pub version: String,

    /// Deployment name (used for overlays, DNS)
    #[validate(custom(function = "crate::spec::validate::validate_deployment_name_wrapper"))]
    pub deployment: String,

    /// Service definitions
    #[serde(default)]
    #[validate(nested)]
    pub services: HashMap<String, ServiceSpec>,

    /// External service definitions (proxy backends without containers)
    ///
    /// External services register static backend addresses with the proxy
    /// for host/path-based routing without starting any containers.
    /// Useful for proxying to services running outside of `ZLayer`
    /// (e.g., on other machines reachable via VPN).
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    #[validate(nested)]
    pub externals: HashMap<String, ExternalSpec>,

    /// Top-level tunnel definitions (not tied to service endpoints)
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub tunnels: HashMap<String, TunnelDefinition>,

    /// API server configuration (enabled by default)
    #[serde(default)]
    pub api: ApiSpec,
}

/// External service specification (proxy backend without a container)
///
/// Defines a service that is not managed by `ZLayer` but should be proxied
/// through `ZLayer`'s reverse proxy. The proxy registers static backend
/// addresses and routes traffic based on endpoint host/path matching.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
pub struct ExternalSpec {
    /// Static backend addresses (e.g., `["100.64.1.5:8096", "192.168.1.10:8096"]`)
    ///
    /// These are the upstream addresses the proxy will forward traffic to.
    /// At least one backend is required.
    #[validate(length(min = 1, message = "at least one backend address is required"))]
    pub backends: Vec<String>,

    /// Endpoint definitions (proxy bindings)
    ///
    /// Defines how public/internal traffic is routed to this external service.
    #[serde(default)]
    #[validate(nested)]
    pub endpoints: Vec<EndpointSpec>,

    /// Health check configuration
    ///
    /// When specified, the proxy will health-check backends and remove
    /// unhealthy ones from the rotation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub health: Option<HealthSpec>,
}

/// Top-level tunnel definition (not tied to a service endpoint)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct TunnelDefinition {
    /// Source node
    pub from: String,

    /// Destination node
    pub to: String,

    /// Local port on source
    pub local_port: u16,

    /// Remote port on destination
    pub remote_port: u16,

    /// Protocol (tcp/udp, defaults to tcp)
    #[serde(default)]
    pub protocol: TunnelProtocol,

    /// Exposure type (defaults to internal)
    #[serde(default)]
    pub expose: ExposeType,
}

/// Protocol for tunnel connections (tcp or udp only)
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum TunnelProtocol {
    #[default]
    Tcp,
    Udp,
}

/// Log output configuration for services and jobs.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct LogsConfig {
    /// Where to write logs: "disk" (default) or "memory"
    #[serde(default = "default_logs_destination")]
    pub destination: String,

    /// Maximum log size in bytes (default: 100MB)
    #[serde(default = "default_logs_max_size")]
    pub max_size_bytes: u64,

    /// Log retention in seconds (default: 7 days)
    #[serde(default = "default_logs_retention")]
    pub retention_secs: u64,
}

fn default_logs_destination() -> String {
    "disk".to_string()
}

fn default_logs_max_size() -> u64 {
    100 * 1024 * 1024 // 100MB
}

fn default_logs_retention() -> u64 {
    7 * 24 * 60 * 60 // 7 days
}

impl Default for LogsConfig {
    fn default() -> Self {
        Self {
            destination: default_logs_destination(),
            max_size_bytes: default_logs_max_size(),
            retention_secs: default_logs_retention(),
        }
    }
}

/// Network mode for a service container.
///
/// Mirrors Docker's `HostConfig.NetworkMode` semantics. Accepts both an
/// enum-tagged form (e.g. `network_mode: { bridge: { name: my-net } }`) and a
/// string form (e.g. `"host"`, `"bridge:my-net"`, `"container:abc123"`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, utoipa::ToSchema)]
#[serde(rename_all = "lowercase")]
pub enum NetworkMode {
    /// Default networking (overlay / bridge as configured by the platform).
    #[default]
    Default,
    /// Share the host network namespace (Docker `--network host`).
    Host,
    /// Disable networking entirely (Docker `--network none`).
    None,
    /// Attach to a Docker bridge network. When `name` is `None`, uses the
    /// default `bridge` network.
    Bridge {
        #[serde(default)]
        name: Option<String>,
    },
    /// Attach to another container's network namespace
    /// (Docker `--network container:<id>`).
    Container { id: String },
}

/// String-or-enum deserializer for [`NetworkMode`].
///
/// Accepts the same strings Docker accepts on `HostConfig.NetworkMode`:
/// `"default"`, `"host"`, `"none"`, `"bridge"`, `"bridge:<name>"`, and
/// `"container:<id>"`. Also accepts the enum-tagged YAML/JSON form produced by
/// the derived [`Serialize`] impl (e.g. `bridge: { name: my-net }`).
fn deserialize_network_mode<'de, D>(deserializer: D) -> Result<NetworkMode, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::Error;

    /// Inline mirror of [`NetworkMode`] used purely for the "object" form.
    /// We re-deserialize the captured YAML/JSON value into this and then map
    /// it back, which correctly drives `deserialize_enum` even when the input
    /// originally came from a `deserialize_any` path.
    #[derive(Deserialize)]
    #[serde(rename_all = "lowercase")]
    enum Inner {
        Default,
        Host,
        None,
        Bridge {
            #[serde(default)]
            name: Option<String>,
        },
        Container {
            id: String,
        },
    }

    impl From<Inner> for NetworkMode {
        fn from(i: Inner) -> Self {
            match i {
                Inner::Default => Self::Default,
                Inner::Host => Self::Host,
                Inner::None => Self::None,
                Inner::Bridge { name } => Self::Bridge { name },
                Inner::Container { id } => Self::Container { id },
            }
        }
    }

    // Capture the input as a self-describing serde value so we can branch
    // on whether it is a string (Docker-style) or an externally-tagged
    // enum (`{ bridge: { name } }`-style).
    let value = serde_yaml::Value::deserialize(deserializer)?;

    if let Some(s) = value.as_str() {
        return match s {
            "default" => Ok(NetworkMode::Default),
            "host" => Ok(NetworkMode::Host),
            "none" => Ok(NetworkMode::None),
            "bridge" => Ok(NetworkMode::Bridge { name: None }),
            _ => {
                if let Some(rest) = s.strip_prefix("bridge:") {
                    if rest.is_empty() {
                        Ok(NetworkMode::Bridge { name: None })
                    } else {
                        Ok(NetworkMode::Bridge {
                            name: Some(rest.to_string()),
                        })
                    }
                } else if let Some(rest) = s.strip_prefix("container:") {
                    if rest.is_empty() {
                        Err(D::Error::custom(
                            "network mode \"container:<id>\" requires a non-empty id",
                        ))
                    } else {
                        Ok(NetworkMode::Container {
                            id: rest.to_string(),
                        })
                    }
                } else {
                    Err(D::Error::custom(format!("unknown network mode: {s}")))
                }
            }
        };
    }

    let inner: Inner = serde_yaml::from_value(value).map_err(D::Error::custom)?;
    Ok(NetworkMode::from(inner))
}

/// Per-process resource limit (Docker `--ulimit` style).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
#[serde(deny_unknown_fields)]
pub struct UlimitSpec {
    /// Soft limit.
    #[serde(default)]
    pub soft: i64,
    /// Hard limit.
    #[serde(default)]
    pub hard: i64,
}

/// Per-service specification
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Validate)]
#[serde(from = "ServiceSpecCompat")]
#[allow(clippy::struct_excessive_bools)]
pub struct ServiceSpec {
    /// Resource type (service, job, cron)
    #[serde(default = "default_resource_type")]
    pub rtype: ResourceType,

    /// Cron schedule expression (only for rtype: cron)
    /// Uses 7-field cron syntax: "sec min hour day-of-month month day-of-week year"
    /// Examples:
    ///   - "0 0 0 * * * *" (daily at midnight)
    ///   - "0 */5 * * * * *" (every 5 minutes)
    ///   - "0 0 12 * * MON-FRI *" (weekdays at noon)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[validate(custom(function = "crate::spec::validate::validate_schedule_wrapper"))]
    pub schedule: Option<String>,

    /// Container image specification
    #[validate(nested)]
    pub image: ImageSpec,

    /// Resource limits
    #[serde(default)]
    #[validate(nested)]
    pub resources: ResourcesSpec,

    /// Environment variables for the service
    ///
    /// Values can be:
    /// - Plain strings: `"value"`
    /// - Host env refs: `$E:VAR_NAME`
    /// - Secret refs: `$S:secret-name` or `$S:@service/secret-name`
    #[serde(default)]
    pub env: HashMap<String, String>,

    /// Command override (entrypoint, args, workdir)
    #[serde(default)]
    pub command: CommandSpec,

    /// Network configuration
    #[serde(default)]
    pub network: ServiceNetworkSpec,

    /// Endpoint definitions (proxy bindings)
    #[serde(default)]
    #[validate(nested)]
    pub endpoints: Vec<EndpointSpec>,

    /// Scaling configuration
    #[serde(default)]
    #[validate(custom(function = "crate::spec::validate::validate_scale_spec"))]
    pub scale: ScaleSpec,

    /// Dependency specifications
    #[serde(default)]
    pub depends: Vec<DependsSpec>,

    /// Health check configuration
    #[serde(default = "default_health")]
    pub health: HealthSpec,

    /// Init actions (pre-start lifecycle steps)
    #[serde(default)]
    pub init: InitSpec,

    /// Error handling policies
    #[serde(default)]
    pub errors: ErrorsSpec,

    /// Container lifecycle policy (e.g., delete-on-exit).
    ///
    /// Purely declarative on this type; downstream layers (agent / API /
    /// scheduler) read this field to decide whether to clean up the
    /// container record after termination.
    #[serde(default)]
    pub lifecycle: LifecycleSpec,

    /// Device passthrough (e.g., /dev/kvm for VMs)
    #[serde(default)]
    pub devices: Vec<DeviceSpec>,

    /// Storage mounts for the container
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub storage: Vec<StorageSpec>,

    /// Host-to-container port mappings (Docker's `-p host:container/proto`).
    ///
    /// Each entry publishes a container port on the host. When `host_port` is
    /// `None` (or zero), the daemon assigns an ephemeral host port.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub port_mappings: Vec<PortMapping>,

    /// Linux capabilities to add (e.g., `SYS_ADMIN`, `NET_ADMIN`).
    ///
    /// Also accepts the Docker-compatible alias `cap_add` on input.
    #[serde(default, alias = "cap_add", skip_serializing_if = "Vec::is_empty")]
    pub capabilities: Vec<String>,

    /// Linux capabilities to drop (Docker `--cap-drop`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cap_drop: Vec<String>,

    /// Run container in privileged mode (all capabilities + all devices)
    #[serde(default)]
    pub privileged: bool,

    /// Node allocation mode (shared, dedicated, exclusive)
    #[serde(default)]
    pub node_mode: NodeMode,

    /// Node selection constraints (required/preferred labels)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub node_selector: Option<NodeSelector>,

    /// Target platform for this service. When `None` (default), the service is
    /// eligible to run on any agent regardless of OS/architecture. When `Some`,
    /// the scheduler will only place replicas on agents whose platform matches.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub platform: Option<TargetPlatform>,

    /// Service type (standard, `wasm_http`, `wasm_plugin`, etc.)
    #[serde(default)]
    pub service_type: ServiceType,

    /// WASM configuration (used when `service_type` is any Wasm* variant)
    /// Also accepts the deprecated `wasm_http` key for backward compatibility.
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "wasm_http")]
    pub wasm: Option<WasmConfig>,

    /// Log output configuration. If not set, uses platform defaults.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub logs: Option<LogsConfig>,

    /// Use host networking (container shares host network namespace)
    ///
    /// When true, the container will NOT get its own network namespace.
    /// This is set programmatically via the `--host-network` CLI flag, not in YAML specs.
    #[serde(skip)]
    pub host_network: bool,

    /// Container hostname (maps to Docker's `--hostname`).
    ///
    /// When set, the container's `/etc/hostname` and initial kernel hostname
    /// are configured to this value. Ignored when `host_network` is true
    /// (the container inherits the host's hostname).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hostname: Option<String>,

    /// Additional DNS servers for the container (maps to Docker's `--dns`).
    ///
    /// Each entry must be a plausible IPv4 or IPv6 address. Forwarded to the
    /// container runtime as resolver addresses ahead of the platform defaults.
    /// Ignored when `host_network` is true.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dns: Vec<String>,

    /// Extra `hostname:ip` entries appended to `/etc/hosts` (maps to Docker's
    /// `--add-host`).
    ///
    /// Each entry must be in the form `"<hostname>:<ip>"`. The special literal
    /// `host-gateway` is accepted as the `<ip>` half (resolved by Docker /
    /// bollard to the host-visible gateway address, commonly used with
    /// `host.docker.internal:host-gateway`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extra_hosts: Vec<String>,

    /// Container restart policy (Docker-style).
    ///
    /// Controls when the runtime should automatically restart the container
    /// after it exits. Maps to Docker's `HostConfig.RestartPolicy`. Named
    /// `ContainerRestartPolicy` to avoid colliding with `ZLayer`'s existing
    /// `PanicPolicy` (which controls post-panic behavior, not runtime-level
    /// restarts).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub restart_policy: Option<ContainerRestartPolicy>,

    /// Free-form key/value labels attached to the container
    /// (Docker `--label`).
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub labels: HashMap<String, String>,

    /// User and group override for the container's main process
    /// (Docker `--user uid:gid`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,

    /// Signal sent to the container's main process to request a graceful
    /// shutdown (Docker `--stop-signal`). Accepts e.g. `"SIGTERM"` or `"15"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stop_signal: Option<String>,

    /// Grace period to wait between the stop signal and a forced kill
    /// (Docker `--stop-timeout`).
    #[serde(
        default,
        with = "duration::option",
        skip_serializing_if = "Option::is_none"
    )]
    pub stop_grace_period: Option<std::time::Duration>,

    /// Kernel sysctl overrides (Docker `--sysctl`).
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub sysctls: HashMap<String, String>,

    /// Per-process ulimits (Docker `--ulimit`).
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub ulimits: HashMap<String, UlimitSpec>,

    /// Security options such as `apparmor=...`, `seccomp=...`,
    /// `no-new-privileges:true` (Docker `--security-opt`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub security_opt: Vec<String>,

    /// PID namespace mode (Docker `--pid`). Accepts e.g. `"host"` or
    /// `"container:<id>"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pid_mode: Option<String>,

    /// IPC namespace mode (Docker `--ipc`). Accepts e.g. `"host"`,
    /// `"shareable"`, `"private"`, or `"container:<id>"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ipc_mode: Option<String>,

    /// Network mode (Docker `--network`). Accepts both the enum-tagged form
    /// and the Docker-style strings (`"host"`, `"none"`, `"bridge"`,
    /// `"bridge:<name>"`, `"container:<id>"`).
    #[serde(default, deserialize_with = "deserialize_network_mode")]
    pub network_mode: NetworkMode,

    /// Additional groups to add to the container process
    /// (Docker `--group-add`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extra_groups: Vec<String>,

    /// Mount the container's root filesystem read-only (Docker `--read-only`).
    #[serde(default)]
    pub read_only_root_fs: bool,

    /// Run a Docker-supplied init process (PID 1) inside the container
    /// (Docker `--init`). Distinct from [`ServiceSpec::init`] which controls
    /// `ZLayer`'s pre-start init actions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub init_container: Option<bool>,

    /// Allocate a TTY for the container's main process (Docker `--tty`,
    /// compose `tty: true`).
    #[serde(default)]
    pub tty: bool,

    /// Keep STDIN open even when nothing is attached (Docker `--interactive`,
    /// compose `stdin_open: true`).
    #[serde(default)]
    pub stdin_open: bool,

    /// User namespace mode (Docker `--userns`). Accepts e.g. `"host"` or
    /// a remap-spec name configured on the daemon.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub userns_mode: Option<String>,

    /// Cgroup parent path (Docker `--cgroup-parent`). When set, the runtime
    /// places the container under the given cgroup hierarchy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cgroup_parent: Option<String>,

    /// Container ports exposed but not published to the host (compose
    /// `expose:`). Each entry is a port string, optionally `port/proto`
    /// (e.g. `"3000"`, `"8080/tcp"`). Treated as documentation by the
    /// runtime; downstream networking layers may use this list to allow
    /// inter-service traffic without publishing to the host.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub expose: Vec<String>,
}

/// Deserialization shim for [`ServiceSpec`].
///
/// Mirrors `ServiceSpec`'s field shape so that the derived `Deserialize` impl
/// can pick up the YAML/JSON value, then [`From::from`] folds the deprecated
/// `host_network: bool` flag into the typed [`NetworkMode`] before handing the
/// finalized struct back to the caller.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(clippy::struct_excessive_bools)]
struct ServiceSpecCompat {
    #[serde(default = "default_resource_type")]
    rtype: ResourceType,
    #[serde(default)]
    schedule: Option<String>,
    image: ImageSpec,
    #[serde(default)]
    resources: ResourcesSpec,
    #[serde(default)]
    env: HashMap<String, String>,
    #[serde(default)]
    command: CommandSpec,
    #[serde(default)]
    network: ServiceNetworkSpec,
    #[serde(default)]
    endpoints: Vec<EndpointSpec>,
    #[serde(default)]
    scale: ScaleSpec,
    #[serde(default)]
    depends: Vec<DependsSpec>,
    #[serde(default = "default_health")]
    health: HealthSpec,
    #[serde(default)]
    init: InitSpec,
    #[serde(default)]
    errors: ErrorsSpec,
    #[serde(default)]
    lifecycle: LifecycleSpec,
    #[serde(default)]
    devices: Vec<DeviceSpec>,
    #[serde(default)]
    storage: Vec<StorageSpec>,
    #[serde(default)]
    port_mappings: Vec<PortMapping>,
    #[serde(default, alias = "cap_add")]
    capabilities: Vec<String>,
    #[serde(default)]
    cap_drop: Vec<String>,
    #[serde(default)]
    privileged: bool,
    #[serde(default)]
    node_mode: NodeMode,
    #[serde(default)]
    node_selector: Option<NodeSelector>,
    #[serde(default)]
    platform: Option<TargetPlatform>,
    #[serde(default)]
    service_type: ServiceType,
    #[serde(default, alias = "wasm_http")]
    wasm: Option<WasmConfig>,
    #[serde(default)]
    logs: Option<LogsConfig>,
    /// Backwards-compat shim: when `host_network: true` is present in the input,
    /// it is folded into `network_mode = NetworkMode::Host` during conversion.
    #[serde(default)]
    host_network: Option<bool>,
    #[serde(default)]
    hostname: Option<String>,
    #[serde(default)]
    dns: Vec<String>,
    #[serde(default)]
    extra_hosts: Vec<String>,
    #[serde(default)]
    restart_policy: Option<ContainerRestartPolicy>,
    #[serde(default)]
    labels: HashMap<String, String>,
    #[serde(default)]
    user: Option<String>,
    #[serde(default)]
    stop_signal: Option<String>,
    #[serde(default, with = "duration::option")]
    stop_grace_period: Option<std::time::Duration>,
    #[serde(default)]
    sysctls: HashMap<String, String>,
    #[serde(default)]
    ulimits: HashMap<String, UlimitSpec>,
    #[serde(default)]
    security_opt: Vec<String>,
    #[serde(default)]
    pid_mode: Option<String>,
    #[serde(default)]
    ipc_mode: Option<String>,
    #[serde(default, deserialize_with = "deserialize_network_mode")]
    network_mode: NetworkMode,
    #[serde(default)]
    extra_groups: Vec<String>,
    #[serde(default)]
    read_only_root_fs: bool,
    #[serde(default)]
    init_container: Option<bool>,
    #[serde(default)]
    tty: bool,
    #[serde(default)]
    stdin_open: bool,
    #[serde(default)]
    userns_mode: Option<String>,
    #[serde(default)]
    cgroup_parent: Option<String>,
    #[serde(default)]
    expose: Vec<String>,
}

impl From<ServiceSpecCompat> for ServiceSpec {
    fn from(c: ServiceSpecCompat) -> Self {
        // If the deprecated `host_network: true` flag is set, fold it into
        // the typed network mode unless the caller already supplied a
        // non-default value. This keeps existing in-process callers and
        // any legacy YAML that still emits `host_network: true` working.
        let network_mode = match (c.host_network, &c.network_mode) {
            (Some(true), NetworkMode::Default) => NetworkMode::Host,
            _ => c.network_mode,
        };
        let host_network = c.host_network.unwrap_or(false) || network_mode == NetworkMode::Host;

        Self {
            rtype: c.rtype,
            schedule: c.schedule,
            image: c.image,
            resources: c.resources,
            env: c.env,
            command: c.command,
            network: c.network,
            endpoints: c.endpoints,
            scale: c.scale,
            depends: c.depends,
            health: c.health,
            init: c.init,
            errors: c.errors,
            lifecycle: c.lifecycle,
            devices: c.devices,
            storage: c.storage,
            port_mappings: c.port_mappings,
            capabilities: c.capabilities,
            cap_drop: c.cap_drop,
            privileged: c.privileged,
            node_mode: c.node_mode,
            node_selector: c.node_selector,
            platform: c.platform,
            service_type: c.service_type,
            wasm: c.wasm,
            logs: c.logs,
            host_network,
            hostname: c.hostname,
            dns: c.dns,
            extra_hosts: c.extra_hosts,
            restart_policy: c.restart_policy,
            labels: c.labels,
            user: c.user,
            stop_signal: c.stop_signal,
            stop_grace_period: c.stop_grace_period,
            sysctls: c.sysctls,
            ulimits: c.ulimits,
            security_opt: c.security_opt,
            pid_mode: c.pid_mode,
            ipc_mode: c.ipc_mode,
            network_mode,
            extra_groups: c.extra_groups,
            read_only_root_fs: c.read_only_root_fs,
            init_container: c.init_container,
            tty: c.tty,
            stdin_open: c.stdin_open,
            userns_mode: c.userns_mode,
            cgroup_parent: c.cgroup_parent,
            expose: c.expose,
        }
    }
}

/// Command override specification (Section 5.5)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(deny_unknown_fields)]
pub struct CommandSpec {
    /// Override image ENTRYPOINT
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entrypoint: Option<Vec<String>>,

    /// Override image CMD
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub args: Option<Vec<String>>,

    /// Override working directory
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workdir: Option<String>,
}

fn default_resource_type() -> ResourceType {
    ResourceType::Service
}

fn default_health() -> HealthSpec {
    HealthSpec {
        start_grace: Some(std::time::Duration::from_secs(5)),
        interval: None,
        timeout: None,
        retries: 3,
        check: HealthCheck::Tcp { port: 0 },
    }
}

/// Resource type - determines container lifecycle
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ResourceType {
    /// Long-running container, receives traffic, load-balanced
    Service,
    /// Run-to-completion, triggered by endpoint/CLI/internal system
    Job,
    /// Scheduled run-to-completion, time-triggered
    Cron,
}

/// Container image specification
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
pub struct ImageSpec {
    /// Image name (e.g., "ghcr.io/org/api:latest")
    #[serde(with = "crate::image_ref_serde")]
    pub name: crate::ImageReference,

    /// When to pull the image
    #[serde(default = "default_pull_policy")]
    pub pull_policy: PullPolicy,
}

fn default_pull_policy() -> PullPolicy {
    PullPolicy::IfNotPresent
}

/// Image pull policy
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PullPolicy {
    /// Always pull the image, even if cached
    Always,
    /// Resolve remote digest; pull and recreate when it differs from local/running
    Newer,
    /// Pull only if not present locally
    IfNotPresent,
    /// Never pull, use local image only
    Never,
}

/// Resolve the effective pull policy for a deploy/scale operation.
///
/// The serde default for `pull_policy` is `IfNotPresent` (preserved for
/// backwards compatibility). When the user has not opted out (i.e. the policy
/// is the default `IfNotPresent`) AND the image tag is `:latest` or unspecified,
/// we auto-upgrade to `Newer` so freshly-pushed `:latest` images get picked up
/// on redeploy. Users who explicitly want immutable behaviour on a `:latest`
/// tag can set `pull_policy: never`.
#[must_use]
pub fn effective_pull_policy(image: &crate::ImageReference, spec_policy: PullPolicy) -> PullPolicy {
    match spec_policy {
        PullPolicy::Always | PullPolicy::Never | PullPolicy::Newer => spec_policy,
        PullPolicy::IfNotPresent => {
            // Auto-upgrade IfNotPresent to Newer for :latest / no-tag images
            if image_is_latest_or_untagged(image) {
                PullPolicy::Newer
            } else {
                PullPolicy::IfNotPresent
            }
        }
    }
}

fn image_is_latest_or_untagged(image: &crate::ImageReference) -> bool {
    // `ImageReference` is `oci_spec::distribution::Reference`, which exposes a
    // clean `tag()` accessor returning `Option<&str>`. No tag, or tag "latest",
    // is treated as the rolling case.
    match image.tag() {
        None => true,
        Some(tag) => tag == "latest",
    }
}

/// Device passthrough specification
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Validate, utoipa::ToSchema)]
#[serde(deny_unknown_fields)]
pub struct DeviceSpec {
    /// Host device path (e.g., /dev/kvm, /dev/net/tun)
    #[validate(length(min = 1, message = "device path cannot be empty"))]
    pub path: String,

    /// Allow read access
    #[serde(default = "default_true")]
    pub read: bool,

    /// Allow write access
    #[serde(default = "default_true")]
    pub write: bool,

    /// Allow mknod (create device nodes)
    #[serde(default)]
    pub mknod: bool,
}

fn default_true() -> bool {
    true
}

/// Storage mount specification
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields, tag = "type", rename_all = "snake_case")]
pub enum StorageSpec {
    /// Bind mount from host path to container
    Bind {
        source: String,
        target: String,
        #[serde(default)]
        readonly: bool,
    },
    /// Named persistent storage volume
    Named {
        name: String,
        target: String,
        #[serde(default)]
        readonly: bool,
        /// Performance tier (default: local, SQLite-safe)
        #[serde(default)]
        tier: StorageTier,
        /// Optional size limit (e.g., "1Gi", "512Mi")
        #[serde(default, skip_serializing_if = "Option::is_none")]
        size: Option<String>,
    },
    /// Anonymous storage (auto-named, container lifecycle)
    Anonymous {
        target: String,
        /// Performance tier (default: local)
        #[serde(default)]
        tier: StorageTier,
    },
    /// Memory-backed tmpfs mount
    Tmpfs {
        target: String,
        #[serde(default)]
        size: Option<String>,
        #[serde(default)]
        mode: Option<u32>,
    },
    /// S3-backed FUSE mount
    S3 {
        bucket: String,
        #[serde(default)]
        prefix: Option<String>,
        target: String,
        #[serde(default)]
        readonly: bool,
        #[serde(default)]
        endpoint: Option<String>,
        #[serde(default)]
        credentials: Option<String>,
    },
}

/// Resource limits (upper bounds, not reservations)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, Validate)]
#[serde(deny_unknown_fields)]
pub struct ResourcesSpec {
    /// CPU limit (cores, e.g., 0.5, 1, 2)
    #[serde(default)]
    #[validate(custom(function = "crate::spec::validate::validate_cpu_option_wrapper"))]
    pub cpu: Option<f64>,

    /// Memory limit (e.g., "512Mi", "1Gi", "2Gi")
    #[serde(default)]
    #[validate(custom(function = "crate::spec::validate::validate_memory_option_wrapper"))]
    pub memory: Option<String>,

    /// GPU resource request
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gpu: Option<GpuSpec>,

    /// Maximum number of processes the container may spawn
    /// (Docker `--pids-limit`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pids_limit: Option<i64>,

    /// CPUs that the container is allowed to execute on (Docker `--cpuset-cpus`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cpuset: Option<String>,

    /// Relative CPU shares (Docker `--cpu-shares`). Default weight is 1024.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cpu_shares: Option<u32>,

    /// Total memory limit including swap (Docker `--memory-swap`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory_swap: Option<String>,

    /// Soft memory limit (Docker `--memory-reservation`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory_reservation: Option<String>,

    /// Container memory swappiness, 0-100 (Docker `--memory-swappiness`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory_swappiness: Option<u8>,

    /// OOM-killer score adjustment (Docker `--oom-score-adj`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub oom_score_adj: Option<i32>,

    /// Disable the OOM killer for the container (Docker `--oom-kill-disable`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub oom_kill_disable: Option<bool>,

    /// Block IO weight, 10-1000 (Docker `--blkio-weight`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub blkio_weight: Option<u16>,
}

/// Scheduling policy for GPU workloads
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "kebab-case")]
pub enum SchedulingPolicy {
    /// Place as many replicas as possible; partial placement is acceptable (default)
    #[default]
    BestEffort,
    /// All replicas must be placed or none are; prevents partial GPU job deployment
    Gang,
    /// Spread replicas across nodes to maximize GPU distribution
    Spread,
}

/// GPU sharing mode controlling how GPU resources are multiplexed.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "kebab-case")]
pub enum GpuSharingMode {
    /// Whole GPU per container (default). No sharing.
    #[default]
    Exclusive,
    /// NVIDIA Multi-Process Service: concurrent GPU compute sharing.
    /// Multiple containers run GPU kernels simultaneously with hardware isolation.
    Mps,
    /// NVIDIA time-slicing: round-robin GPU access across containers.
    /// Lower overhead than MPS but no concurrent execution.
    TimeSlice,
}

/// Configuration for distributed GPU job coordination.
///
/// When enabled on a multi-replica GPU service, `ZLayer` injects standard
/// distributed training environment variables (`MASTER_ADDR`, `MASTER_PORT`,
/// `WORLD_SIZE`, `RANK`, `LOCAL_RANK`) so frameworks like `PyTorch`, `Horovod`,
/// and `DeepSpeed` can coordinate automatically.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
pub struct DistributedConfig {
    /// Communication backend: "nccl" (default), "gloo", or "mpi"
    #[serde(default = "default_dist_backend")]
    pub backend: String,
    /// Port for rank-0 master coordination (default: 29500)
    #[serde(default = "default_dist_port")]
    pub master_port: u16,
}

fn default_dist_backend() -> String {
    "nccl".to_string()
}

fn default_dist_port() -> u16 {
    29500
}

/// GPU resource specification
///
/// Supported vendors:
/// - `nvidia` - NVIDIA GPUs via NVIDIA Container Toolkit (default)
/// - `amd` - AMD GPUs via `ROCm` (/dev/kfd + /dev/dri/renderD*)
/// - `intel` - Intel GPUs via VAAPI/i915 (/dev/dri/renderD*)
/// - `apple` - Apple Silicon GPUs via Metal/MPS (macOS only)
///
/// Unknown vendors fall back to DRI render node passthrough.
///
/// ## GPU mode (macOS only)
///
/// When `vendor` is `"apple"`, the `mode` field controls how GPU access is provided:
/// - `"native"` -- Seatbelt sandbox with direct Metal/MPS access (lowest overhead)
/// - `"vm"` -- libkrun micro-VM with GPU forwarding (stronger isolation)
/// - `None` (default) -- Auto-select based on platform and vendor
///
/// On Linux, `mode` is ignored; GPU passthrough always uses device node binding.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
pub struct GpuSpec {
    /// Number of GPUs to request
    #[serde(default = "default_gpu_count")]
    pub count: u32,
    /// GPU vendor (`nvidia`, `amd`, `intel`, `apple`) - defaults to `nvidia`
    #[serde(default = "default_gpu_vendor")]
    pub vendor: String,
    /// GPU access mode (macOS only): `"native"`, `"vm"`, or `None` for auto-select
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mode: Option<String>,
    /// Pin to a specific GPU model (e.g. "A100", "H100").
    /// Substring match against detected GPU model names.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// Scheduling policy for GPU workloads.
    /// - `best-effort` (default): place what fits
    /// - `gang`: all-or-nothing for distributed jobs
    /// - `spread`: distribute across nodes
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scheduling: Option<SchedulingPolicy>,
    /// Distributed GPU job coordination.
    /// When set, injects `MASTER_ADDR`, `WORLD_SIZE`, `RANK`, `LOCAL_RANK` env vars.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub distributed: Option<DistributedConfig>,
    /// GPU sharing mode: exclusive (default), mps, or time-slice.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sharing: Option<GpuSharingMode>,
}

fn default_gpu_count() -> u32 {
    1
}

fn default_gpu_vendor() -> String {
    "nvidia".to_string()
}

/// Per-service network configuration (overlay + join policy).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
#[derive(Default)]
pub struct ServiceNetworkSpec {
    /// Overlay network configuration
    #[serde(default)]
    pub overlays: OverlayConfig,

    /// Join policy (who can join this service)
    #[serde(default)]
    pub join: JoinPolicy,
}

/// Overlay network configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct OverlayConfig {
    /// Service-scoped overlay (service replicas only)
    #[serde(default)]
    pub service: OverlaySettings,

    /// Global overlay (all services in deployment)
    #[serde(default)]
    pub global: OverlaySettings,
}

impl Default for OverlayConfig {
    fn default() -> Self {
        Self {
            service: OverlaySettings {
                enabled: true,
                encrypted: true,
                isolated: true,
            },
            global: OverlaySettings {
                enabled: true,
                encrypted: true,
                isolated: false,
            },
        }
    }
}

/// Overlay network settings
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(deny_unknown_fields)]
pub struct OverlaySettings {
    /// Enable this overlay
    #[serde(default = "default_enabled")]
    pub enabled: bool,

    /// Use encryption
    #[serde(default = "default_encrypted")]
    pub encrypted: bool,

    /// Isolate from other services/groups
    #[serde(default)]
    pub isolated: bool,
}

fn default_enabled() -> bool {
    true
}

fn default_encrypted() -> bool {
    true
}

/// Join policy - controls who can join a service
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct JoinPolicy {
    /// Join mode
    #[serde(default = "default_join_mode")]
    pub mode: JoinMode,

    /// Scope of join
    #[serde(default = "default_join_scope")]
    pub scope: JoinScope,
}

impl Default for JoinPolicy {
    fn default() -> Self {
        Self {
            mode: default_join_mode(),
            scope: default_join_scope(),
        }
    }
}

fn default_join_mode() -> JoinMode {
    JoinMode::Token
}

fn default_join_scope() -> JoinScope {
    JoinScope::Service
}

/// Join mode
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum JoinMode {
    /// Any trusted node in deployment can self-enroll
    Open,
    /// Requires a join key (recommended)
    Token,
    /// Only control-plane/scheduler can place replicas
    Closed,
}

/// Join scope
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum JoinScope {
    /// Join this specific service
    Service,
    /// Join all services in deployment
    Global,
}

/// Endpoint specification (proxy binding)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
pub struct EndpointSpec {
    /// Endpoint name (for routing)
    #[validate(length(min = 1, message = "endpoint name cannot be empty"))]
    pub name: String,

    /// Protocol
    pub protocol: Protocol,

    /// Proxy listen port (external-facing port)
    #[validate(custom(function = "crate::spec::validate::validate_port_wrapper"))]
    pub port: u16,

    /// Container port the service actually listens on.
    /// Defaults to `port` when not specified.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_port: Option<u16>,

    /// URL path prefix (for http/https/websocket)
    pub path: Option<String>,

    /// Host pattern for routing (e.g. "api.example.com" or "*.example.com").
    /// `None` means match any host.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub host: Option<String>,

    /// Exposure type
    #[serde(default = "default_expose")]
    pub expose: ExposeType,

    /// Optional stream (L4) proxy configuration
    /// Only applicable when protocol is tcp or udp
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stream: Option<StreamEndpointConfig>,

    /// Optional tunnel configuration for this endpoint
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tunnel: Option<EndpointTunnelConfig>,
}

impl EndpointSpec {
    /// Returns the port the container actually listens on.
    /// Falls back to `port` when `target_port` is not specified.
    #[must_use]
    pub fn target_port(&self) -> u16 {
        self.target_port.unwrap_or(self.port)
    }
}

/// Tunnel configuration for an endpoint
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(deny_unknown_fields)]
pub struct EndpointTunnelConfig {
    /// Enable tunneling for this endpoint
    #[serde(default)]
    pub enabled: bool,

    /// Source node name (defaults to service's node)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,

    /// Destination node name (defaults to cluster ingress)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub to: Option<String>,

    /// Remote port to expose (0 = auto-assign)
    #[serde(default)]
    pub remote_port: u16,

    /// Override exposure for tunnel (public/internal)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expose: Option<ExposeType>,

    /// On-demand access configuration
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub access: Option<TunnelAccessConfig>,
}

/// On-demand access settings for `zlayer tunnel access`
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(deny_unknown_fields)]
pub struct TunnelAccessConfig {
    /// Allow on-demand access via CLI
    #[serde(default)]
    pub enabled: bool,

    /// Maximum session duration (e.g., "4h", "30m")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_ttl: Option<String>,

    /// Log all access sessions
    #[serde(default)]
    pub audit: bool,
}

fn default_expose() -> ExposeType {
    ExposeType::Internal
}

/// Protocol type
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Protocol {
    Http,
    Https,
    Tcp,
    Udp,
    Websocket,
}

/// Exposure type
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum ExposeType {
    Public,
    #[default]
    Internal,
}

/// Stream (L4) proxy configuration for TCP/UDP endpoints
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(deny_unknown_fields)]
pub struct StreamEndpointConfig {
    /// Enable TLS termination for TCP (auto-provision cert)
    #[serde(default)]
    pub tls: bool,

    /// Enable PROXY protocol for passing client IP
    #[serde(default)]
    pub proxy_protocol: bool,

    /// Custom session timeout for UDP (default: 60s)
    /// Format: duration string like "60s", "5m"
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_timeout: Option<String>,

    /// Health check configuration for L4
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub health_check: Option<StreamHealthCheck>,
}

/// Health check types for stream (L4) endpoints
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum StreamHealthCheck {
    /// TCP connect check - verifies port is accepting connections
    TcpConnect,
    /// UDP probe - sends request and optionally validates response
    UdpProbe {
        /// Request payload to send (can use hex escapes like \\xFF)
        request: String,
        /// Expected response pattern (optional regex)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        expect: Option<String>,
    },
}

/// Scaling configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "mode", rename_all = "lowercase", deny_unknown_fields)]
pub enum ScaleSpec {
    /// Adaptive scaling with metrics
    #[serde(rename = "adaptive")]
    Adaptive {
        /// Minimum replicas
        min: u32,

        /// Maximum replicas
        max: u32,

        /// Cooldown period between scale events
        #[serde(default, with = "duration::option")]
        cooldown: Option<std::time::Duration>,

        /// Target metrics for scaling
        #[serde(default)]
        targets: ScaleTargets,
    },

    /// Fixed number of replicas
    #[serde(rename = "fixed")]
    Fixed { replicas: u32 },

    /// Manual scaling (no automatic scaling)
    #[serde(rename = "manual")]
    Manual,
}

impl Default for ScaleSpec {
    fn default() -> Self {
        Self::Adaptive {
            min: 1,
            max: 10,
            cooldown: Some(std::time::Duration::from_secs(30)),
            targets: ScaleTargets::default(),
        }
    }
}

/// Target metrics for adaptive scaling
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
#[derive(Default)]
pub struct ScaleTargets {
    /// CPU percentage threshold (0-100)
    #[serde(default)]
    pub cpu: Option<u8>,

    /// Memory percentage threshold (0-100)
    #[serde(default)]
    pub memory: Option<u8>,

    /// Requests per second threshold
    #[serde(default)]
    pub rps: Option<u32>,
}

/// Dependency specification
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct DependsSpec {
    /// Service name to depend on
    pub service: String,

    /// Condition for dependency
    #[serde(default = "default_condition")]
    pub condition: DependencyCondition,

    /// Maximum time to wait
    #[serde(default = "default_timeout", with = "duration::option")]
    pub timeout: Option<std::time::Duration>,

    /// Action on timeout
    #[serde(default = "default_on_timeout")]
    pub on_timeout: TimeoutAction,
}

fn default_condition() -> DependencyCondition {
    DependencyCondition::Healthy
}

#[allow(clippy::unnecessary_wraps)]
fn default_timeout() -> Option<std::time::Duration> {
    Some(std::time::Duration::from_secs(300))
}

fn default_on_timeout() -> TimeoutAction {
    TimeoutAction::Fail
}

/// Dependency condition
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum DependencyCondition {
    /// Container process exists
    Started,
    /// Health check passes
    Healthy,
    /// Service is available for routing
    Ready,
}

/// Timeout action
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum TimeoutAction {
    Fail,
    Warn,
    Continue,
}

/// Health check specification
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct HealthSpec {
    /// Grace period before first check
    #[serde(default, with = "duration::option")]
    pub start_grace: Option<std::time::Duration>,

    /// Interval between checks
    #[serde(default, with = "duration::option")]
    pub interval: Option<std::time::Duration>,

    /// Timeout per check
    #[serde(default, with = "duration::option")]
    pub timeout: Option<std::time::Duration>,

    /// Number of retries before marking unhealthy
    #[serde(default = "default_retries")]
    pub retries: u32,

    /// Health check type and parameters
    pub check: HealthCheck,
}

fn default_retries() -> u32 {
    3
}

/// Health check type
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum HealthCheck {
    /// TCP port check
    Tcp {
        /// Port to check (0 = use first endpoint)
        port: u16,
    },

    /// HTTP check
    Http {
        /// URL to check
        url: String,
        /// Expected status code
        #[serde(default = "default_expect_status")]
        expect_status: u16,
    },

    /// Command check
    Command {
        /// Command to run
        command: String,
    },
}

fn default_expect_status() -> u16 {
    200
}

/// Init actions specification
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
#[derive(Default)]
pub struct InitSpec {
    /// Init steps to run before container starts
    #[serde(default)]
    pub steps: Vec<InitStep>,
}

/// Lifecycle policy for service / job / cron containers.
///
/// Currently exposes a single `delete_on_exit` knob that, when `true`,
/// instructs higher layers to remove the container record (and its bundle)
/// once it has terminated. Other layers consume this field; this type is
/// purely descriptive.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
#[serde(deny_unknown_fields)]
pub struct LifecycleSpec {
    /// When true, terminated containers (and their bundles) are removed
    /// automatically rather than retained for inspection. Defaults to
    /// `false`, preserving the historical retain-on-exit behavior.
    #[serde(default)]
    pub delete_on_exit: bool,
}

/// Init action step
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct InitStep {
    /// Step identifier
    pub id: String,

    /// Action to perform (e.g., "`init.wait_tcp`")
    pub uses: String,

    /// Parameters for the action
    #[serde(default)]
    pub with: InitParams,

    /// Number of retries
    #[serde(default)]
    pub retry: Option<u32>,

    /// Maximum time for this step
    #[serde(default, with = "duration::option")]
    pub timeout: Option<std::time::Duration>,

    /// Action on failure
    #[serde(default = "default_on_failure")]
    pub on_failure: FailureAction,
}

fn default_on_failure() -> FailureAction {
    FailureAction::Fail
}

/// Init action parameters
pub type InitParams = std::collections::HashMap<String, serde_json::Value>;

/// Failure action for init steps
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum FailureAction {
    Fail,
    Warn,
    Continue,
}

/// Error handling policies
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
#[derive(Default)]
pub struct ErrorsSpec {
    /// Init failure policy
    #[serde(default)]
    pub on_init_failure: InitFailurePolicy,

    /// Panic/restart policy
    #[serde(default)]
    pub on_panic: PanicPolicy,
}

/// Init failure policy
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct InitFailurePolicy {
    #[serde(default = "default_init_action")]
    pub action: InitFailureAction,
}

impl Default for InitFailurePolicy {
    fn default() -> Self {
        Self {
            action: default_init_action(),
        }
    }
}

fn default_init_action() -> InitFailureAction {
    InitFailureAction::Fail
}

/// Init failure action
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum InitFailureAction {
    Fail,
    Restart,
    Backoff,
}

/// Panic policy
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct PanicPolicy {
    #[serde(default = "default_panic_action")]
    pub action: PanicAction,
}

impl Default for PanicPolicy {
    fn default() -> Self {
        Self {
            action: default_panic_action(),
        }
    }
}

fn default_panic_action() -> PanicAction {
    PanicAction::Restart
}

/// Panic action
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum PanicAction {
    Restart,
    Shutdown,
    Isolate,
}

// ==========================================================================
// Network / Access Control types
// ==========================================================================

/// A network policy defines an access control group with membership rules
/// and service access policies.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct NetworkPolicySpec {
    /// Unique network name.
    pub name: String,

    /// Human-readable description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// CIDR ranges that belong to this network (e.g., "10.200.0.0/16", "192.168.1.0/24").
    #[serde(default)]
    pub cidrs: Vec<String>,

    /// Named members (users, groups, nodes) of this network.
    #[serde(default)]
    pub members: Vec<NetworkMember>,

    /// Access rules defining which services this network can reach.
    #[serde(default)]
    pub access_rules: Vec<AccessRule>,
}

/// A member of a network.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct NetworkMember {
    /// Member identifier (username, group name, node ID, or CIDR).
    pub name: String,
    /// Type of member.
    #[serde(default)]
    pub kind: MemberKind,
}

/// Type of network member.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum MemberKind {
    /// An individual user identity.
    #[default]
    User,
    /// A group of users.
    Group,
    /// A specific cluster node.
    Node,
    /// A CIDR range (redundant with NetworkPolicySpec.cidrs but allows per-member CIDR).
    Cidr,
}

/// An access rule determining what a network can reach.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AccessRule {
    /// Target service name, or "*" for all services.
    #[serde(default = "wildcard")]
    pub service: String,

    /// Target deployment name, or "*" for all deployments.
    #[serde(default = "wildcard")]
    pub deployment: String,

    /// Specific ports allowed. None means all ports.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ports: Option<Vec<u16>>,

    /// Whether to allow or deny access.
    #[serde(default)]
    pub action: AccessAction,
}

fn wildcard() -> String {
    "*".to_string()
}

/// Access control action.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum AccessAction {
    /// Allow access (default).
    #[default]
    Allow,
    /// Deny access.
    Deny,
}

// ==========================================================================
// Container bridge / overlay network types (Docker-compatible)
// ==========================================================================
//
// These types model user-defined bridge or overlay networks that standalone
// containers can attach to — the Docker-style "docker network create" model.
// They are intentionally named `BridgeNetwork*` to avoid colliding with the
// CIDR-ACL `NetworkPolicySpec` types above, which model a completely
// different concept (access-control groups).

/// A user-defined bridge or overlay network that containers can attach to.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
pub struct BridgeNetwork {
    /// Opaque server-generated identifier (UUID v4).
    pub id: String,

    /// Human-readable, unique name (must match `^[a-z0-9][a-z0-9_-]{0,63}$`).
    pub name: String,

    /// Driver backing the network (bridge vs. overlay).
    #[serde(default)]
    pub driver: BridgeNetworkDriver,

    /// IPv4/IPv6 subnet in CIDR notation (e.g. `"10.240.0.0/24"`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subnet: Option<String>,

    /// Arbitrary key/value labels for filtering and grouping.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub labels: HashMap<String, String>,

    /// If true, containers attached to this network cannot reach the outside
    /// world — only other containers on the same network.
    #[serde(default)]
    pub internal: bool,

    /// Creation timestamp (UTC, RFC 3339).
    #[schema(value_type = String, format = "date-time")]
    pub created_at: chrono::DateTime<chrono::Utc>,
}

/// Backing driver for a [`BridgeNetwork`].
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default, utoipa::ToSchema)]
#[serde(rename_all = "lowercase")]
pub enum BridgeNetworkDriver {
    /// Linux bridge on the local host (single-host, default).
    #[default]
    Bridge,
    /// Overlay network spanning multiple hosts.
    Overlay,
}

/// A container attached to a [`BridgeNetwork`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
pub struct BridgeNetworkAttachment {
    /// Runtime-provided container id.
    pub container_id: String,

    /// Container name, if known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub container_name: Option<String>,

    /// DNS aliases the container can be reached by on this network.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub aliases: Vec<String>,

    /// Assigned IPv4 address on the network (if any).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ipv4: Option<String>,
}

// ==========================================================================
// Registry auth (inline, not persisted) — §3.10 of ZLAYER_SDK_FIXES.md
// ==========================================================================
//
// Inline credentials a client can attach to a single pull or container-create
// request without first POSTing them to `/api/v1/credentials/registry`. The
// daemon uses them exactly once — they are never logged, never persisted, and
// never echoed back on a response.
//
// For requests that instead want to reuse an already-stored credential, the
// `CreateContainerRequest` / `PullImageRequest` DTOs also accept a
// `registry_credential_id` pointing at the `RegistryCredentialStore`. Inline
// `RegistryAuth` takes precedence when both are provided.

/// Inline Docker/OCI registry credentials attached to a single pull request.
///
/// Prefer persistent credentials via `/api/v1/credentials/registry` for
/// long-lived services. Use this inline form for one-off pulls (e.g. CI
/// runners fetching a private image for a single job) where persisting a
/// credential is undesirable.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
pub struct RegistryAuth {
    /// Username for the registry (for basic auth) or a placeholder
    /// identifier when `auth_type == Token`.
    pub username: String,
    /// Password or bearer token. **Never** logged or returned on any
    /// response — consumed once and dropped.
    pub password: String,
    /// Which authentication scheme to use against the registry.
    #[serde(default = "default_registry_auth_type")]
    pub auth_type: RegistryAuthType,
}

/// Authentication scheme for a [`RegistryAuth`].
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum RegistryAuthType {
    /// HTTP Basic authentication (username + password). Default.
    #[default]
    Basic,
    /// Bearer token authentication. `password` carries the token; `username`
    /// is typically a placeholder such as `"oauth2accesstoken"` or `"<token>"`.
    Token,
}

/// Serde default for [`RegistryAuth::auth_type`]. Kept as a free function so
/// `#[serde(default = "...")]` can reference it.
#[must_use]
pub fn default_registry_auth_type() -> RegistryAuthType {
    RegistryAuthType::Basic
}

// ==========================================================================
// Container restart policy (Docker-style) — §3.4 of ZLAYER_SDK_FIXES.md
// ==========================================================================
//
// Named `ContainerRestartPolicy` / `ContainerRestartKind` rather than
// `RestartPolicy` / `RestartKind` to avoid colliding with ZLayer's existing
// `PanicPolicy`/`PanicAction` types and to make the runtime-level (as opposed
// to panic-driven) nature of this policy explicit.

/// Container-runtime-level restart policy.
///
/// Maps onto Docker's `HostConfig.RestartPolicy`. Distinct from
/// [`PanicPolicy`], which governs what `ZLayer` does in response to an
/// application panic (it does not set a Docker restart policy).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub struct ContainerRestartPolicy {
    /// Which restart policy to apply.
    pub kind: ContainerRestartKind,

    /// For `on_failure` only: maximum number of restart attempts before
    /// giving up. Ignored by other kinds. `None` means "retry forever".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_attempts: Option<u32>,

    /// Humantime-formatted delay between restarts (e.g. `"500ms"`,
    /// `"2s"`). Accepted for forward-compatibility but currently ignored
    /// by the Docker backend: bollard's `RestartPolicy` has no per-kind
    /// delay field. When set, the runtime emits a warning.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delay: Option<String>,
}

/// Which flavor of container restart policy to apply.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ContainerRestartKind {
    /// Never restart (Docker's `"no"`).
    No,
    /// Always restart (Docker's `"always"`).
    Always,
    /// Restart unless the user explicitly stopped the container
    /// (Docker's `"unless-stopped"`).
    UnlessStopped,
    /// Restart only when the container exits with a non-zero code
    /// (Docker's `"on-failure"`). Respects `max_attempts`.
    OnFailure,
}

// ==========================================================================
// Port mappings (Docker-style container port publishing)
// ==========================================================================

/// Transport protocol for a published container port.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum PortProtocol {
    /// TCP (default).
    Tcp,
    /// UDP.
    Udp,
}

impl Default for PortProtocol {
    fn default() -> Self {
        default_port_protocol()
    }
}

impl PortProtocol {
    /// Return the lowercase string form Docker uses in port-binding keys
    /// (e.g. `"tcp"` or `"udp"`).
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            PortProtocol::Tcp => "tcp",
            PortProtocol::Udp => "udp",
        }
    }
}

fn default_port_protocol() -> PortProtocol {
    PortProtocol::Tcp
}

fn default_host_ip() -> String {
    "0.0.0.0".to_string()
}

/// A single host-to-container port publish rule (Docker's `-p`).
///
/// When `host_port` is `None` (or explicitly `Some(0)`), the container runtime
/// assigns an ephemeral host port. `host_ip` defaults to `"0.0.0.0"` to bind
/// on all interfaces.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct PortMapping {
    /// Host port. `None` (or zero) means "assign an ephemeral port".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub host_port: Option<u16>,
    /// Container-side port.
    pub container_port: u16,
    /// Transport protocol (defaults to TCP).
    #[serde(default = "default_port_protocol")]
    pub protocol: PortProtocol,
    /// Host interface to bind on. Defaults to `"0.0.0.0"` (all interfaces).
    #[serde(default = "default_host_ip", skip_serializing_if = "String::is_empty")]
    pub host_ip: String,
}

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

    #[test]
    fn port_mapping_defaults_via_serde() {
        // Minimal JSON: only container_port. host_port omitted, protocol defaults
        // to "tcp", host_ip defaults to "0.0.0.0".
        let json = r#"{"container_port": 8080}"#;
        let m: PortMapping = serde_json::from_str(json).expect("parse minimal PortMapping");
        assert_eq!(m.container_port, 8080);
        assert_eq!(m.host_port, None);
        assert_eq!(m.protocol, PortProtocol::Tcp);
        assert_eq!(m.host_ip, "0.0.0.0");
    }

    #[test]
    fn port_mapping_skips_none_host_port_and_empty_host_ip() {
        let m = PortMapping {
            host_port: None,
            container_port: 443,
            protocol: PortProtocol::Tcp,
            host_ip: String::new(),
        };
        let s = serde_json::to_string(&m).expect("serialize");
        // host_port = None should be skipped, host_ip = "" should be skipped.
        assert!(!s.contains("host_port"), "host_port should be skipped: {s}");
        assert!(!s.contains("host_ip"), "host_ip should be skipped: {s}");
        assert!(s.contains("\"container_port\":443"));
        assert!(s.contains("\"protocol\":\"tcp\""));
    }

    #[test]
    fn test_parse_simple_spec() {
        let yaml = r"
version: v1
deployment: test
services:
  hello:
    rtype: service
    image:
      name: hello-world:latest
    endpoints:
      - name: http
        protocol: http
        port: 8080
        expose: public
";

        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.version, "v1");
        assert_eq!(spec.deployment, "test");
        assert!(spec.services.contains_key("hello"));
    }

    #[test]
    fn test_parse_duration() {
        let yaml = r"
version: v1
deployment: test
services:
  test:
    rtype: service
    image:
      name: test:latest
    health:
      timeout: 30s
      interval: 1m
      start_grace: 5s
      check:
        type: tcp
        port: 8080
";

        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let health = &spec.services["test"].health;
        assert_eq!(health.timeout, Some(std::time::Duration::from_secs(30)));
        assert_eq!(health.interval, Some(std::time::Duration::from_secs(60)));
        assert_eq!(health.start_grace, Some(std::time::Duration::from_secs(5)));
        match &health.check {
            HealthCheck::Tcp { port } => assert_eq!(*port, 8080),
            _ => panic!("Expected TCP health check"),
        }
    }

    #[test]
    fn test_parse_adaptive_scale() {
        let yaml = r"
version: v1
deployment: test
services:
  test:
    rtype: service
    image:
      name: test:latest
    scale:
      mode: adaptive
      min: 2
      max: 10
      cooldown: 15s
      targets:
        cpu: 70
        rps: 800
";

        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let scale = &spec.services["test"].scale;
        match scale {
            ScaleSpec::Adaptive {
                min,
                max,
                cooldown,
                targets,
            } => {
                assert_eq!(*min, 2);
                assert_eq!(*max, 10);
                assert_eq!(*cooldown, Some(std::time::Duration::from_secs(15)));
                assert_eq!(targets.cpu, Some(70));
                assert_eq!(targets.rps, Some(800));
            }
            _ => panic!("Expected Adaptive scale mode"),
        }
    }

    #[test]
    fn test_node_mode_default() {
        let yaml = r"
version: v1
deployment: test
services:
  hello:
    rtype: service
    image:
      name: hello-world:latest
";

        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.services["hello"].node_mode, NodeMode::Shared);
        assert!(spec.services["hello"].node_selector.is_none());
    }

    #[test]
    fn test_node_mode_dedicated() {
        let yaml = r"
version: v1
deployment: test
services:
  api:
    rtype: service
    image:
      name: api:latest
    node_mode: dedicated
";

        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.services["api"].node_mode, NodeMode::Dedicated);
    }

    #[test]
    fn test_node_mode_exclusive() {
        let yaml = r"
version: v1
deployment: test
services:
  database:
    rtype: service
    image:
      name: postgres:15
    node_mode: exclusive
";

        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.services["database"].node_mode, NodeMode::Exclusive);
    }

    #[test]
    fn test_node_selector_with_labels() {
        let yaml = r#"
version: v1
deployment: test
services:
  ml-worker:
    rtype: service
    image:
      name: ml-worker:latest
    node_mode: dedicated
    node_selector:
      labels:
        gpu: "true"
        zone: us-east
      prefer_labels:
        storage: ssd
"#;

        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let service = &spec.services["ml-worker"];
        assert_eq!(service.node_mode, NodeMode::Dedicated);

        let selector = service.node_selector.as_ref().unwrap();
        assert_eq!(selector.labels.get("gpu"), Some(&"true".to_string()));
        assert_eq!(selector.labels.get("zone"), Some(&"us-east".to_string()));
        assert_eq!(
            selector.prefer_labels.get("storage"),
            Some(&"ssd".to_string())
        );
    }

    #[test]
    fn test_node_mode_serialization_roundtrip() {
        use serde_json;

        // Test all variants serialize/deserialize correctly
        let modes = [NodeMode::Shared, NodeMode::Dedicated, NodeMode::Exclusive];
        let expected_json = ["\"shared\"", "\"dedicated\"", "\"exclusive\""];

        for (mode, expected) in modes.iter().zip(expected_json.iter()) {
            let json = serde_json::to_string(mode).unwrap();
            assert_eq!(&json, *expected, "Serialization failed for {mode:?}");

            let deserialized: NodeMode = serde_json::from_str(&json).unwrap();
            assert_eq!(deserialized, *mode, "Roundtrip failed for {mode:?}");
        }
    }

    #[test]
    fn test_node_selector_empty() {
        let yaml = r"
version: v1
deployment: test
services:
  api:
    rtype: service
    image:
      name: api:latest
    node_selector:
      labels: {}
";

        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let selector = spec.services["api"].node_selector.as_ref().unwrap();
        assert!(selector.labels.is_empty());
        assert!(selector.prefer_labels.is_empty());
    }

    #[test]
    fn test_mixed_node_modes_in_deployment() {
        let yaml = r"
version: v1
deployment: test
services:
  redis:
    rtype: service
    image:
      name: redis:alpine
    # Default shared mode
  api:
    rtype: service
    image:
      name: api:latest
    node_mode: dedicated
  database:
    rtype: service
    image:
      name: postgres:15
    node_mode: exclusive
    node_selector:
      labels:
        storage: ssd
";

        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.services["redis"].node_mode, NodeMode::Shared);
        assert_eq!(spec.services["api"].node_mode, NodeMode::Dedicated);
        assert_eq!(spec.services["database"].node_mode, NodeMode::Exclusive);

        let db_selector = spec.services["database"].node_selector.as_ref().unwrap();
        assert_eq!(db_selector.labels.get("storage"), Some(&"ssd".to_string()));
    }

    #[test]
    fn test_storage_bind_mount() {
        let yaml = r"
version: v1
deployment: test
services:
  app:
    image:
      name: app:latest
    storage:
      - type: bind
        source: /host/data
        target: /app/data
        readonly: true
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let storage = &spec.services["app"].storage;
        assert_eq!(storage.len(), 1);
        match &storage[0] {
            StorageSpec::Bind {
                source,
                target,
                readonly,
            } => {
                assert_eq!(source, "/host/data");
                assert_eq!(target, "/app/data");
                assert!(*readonly);
            }
            _ => panic!("Expected Bind storage"),
        }
    }

    #[test]
    fn test_storage_named_with_tier() {
        let yaml = r"
version: v1
deployment: test
services:
  app:
    image:
      name: app:latest
    storage:
      - type: named
        name: my-data
        target: /app/data
        tier: cached
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let storage = &spec.services["app"].storage;
        match &storage[0] {
            StorageSpec::Named {
                name, target, tier, ..
            } => {
                assert_eq!(name, "my-data");
                assert_eq!(target, "/app/data");
                assert_eq!(*tier, StorageTier::Cached);
            }
            _ => panic!("Expected Named storage"),
        }
    }

    #[test]
    fn test_storage_anonymous() {
        let yaml = r"
version: v1
deployment: test
services:
  app:
    image:
      name: app:latest
    storage:
      - type: anonymous
        target: /app/cache
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let storage = &spec.services["app"].storage;
        match &storage[0] {
            StorageSpec::Anonymous { target, tier } => {
                assert_eq!(target, "/app/cache");
                assert_eq!(*tier, StorageTier::Local); // default
            }
            _ => panic!("Expected Anonymous storage"),
        }
    }

    #[test]
    fn test_storage_tmpfs() {
        let yaml = r"
version: v1
deployment: test
services:
  app:
    image:
      name: app:latest
    storage:
      - type: tmpfs
        target: /app/tmp
        size: 256Mi
        mode: 1777
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let storage = &spec.services["app"].storage;
        match &storage[0] {
            StorageSpec::Tmpfs { target, size, mode } => {
                assert_eq!(target, "/app/tmp");
                assert_eq!(size.as_deref(), Some("256Mi"));
                assert_eq!(*mode, Some(1777));
            }
            _ => panic!("Expected Tmpfs storage"),
        }
    }

    #[test]
    fn test_storage_s3() {
        let yaml = r"
version: v1
deployment: test
services:
  app:
    image:
      name: app:latest
    storage:
      - type: s3
        bucket: my-bucket
        prefix: models/
        target: /app/models
        readonly: true
        endpoint: https://s3.us-west-2.amazonaws.com
        credentials: aws-creds
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let storage = &spec.services["app"].storage;
        match &storage[0] {
            StorageSpec::S3 {
                bucket,
                prefix,
                target,
                readonly,
                endpoint,
                credentials,
            } => {
                assert_eq!(bucket, "my-bucket");
                assert_eq!(prefix.as_deref(), Some("models/"));
                assert_eq!(target, "/app/models");
                assert!(*readonly);
                assert_eq!(
                    endpoint.as_deref(),
                    Some("https://s3.us-west-2.amazonaws.com")
                );
                assert_eq!(credentials.as_deref(), Some("aws-creds"));
            }
            _ => panic!("Expected S3 storage"),
        }
    }

    #[test]
    fn test_storage_multiple_types() {
        let yaml = r"
version: v1
deployment: test
services:
  app:
    image:
      name: app:latest
    storage:
      - type: bind
        source: /etc/config
        target: /app/config
        readonly: true
      - type: named
        name: app-data
        target: /app/data
      - type: tmpfs
        target: /app/tmp
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let storage = &spec.services["app"].storage;
        assert_eq!(storage.len(), 3);
        assert!(matches!(&storage[0], StorageSpec::Bind { .. }));
        assert!(matches!(&storage[1], StorageSpec::Named { .. }));
        assert!(matches!(&storage[2], StorageSpec::Tmpfs { .. }));
    }

    #[test]
    fn test_storage_tier_default() {
        let yaml = r"
version: v1
deployment: test
services:
  app:
    image:
      name: app:latest
    storage:
      - type: named
        name: data
        target: /data
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        match &spec.services["app"].storage[0] {
            StorageSpec::Named { tier, .. } => {
                assert_eq!(*tier, StorageTier::Local); // default should be Local
            }
            _ => panic!("Expected Named storage"),
        }
    }

    // ==========================================================================
    // Tunnel configuration tests
    // ==========================================================================

    #[test]
    fn test_endpoint_tunnel_config_basic() {
        let yaml = r"
version: v1
deployment: test
services:
  api:
    image:
      name: api:latest
    endpoints:
      - name: http
        protocol: http
        port: 8080
        tunnel:
          enabled: true
          remote_port: 8080
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let endpoint = &spec.services["api"].endpoints[0];
        let tunnel = endpoint.tunnel.as_ref().unwrap();
        assert!(tunnel.enabled);
        assert_eq!(tunnel.remote_port, 8080);
        assert!(tunnel.from.is_none());
        assert!(tunnel.to.is_none());
    }

    #[test]
    fn test_endpoint_tunnel_config_full() {
        let yaml = r"
version: v1
deployment: test
services:
  api:
    image:
      name: api:latest
    endpoints:
      - name: http
        protocol: http
        port: 8080
        tunnel:
          enabled: true
          from: node-1
          to: ingress-node
          remote_port: 9000
          expose: public
          access:
            enabled: true
            max_ttl: 4h
            audit: true
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let endpoint = &spec.services["api"].endpoints[0];
        let tunnel = endpoint.tunnel.as_ref().unwrap();
        assert!(tunnel.enabled);
        assert_eq!(tunnel.from, Some("node-1".to_string()));
        assert_eq!(tunnel.to, Some("ingress-node".to_string()));
        assert_eq!(tunnel.remote_port, 9000);
        assert_eq!(tunnel.expose, Some(ExposeType::Public));

        let access = tunnel.access.as_ref().unwrap();
        assert!(access.enabled);
        assert_eq!(access.max_ttl, Some("4h".to_string()));
        assert!(access.audit);
    }

    #[test]
    fn test_top_level_tunnel_definition() {
        let yaml = r"
version: v1
deployment: test
services: {}
tunnels:
  db-tunnel:
    from: app-node
    to: db-node
    local_port: 5432
    remote_port: 5432
    protocol: tcp
    expose: internal
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let tunnel = spec.tunnels.get("db-tunnel").unwrap();
        assert_eq!(tunnel.from, "app-node");
        assert_eq!(tunnel.to, "db-node");
        assert_eq!(tunnel.local_port, 5432);
        assert_eq!(tunnel.remote_port, 5432);
        assert_eq!(tunnel.protocol, TunnelProtocol::Tcp);
        assert_eq!(tunnel.expose, ExposeType::Internal);
    }

    #[test]
    fn test_top_level_tunnel_defaults() {
        let yaml = r"
version: v1
deployment: test
services: {}
tunnels:
  simple-tunnel:
    from: node-a
    to: node-b
    local_port: 3000
    remote_port: 3000
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let tunnel = spec.tunnels.get("simple-tunnel").unwrap();
        assert_eq!(tunnel.protocol, TunnelProtocol::Tcp); // default
        assert_eq!(tunnel.expose, ExposeType::Internal); // default
    }

    #[test]
    fn test_tunnel_protocol_udp() {
        let yaml = r"
version: v1
deployment: test
services: {}
tunnels:
  udp-tunnel:
    from: node-a
    to: node-b
    local_port: 5353
    remote_port: 5353
    protocol: udp
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let tunnel = spec.tunnels.get("udp-tunnel").unwrap();
        assert_eq!(tunnel.protocol, TunnelProtocol::Udp);
    }

    #[test]
    fn test_endpoint_without_tunnel() {
        let yaml = r"
version: v1
deployment: test
services:
  api:
    image:
      name: api:latest
    endpoints:
      - name: http
        protocol: http
        port: 8080
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        let endpoint = &spec.services["api"].endpoints[0];
        assert!(endpoint.tunnel.is_none());
    }

    #[test]
    fn test_deployment_without_tunnels() {
        let yaml = r"
version: v1
deployment: test
services:
  api:
    image:
      name: api:latest
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        assert!(spec.tunnels.is_empty());
    }

    // ==========================================================================
    // ApiSpec tests
    // ==========================================================================

    #[test]
    fn test_spec_without_api_block_uses_defaults() {
        let yaml = r"
version: v1
deployment: test
services:
  hello:
    image:
      name: hello-world:latest
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        assert!(spec.api.enabled);
        assert_eq!(spec.api.bind, "0.0.0.0:3669");
        assert!(spec.api.jwt_secret.is_none());
        assert!(spec.api.swagger);
    }

    #[test]
    fn test_spec_with_explicit_api_block() {
        let yaml = r#"
version: v1
deployment: test
services:
  hello:
    image:
      name: hello-world:latest
api:
  enabled: false
  bind: "127.0.0.1:9090"
  jwt_secret: "my-secret"
  swagger: false
"#;
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        assert!(!spec.api.enabled);
        assert_eq!(spec.api.bind, "127.0.0.1:9090");
        assert_eq!(spec.api.jwt_secret, Some("my-secret".to_string()));
        assert!(!spec.api.swagger);
    }

    #[test]
    fn test_spec_with_partial_api_block() {
        let yaml = r#"
version: v1
deployment: test
services:
  hello:
    image:
      name: hello-world:latest
api:
  bind: "0.0.0.0:3000"
"#;
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).unwrap();
        assert!(spec.api.enabled); // default true
        assert_eq!(spec.api.bind, "0.0.0.0:3000");
        assert!(spec.api.jwt_secret.is_none()); // default None
        assert!(spec.api.swagger); // default true
    }

    // ==========================================================================
    // NetworkPolicySpec tests
    // ==========================================================================

    #[test]
    fn test_network_policy_spec_roundtrip() {
        let spec = NetworkPolicySpec {
            name: "corp-vpn".to_string(),
            description: Some("Corporate VPN network".to_string()),
            cidrs: vec!["10.200.0.0/16".to_string()],
            members: vec![
                NetworkMember {
                    name: "alice".to_string(),
                    kind: MemberKind::User,
                },
                NetworkMember {
                    name: "ops-team".to_string(),
                    kind: MemberKind::Group,
                },
                NetworkMember {
                    name: "node-01".to_string(),
                    kind: MemberKind::Node,
                },
            ],
            access_rules: vec![
                AccessRule {
                    service: "api-gateway".to_string(),
                    deployment: "*".to_string(),
                    ports: Some(vec![443, 8080]),
                    action: AccessAction::Allow,
                },
                AccessRule {
                    service: "*".to_string(),
                    deployment: "staging".to_string(),
                    ports: None,
                    action: AccessAction::Deny,
                },
            ],
        };

        let yaml = serde_yaml::to_string(&spec).unwrap();
        let deserialized: NetworkPolicySpec = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(spec, deserialized);
    }

    #[test]
    fn test_network_policy_spec_defaults() {
        let yaml = r"
name: minimal
";
        let spec: NetworkPolicySpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.name, "minimal");
        assert!(spec.description.is_none());
        assert!(spec.cidrs.is_empty());
        assert!(spec.members.is_empty());
        assert!(spec.access_rules.is_empty());
    }

    #[test]
    fn test_access_rule_defaults() {
        let yaml = "{}";
        let rule: AccessRule = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(rule.service, "*");
        assert_eq!(rule.deployment, "*");
        assert!(rule.ports.is_none());
        assert_eq!(rule.action, AccessAction::Allow);
    }

    #[test]
    fn test_member_kind_defaults_to_user() {
        let yaml = r"
name: bob
";
        let member: NetworkMember = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(member.name, "bob");
        assert_eq!(member.kind, MemberKind::User);
    }

    #[test]
    fn test_member_kind_variants() {
        for (input, expected) in [
            ("user", MemberKind::User),
            ("group", MemberKind::Group),
            ("node", MemberKind::Node),
            ("cidr", MemberKind::Cidr),
        ] {
            let yaml = format!("name: test\nkind: {input}");
            let member: NetworkMember = serde_yaml::from_str(&yaml).unwrap();
            assert_eq!(member.kind, expected);
        }
    }

    #[test]
    fn test_access_action_variants() {
        // Test via a wrapper struct since bare enums need a YAML tag
        #[derive(Debug, Deserialize)]
        struct Wrapper {
            action: AccessAction,
        }

        let allow: Wrapper = serde_yaml::from_str("action: allow").unwrap();
        let deny: Wrapper = serde_yaml::from_str("action: deny").unwrap();

        assert_eq!(allow.action, AccessAction::Allow);
        assert_eq!(deny.action, AccessAction::Deny);
    }

    #[test]
    fn test_network_policy_spec_default_impl() {
        let spec = NetworkPolicySpec::default();
        assert_eq!(spec.name, "");
        assert!(spec.description.is_none());
        assert!(spec.cidrs.is_empty());
        assert!(spec.members.is_empty());
        assert!(spec.access_rules.is_empty());
    }

    #[test]
    fn container_restart_policy_serde_roundtrip_all_kinds() {
        // Exercise every `ContainerRestartKind` variant via a JSON roundtrip.
        // Covers the `snake_case` rename (`unless_stopped`, `on_failure`) and
        // the optional `max_attempts` / `delay` fields. Validates the wire
        // format the API will expose under `/v1/containers`.
        let cases = [
            (
                ContainerRestartPolicy {
                    kind: ContainerRestartKind::No,
                    max_attempts: None,
                    delay: None,
                },
                r#"{"kind":"no"}"#,
            ),
            (
                ContainerRestartPolicy {
                    kind: ContainerRestartKind::Always,
                    max_attempts: None,
                    delay: Some("500ms".to_string()),
                },
                r#"{"kind":"always","delay":"500ms"}"#,
            ),
            (
                ContainerRestartPolicy {
                    kind: ContainerRestartKind::UnlessStopped,
                    max_attempts: None,
                    delay: None,
                },
                r#"{"kind":"unless_stopped"}"#,
            ),
            (
                ContainerRestartPolicy {
                    kind: ContainerRestartKind::OnFailure,
                    max_attempts: Some(5),
                    delay: None,
                },
                r#"{"kind":"on_failure","max_attempts":5}"#,
            ),
        ];

        for (value, expected_json) in &cases {
            let serialized = serde_json::to_string(value).expect("serialize");
            assert_eq!(&serialized, expected_json, "serialize mismatch");
            let round: ContainerRestartPolicy =
                serde_json::from_str(&serialized).expect("deserialize");
            assert_eq!(&round, value, "roundtrip mismatch");
        }
    }

    // -- §3.10: RegistryAuth ------------------------------------------------

    #[test]
    fn registry_auth_type_serializes_snake_case() {
        assert_eq!(
            serde_json::to_string(&RegistryAuthType::Basic).unwrap(),
            "\"basic\""
        );
        assert_eq!(
            serde_json::to_string(&RegistryAuthType::Token).unwrap(),
            "\"token\""
        );
    }

    #[test]
    fn registry_auth_default_auth_type_is_basic() {
        // When `auth_type` is omitted on the wire, the serde default kicks in.
        let json = r#"{"username":"u","password":"p"}"#;
        let parsed: RegistryAuth = serde_json::from_str(json).expect("parse");
        assert_eq!(parsed.auth_type, RegistryAuthType::Basic);
        assert_eq!(parsed.username, "u");
        assert_eq!(parsed.password, "p");
    }

    #[test]
    fn registry_auth_serde_roundtrip_both_variants() {
        for variant in [RegistryAuthType::Basic, RegistryAuthType::Token] {
            let cred = RegistryAuth {
                username: "ci-bot".to_string(),
                password: "s3cret".to_string(),
                auth_type: variant,
            };
            let serialized = serde_json::to_string(&cred).expect("serialize");
            let back: RegistryAuth = serde_json::from_str(&serialized).expect("deserialize");
            assert_eq!(back, cred, "roundtrip mismatch for {variant:?}");
        }
    }

    #[test]
    fn registry_auth_explicit_token_type_parses() {
        let json = r#"{"username":"oauth2accesstoken","password":"ghp_abc","auth_type":"token"}"#;
        let parsed: RegistryAuth = serde_json::from_str(json).expect("parse");
        assert_eq!(parsed.auth_type, RegistryAuthType::Token);
    }

    #[test]
    fn target_platform_as_oci_str() {
        assert_eq!(
            TargetPlatform::new(OsKind::Linux, ArchKind::Amd64).as_oci_str(),
            "linux/amd64"
        );
        assert_eq!(
            TargetPlatform::new(OsKind::Windows, ArchKind::Arm64).as_oci_str(),
            "windows/arm64"
        );
        assert_eq!(
            TargetPlatform::new(OsKind::Macos, ArchKind::Arm64).as_oci_str(),
            "darwin/arm64"
        );
    }

    #[test]
    fn os_kind_from_rust_consts() {
        assert_eq!(OsKind::from_rust_os("linux"), Some(OsKind::Linux));
        assert_eq!(OsKind::from_rust_os("windows"), Some(OsKind::Windows));
        assert_eq!(OsKind::from_rust_os("macos"), Some(OsKind::Macos));
        assert_eq!(OsKind::from_rust_os("freebsd"), None);
    }

    #[test]
    fn arch_kind_from_rust_consts() {
        assert_eq!(ArchKind::from_rust_arch("x86_64"), Some(ArchKind::Amd64));
        assert_eq!(ArchKind::from_rust_arch("aarch64"), Some(ArchKind::Arm64));
        assert_eq!(ArchKind::from_rust_arch("riscv64"), None);
    }

    #[test]
    fn service_spec_platform_yaml_round_trip_none() {
        // Omitting `platform` from YAML should deserialize as None without error,
        // even though ServiceSpec has `#[serde(deny_unknown_fields)]`.
        let yaml = r"
version: v1
deployment: test
services:
  app:
    rtype: service
    image:
      name: nginx:latest
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).expect("yaml parse");
        assert!(spec.services["app"].platform.is_none());
    }

    #[test]
    fn service_spec_platform_yaml_round_trip_some() {
        let yaml = r"
version: v1
deployment: test
services:
  app:
    rtype: service
    image:
      name: nginx:latest
    platform:
      os: windows
      arch: amd64
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).expect("yaml parse");
        assert_eq!(
            spec.services["app"].platform,
            Some(TargetPlatform::new(OsKind::Windows, ArchKind::Amd64))
        );
    }

    #[test]
    fn service_spec_platform_serializes_omitted_when_none() {
        // Build a minimal ServiceSpec via YAML to avoid enumerating every field
        // (ServiceSpec has no Default impl and no named-struct helper).
        let yaml = r"
version: v1
deployment: test
services:
  app:
    rtype: service
    image:
      name: nginx:latest
";
        let mut spec: DeploymentSpec = serde_yaml::from_str(yaml).expect("yaml parse");
        let service = spec.services.get_mut("app").expect("service present");
        service.platform = None;
        let rendered = serde_yaml::to_string(service).expect("render");
        assert!(
            !rendered.contains("platform"),
            "platform must be omitted when None: {rendered}"
        );
    }

    #[test]
    fn target_platform_os_version_builder() {
        let p =
            TargetPlatform::new(OsKind::Windows, ArchKind::Amd64).with_os_version("10.0.26100.1");
        assert_eq!(p.os_version.as_deref(), Some("10.0.26100.1"));
        assert_eq!(p.os, OsKind::Windows);
        assert_eq!(p.arch, ArchKind::Amd64);
    }

    #[test]
    fn target_platform_os_version_yaml_roundtrip() {
        let yaml = "os: windows\narch: amd64\nosVersion: 10.0.26100.1\n";
        let p: TargetPlatform = serde_yaml::from_str(yaml).expect("yaml parse");
        assert_eq!(p.os_version.as_deref(), Some("10.0.26100.1"));
        assert_eq!(p.os, OsKind::Windows);
        assert_eq!(p.arch, ArchKind::Amd64);
    }

    #[test]
    fn target_platform_os_version_yaml_omits_when_none() {
        let p = TargetPlatform::new(OsKind::Linux, ArchKind::Amd64);
        let rendered = serde_yaml::to_string(&p).expect("render");
        assert!(
            !rendered.contains("osVersion"),
            "osVersion must be omitted when None: {rendered}"
        );
    }

    #[test]
    fn target_platform_as_detailed_str_includes_version() {
        let without = TargetPlatform::new(OsKind::Windows, ArchKind::Amd64).as_detailed_str();
        assert_eq!(without, "windows/amd64");

        let with = TargetPlatform::new(OsKind::Windows, ArchKind::Amd64)
            .with_os_version("10.0.26100.1")
            .as_detailed_str();
        assert_eq!(with, "windows/amd64 (os.version=10.0.26100.1)");
    }

    #[test]
    fn target_platform_display_ignores_version() {
        // Display deliberately stays terse so existing log lines don't change.
        let p =
            TargetPlatform::new(OsKind::Windows, ArchKind::Amd64).with_os_version("10.0.26100.1");
        assert_eq!(format!("{p}"), "windows/amd64");
    }

    // ----------------------------------------------------------------------
    // Phase 1 Task 1.1: Docker-compat ServiceSpec/ResourcesSpec extensions.
    // ----------------------------------------------------------------------

    /// Build a minimal-but-valid `ServiceSpec` for round-trip tests.
    fn fixture_service_spec_full() -> ServiceSpec {
        let yaml = r"
version: v1
deployment: phase1-task1
services:
  hello:
    rtype: service
    image:
      name: hello-world:latest
";
        let spec: DeploymentSpec = serde_yaml::from_str(yaml).expect("parse fixture");
        spec.services.get("hello").expect("hello service").clone()
    }

    #[test]
    fn service_spec_round_trip_with_all_new_fields() {
        let mut spec = fixture_service_spec_full();
        spec.labels
            .insert("zlayer.team".to_string(), "platform".to_string());
        spec.user = Some("1000:1000".to_string());
        spec.stop_signal = Some("SIGTERM".to_string());
        spec.stop_grace_period = Some(std::time::Duration::from_secs(30));
        spec.sysctls
            .insert("net.core.somaxconn".to_string(), "1024".to_string());
        spec.ulimits.insert(
            "nofile".to_string(),
            UlimitSpec {
                soft: 65_536,
                hard: 65_536,
            },
        );
        spec.security_opt.push("no-new-privileges:true".to_string());
        spec.pid_mode = Some("host".to_string());
        spec.ipc_mode = Some("private".to_string());
        spec.network_mode = NetworkMode::Bridge {
            name: Some("custom-net".to_string()),
        };
        spec.cap_drop.push("NET_RAW".to_string());
        spec.extra_groups.push("docker".to_string());
        spec.read_only_root_fs = true;
        spec.init_container = Some(true);
        spec.resources.pids_limit = Some(2048);
        spec.resources.cpuset = Some("0-3".to_string());
        spec.resources.cpu_shares = Some(1024);
        spec.resources.memory_swap = Some("2Gi".to_string());
        spec.resources.memory_reservation = Some("256Mi".to_string());
        spec.resources.memory_swappiness = Some(10);
        spec.resources.oom_score_adj = Some(-500);
        spec.resources.oom_kill_disable = Some(false);
        spec.resources.blkio_weight = Some(500);

        let yaml = serde_yaml::to_string(&spec).expect("serialize");
        let round: ServiceSpec = serde_yaml::from_str(&yaml).expect("deserialize");
        assert_eq!(spec, round, "round-trip mismatch:\n{yaml}");
    }

    #[test]
    fn network_mode_string_form_round_trip() {
        let cases: &[(&str, NetworkMode)] = &[
            ("default", NetworkMode::Default),
            ("host", NetworkMode::Host),
            ("none", NetworkMode::None),
            ("bridge", NetworkMode::Bridge { name: None }),
            (
                "bridge:custom",
                NetworkMode::Bridge {
                    name: Some("custom".to_string()),
                },
            ),
            (
                "container:abc123",
                NetworkMode::Container {
                    id: "abc123".to_string(),
                },
            ),
        ];

        for (input, expected) in cases {
            #[derive(Deserialize)]
            struct Wrap {
                #[serde(deserialize_with = "deserialize_network_mode")]
                m: NetworkMode,
            }
            let yaml = format!("m: \"{input}\"\n");
            let parsed: Wrap = serde_yaml::from_str(&yaml).expect("parse network mode");
            assert_eq!(&parsed.m, expected, "mismatch for {input}");
        }
    }

    #[test]
    fn ulimit_spec_round_trip() {
        let u = UlimitSpec {
            soft: 1024,
            hard: 65_536,
        };
        let yaml = serde_yaml::to_string(&u).expect("serialize");
        let parsed: UlimitSpec = serde_yaml::from_str(&yaml).expect("parse");
        assert_eq!(u, parsed);
    }

    #[test]
    fn host_network_true_yaml_promotes_to_network_mode_host() {
        let yaml = r"
version: v1
deployment: bc-test
services:
  hello:
    rtype: service
    image:
      name: hello-world:latest
    host_network: true
";
        let dep: DeploymentSpec = serde_yaml::from_str(yaml).expect("parse");
        let svc = dep.services.get("hello").expect("hello service");
        assert_eq!(svc.network_mode, NetworkMode::Host);
        // The legacy bool stays mirrored so in-process callers that still
        // read `host_network` continue to work.
        assert!(svc.host_network);
    }

    #[test]
    fn capabilities_yaml_alias_cap_add_round_trip() {
        // Forward-compat: ZLayer keeps the field named `capabilities`, but the
        // Docker-style key `cap_add` must also deserialize into it.
        let yaml = r"
version: v1
deployment: cap-test
services:
  hello:
    rtype: service
    image:
      name: hello-world:latest
    cap_add:
      - NET_ADMIN
      - SYS_PTRACE
";
        let dep: DeploymentSpec = serde_yaml::from_str(yaml).expect("parse cap_add alias");
        let svc = dep.services.get("hello").expect("hello service");
        assert_eq!(
            svc.capabilities,
            vec!["NET_ADMIN".to_string(), "SYS_PTRACE".to_string()]
        );
    }

    #[test]
    fn lifecycle_omitted_defaults_to_false() {
        // When `lifecycle` is absent from the YAML/JSON entirely, the
        // deserialized service must fall back to `LifecycleSpec::default()`,
        // i.e. `delete_on_exit: false` — the historical retain-on-exit
        // behavior. This guards against accidental policy flips when the
        // field is added to existing specs.
        let yaml = r"
version: v1
deployment: lifecycle-default-test
services:
  app:
    rtype: service
    image:
      name: hello-world:latest
";
        let dep: DeploymentSpec = serde_yaml::from_str(yaml).expect("parse spec without lifecycle");
        let svc = dep.services.get("app").expect("app service");
        assert_eq!(svc.lifecycle, LifecycleSpec::default());
        assert!(!svc.lifecycle.delete_on_exit);
    }

    #[test]
    fn lifecycle_delete_on_exit_round_trips() {
        // `lifecycle.delete_on_exit: true` must survive a full YAML
        // deserialize → serialize → deserialize cycle, and the explicit
        // value must propagate into the parsed `ServiceSpec`.
        let yaml = r"
version: v1
deployment: lifecycle-delete-test
services:
  app:
    rtype: service
    image:
      name: hello-world:latest
    lifecycle:
      delete_on_exit: true
";
        let dep: DeploymentSpec = serde_yaml::from_str(yaml).expect("parse spec with lifecycle");
        let svc = dep.services.get("app").expect("app service");
        assert!(svc.lifecycle.delete_on_exit);

        // Round-trip via YAML to confirm Serialize emits the field and
        // Deserialize folds it back identically.
        let dumped = serde_yaml::to_string(&dep).expect("serialize spec with lifecycle");
        let reparsed: DeploymentSpec =
            serde_yaml::from_str(&dumped).expect("reparse round-tripped spec");
        let reparsed_svc = reparsed.services.get("app").expect("app service after rt");
        assert!(reparsed_svc.lifecycle.delete_on_exit);
        assert_eq!(svc.lifecycle, reparsed_svc.lifecycle);
    }
}