zlayer-agent 0.12.1

Container runtime agent using libcontainer/youki
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
//! OCI Bundle Creation
//!
//! Creates OCI-compliant bundles for container runtimes using libcontainer (youki).
//! A bundle consists of a directory with:
//! - config.json: OCI runtime specification
//! - rootfs/: Container filesystem (symlink or bind mount target)

use crate::cdi::{self, CdiContainerEdits, CdiRegistry};
use crate::error::{AgentError, Result};
use crate::runtime::ContainerId;
use oci_spec::runtime::{
    Capability, Hook, HookBuilder, Hooks, HooksBuilder, LinuxBuilder, LinuxCapabilitiesBuilder,
    LinuxCpuBuilder, LinuxDeviceBuilder, LinuxDeviceCgroupBuilder, LinuxDeviceType,
    LinuxMemoryBuilder, LinuxNamespaceBuilder, LinuxNamespaceType, LinuxResourcesBuilder, Mount,
    MountBuilder, ProcessBuilder, RootBuilder, Spec, SpecBuilder, UserBuilder,
};
// `LinuxIdMappingBuilder` is only used by the unix-gated rootless user-namespace
// helpers below; importing it unconditionally trips dead-code lints on Windows.
#[cfg(unix)]
use oci_spec::runtime::LinuxIdMappingBuilder;
use std::collections::{HashMap, HashSet};
// `MetadataExt` is only meaningful on Unix-like hosts where `/dev/*` nodes exist
// and have major/minor numbers. On Windows this module is still built so that
// `BundleBuilder::build_spec_only` (cross-platform OCI Spec generation) can be
// called from the WSL2 delegate runtime, which then pipes the generated
// `config.json` into a Linux WSL2 distro that owns the actual device
// fingerprint. See G-1 / G-2 in the Windows plan. The import is performed
// inside `get_device_major_minor` itself to avoid an unused-import warning on
// non-Unix platforms.
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;
use tokio::fs;
use zlayer_secrets::SecretsProvider;
use zlayer_spec::{GpuSharingMode, ServiceSpec, StorageSpec, StorageTier};

/// Default host directory for the NVIDIA MPS control pipe when the spec
/// doesn't override [`zlayer_spec::GpuSpec::mps_pipe_dir`].
const DEFAULT_MPS_PIPE_DIR: &str = "/tmp/nvidia-mps";

/// Default host directory for NVIDIA MPS log output when the spec doesn't
/// override [`zlayer_spec::GpuSpec::mps_log_dir`].
const DEFAULT_MPS_LOG_DIR: &str = "/tmp/nvidia-log";

/// Container path where a host-supplied NVIDIA time-slicing config YAML is
/// surfaced (read-only). The file is informational — `ZLayer` doesn't interpret
/// it; tools running inside the container can read it to discover slice
/// topology.
const TIMESLICE_CONFIG_CONTAINER_PATH: &str = "/etc/nvidia/gpu-time-slicing.yaml";

/// Resolved MPS host directories (pipe + log), validated to exist on disk.
///
/// Returned by [`resolve_mps_dirs`] only when `GpuSpec.sharing == Mps`. Both
/// paths are absolute and guaranteed to be directories at the time the
/// helper ran — callers can bind-mount them directly.
struct MpsDirs {
    pipe_dir: PathBuf,
    log_dir: PathBuf,
}

/// Resolve and validate the MPS pipe / log directories for a GPU spec.
///
/// Returns `Ok(None)` when sharing is not MPS (or absent), `Ok(Some(...))`
/// when both directories exist on the host, or
/// [`AgentError::GpuSharingUnavailable`] when either directory is missing.
///
/// Defaults to [`DEFAULT_MPS_PIPE_DIR`] / [`DEFAULT_MPS_LOG_DIR`] when the
/// spec omits explicit paths, matching the convention used by
/// `nvidia-cuda-mps-control` out of the box.
fn resolve_mps_dirs(gpu: &zlayer_spec::GpuSpec) -> Result<Option<MpsDirs>> {
    if gpu.sharing != Some(GpuSharingMode::Mps) {
        return Ok(None);
    }

    let pipe_dir = PathBuf::from(gpu.mps_pipe_dir.as_deref().unwrap_or(DEFAULT_MPS_PIPE_DIR));
    let log_dir = PathBuf::from(gpu.mps_log_dir.as_deref().unwrap_or(DEFAULT_MPS_LOG_DIR));

    if !pipe_dir.is_dir() {
        return Err(AgentError::GpuSharingUnavailable {
            mode: "mps".to_string(),
            reason: format!(
                "MPS pipe directory {} does not exist; ensure nvidia-cuda-mps-control is running",
                pipe_dir.display()
            ),
        });
    }
    if !log_dir.is_dir() {
        return Err(AgentError::GpuSharingUnavailable {
            mode: "mps".to_string(),
            reason: format!(
                "MPS log directory {} does not exist; ensure nvidia-cuda-mps-control is running",
                log_dir.display()
            ),
        });
    }

    Ok(Some(MpsDirs { pipe_dir, log_dir }))
}

/// Convert a CDI device node descriptor into the OCI [`LinuxDevice`] used by
/// the runtime.
///
/// CDI device nodes may omit `type`, `major`, and `minor` — in that case we
/// probe the host (via `get_device_type` / `get_device_major_minor`) using
/// the resolved host path, falling back to character device with zero
/// major/minor when the file is unavailable (typical for test fixtures
/// that reference paths that don't exist on the build host).
fn cdi_node_to_oci_device(
    node: &crate::cdi::CdiDeviceNode,
) -> Result<oci_spec::runtime::LinuxDevice> {
    let host_path = node.host_path.as_deref().unwrap_or(&node.path);

    let dev_type = match node.device_type.as_deref() {
        Some("c" | "u") => LinuxDeviceType::C,
        Some("b") => LinuxDeviceType::B,
        Some("p") => LinuxDeviceType::P,
        _ => get_device_type(host_path).unwrap_or(LinuxDeviceType::C),
    };

    let (major, minor) = if let (Some(maj), Some(min)) = (node.major, node.minor) {
        (maj, min)
    } else {
        get_device_major_minor(host_path).unwrap_or((0, 0))
    };

    let mut builder = LinuxDeviceBuilder::default()
        .path(node.path.clone())
        .typ(dev_type)
        .major(major)
        .minor(minor);
    if let Some(mode) = node.file_mode {
        builder = builder.file_mode(mode);
    } else {
        builder = builder.file_mode(0o666u32);
    }
    builder = builder.uid(node.uid.unwrap_or(0));
    builder = builder.gid(node.gid.unwrap_or(0));

    builder.build().map_err(|e| {
        AgentError::InvalidSpec(format!(
            "failed to build CDI device {path}: {e}",
            path = node.path
        ))
    })
}

/// Convert a CDI hook descriptor into the OCI [`Hook`] used by the runtime.
fn convert_cdi_hook(cdi_hook: &crate::cdi::CdiHook) -> Result<Hook> {
    let mut builder = HookBuilder::default().path(PathBuf::from(&cdi_hook.path));
    if !cdi_hook.args.is_empty() {
        builder = builder.args(cdi_hook.args.clone());
    }
    if !cdi_hook.env.is_empty() {
        builder = builder.env(cdi_hook.env.clone());
    }
    builder
        .build()
        .map_err(|e| AgentError::InvalidSpec(format!("failed to build CDI hook: {e}")))
}

/// All Linux capabilities for privileged mode
const ALL_CAPABILITIES: &[Capability] = &[
    Capability::AuditControl,
    Capability::AuditRead,
    Capability::AuditWrite,
    Capability::BlockSuspend,
    Capability::Bpf,
    Capability::CheckpointRestore,
    Capability::Chown,
    Capability::DacOverride,
    Capability::DacReadSearch,
    Capability::Fowner,
    Capability::Fsetid,
    Capability::IpcLock,
    Capability::IpcOwner,
    Capability::Kill,
    Capability::Lease,
    Capability::LinuxImmutable,
    Capability::MacAdmin,
    Capability::MacOverride,
    Capability::Mknod,
    Capability::NetAdmin,
    Capability::NetBindService,
    Capability::NetBroadcast,
    Capability::NetRaw,
    Capability::Perfmon,
    Capability::Setfcap,
    Capability::Setgid,
    Capability::Setpcap,
    Capability::Setuid,
    Capability::SysAdmin,
    Capability::SysBoot,
    Capability::SysChroot,
    Capability::SysModule,
    Capability::SysNice,
    Capability::SysPacct,
    Capability::SysPtrace,
    Capability::SysRawio,
    Capability::SysResource,
    Capability::SysTime,
    Capability::SysTtyConfig,
    Capability::Syslog,
    Capability::WakeAlarm,
];

/// Parse memory string like "512Mi", "1Gi" to bytes
///
/// Supports both IEC (binary) and SI (decimal) units:
/// - IEC: Ki, Mi, Gi, Ti (powers of 1024)
/// - SI: K/k, M/m, G/g, T/t (powers of 1000)
/// - No suffix: bytes
///
/// # Examples
/// ```ignore
/// assert_eq!(parse_memory_string("512Mi").unwrap(), 512 * 1024 * 1024);
/// assert_eq!(parse_memory_string("1Gi").unwrap(), 1024 * 1024 * 1024);
/// assert_eq!(parse_memory_string("2G").unwrap(), 2 * 1000 * 1000 * 1000);
/// ```
///
/// # Errors
/// Returns an error if the string cannot be parsed as a memory size.
pub fn parse_memory_string(s: &str) -> std::result::Result<u64, String> {
    let s = s.trim();
    if s.is_empty() {
        return Err("empty memory string".to_string());
    }

    let (num_str, multiplier) = if let Some(n) = s.strip_suffix("Ki") {
        (n, 1024u64)
    } else if let Some(n) = s.strip_suffix("Mi") {
        (n, 1024u64 * 1024)
    } else if let Some(n) = s.strip_suffix("Gi") {
        (n, 1024u64 * 1024 * 1024)
    } else if let Some(n) = s.strip_suffix("Ti") {
        (n, 1024u64 * 1024 * 1024 * 1024)
    } else if let Some(n) = s.strip_suffix('K').or_else(|| s.strip_suffix('k')) {
        (n, 1000u64)
    } else if let Some(n) = s.strip_suffix('M').or_else(|| s.strip_suffix('m')) {
        (n, 1000u64 * 1000)
    } else if let Some(n) = s.strip_suffix('G').or_else(|| s.strip_suffix('g')) {
        (n, 1000u64 * 1000 * 1000)
    } else if let Some(n) = s.strip_suffix('T').or_else(|| s.strip_suffix('t')) {
        (n, 1000u64 * 1000 * 1000 * 1000)
    } else {
        (s, 1u64)
    };

    let num: u64 = num_str
        .parse()
        .map_err(|e| format!("invalid number: {e}"))?;

    Ok(num * multiplier)
}

/// Get major and minor device numbers from a device path
///
/// Unix-only: relies on `MetadataExt::rdev()` which isn't available on Windows.
/// When `bundle.rs` is compiled for a Windows host (for the WSL2 delegate's
/// cross-platform `build_spec_only` path), device probing is skipped entirely —
/// the Linux side of the delegate is responsible for its own device fingerprint.
/// The non-Unix stub below returns `Unsupported` so the `if let Ok(..)` /
/// `.unwrap_or(..)` call sites at the CDI / GPU passthrough paths skip cleanly.
#[cfg(unix)]
#[allow(clippy::cast_possible_wrap)]
fn get_device_major_minor(path: &str) -> std::io::Result<(i64, i64)> {
    use std::os::unix::fs::MetadataExt;
    let metadata = std::fs::metadata(path)?;
    let rdev = metadata.rdev();
    // Major is upper 8 bits (after shifting), minor is lower 8 bits
    let major = ((rdev >> 8) & 0xff) as i64;
    let minor = (rdev & 0xff) as i64;
    Ok((major, minor))
}

/// Non-Unix stub: device-cgroup probes require Unix; callers use `if let Ok(..)` to skip.
#[cfg(not(unix))]
fn get_device_major_minor(_path: &str) -> std::io::Result<(i64, i64)> {
    Err(std::io::Error::new(
        std::io::ErrorKind::Unsupported,
        "device-cgroup probes require Unix",
    ))
}

/// Detect device type from path
///
/// Unix-only: uses `FileTypeExt::is_char_device` / `is_block_device` which are
/// not available on Windows. See `get_device_major_minor` for the rationale.
#[cfg(unix)]
fn get_device_type(path: &str) -> std::io::Result<LinuxDeviceType> {
    use std::os::unix::fs::FileTypeExt;
    let metadata = std::fs::metadata(path)?;
    let file_type = metadata.file_type();
    if file_type.is_char_device() {
        Ok(LinuxDeviceType::C)
    } else if file_type.is_block_device() {
        Ok(LinuxDeviceType::B)
    } else {
        Ok(LinuxDeviceType::U) // Unknown/other
    }
}

/// Non-Unix stub: device-cgroup probes require Unix; callers use `.unwrap_or(..)` to skip.
#[cfg(not(unix))]
fn get_device_type(_path: &str) -> std::io::Result<LinuxDeviceType> {
    Err(std::io::Error::new(
        std::io::ErrorKind::Unsupported,
        "device-cgroup probes require Unix",
    ))
}

/// Builder for OCI container bundles
///
/// Creates the directory structure and config.json required for OCI-compliant
/// container runtimes like runc or youki.
///
/// # Example
/// ```ignore
/// let dirs = zlayer_paths::ZLayerDirs::system_default();
/// let builder = BundleBuilder::new(dirs.bundles().join("mycontainer"))
///     .with_rootfs(dirs.rootfs().join("myimage"));
///
/// let bundle_path = builder.build(&container_id, &service_spec).await?;
/// ```
#[derive(Clone)]
pub struct BundleBuilder {
    /// Base directory for the bundle
    bundle_dir: PathBuf,
    /// Path to the unpacked rootfs (from image layers)
    rootfs_path: Option<PathBuf>,
    /// Custom hostname (defaults to container ID)
    hostname: Option<String>,
    /// Additional environment variables
    extra_env: Vec<(String, String)>,
    /// Custom working directory
    cwd: Option<String>,
    /// Custom command/args to run (overrides image default)
    args: Option<Vec<String>>,
    /// Pre-resolved volume paths from `StorageManager`
    volume_paths: HashMap<String, PathBuf>,
    /// Image configuration from the OCI registry (entrypoint, cmd, env, workdir, user)
    image_config: Option<zlayer_registry::ImageConfig>,
    /// Use host networking (skip Network namespace, container shares host network)
    host_network: bool,
    /// Secrets provider for resolving $S: prefixed env vars
    secrets_provider: Option<Arc<dyn SecretsProvider>>,
    /// Deployment scope for secret lookups (e.g., deployment name)
    deployment_scope: Option<String>,
    /// Host-side Unix socket path to bind-mount into the container
    socket_path: Option<String>,
    /// Optional CDI registry override (defaults to discovery from system paths).
    ///
    /// Wrapped in `Arc` so [`BundleBuilder`] can stay [`Clone`]. Primarily set
    /// in tests via [`BundleBuilder::with_cdi_registry`]; production paths
    /// leave this `None` and lazy-discover via [`CdiRegistry::discover`] when
    /// a `GpuSpec` is present.
    cdi_registry: Option<Arc<CdiRegistry>>,
}

impl std::fmt::Debug for BundleBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BundleBuilder")
            .field("bundle_dir", &self.bundle_dir)
            .field("rootfs_path", &self.rootfs_path)
            .field("hostname", &self.hostname)
            .field("extra_env", &self.extra_env)
            .field("cwd", &self.cwd)
            .field("args", &self.args)
            .field("volume_paths", &self.volume_paths)
            .field("image_config", &self.image_config)
            .field("host_network", &self.host_network)
            .field("secrets_provider", &self.secrets_provider.is_some())
            .field("deployment_scope", &self.deployment_scope)
            .field("socket_path", &self.socket_path)
            .field("cdi_registry", &self.cdi_registry.is_some())
            .finish()
    }
}

/// Build OCI `uid_mappings` (or `gid_mappings` — same structure) for a rootless
/// container. Always emits a single-id mapping (container 0 → `host_id`, size 1).
/// If `username` has an entry in `subid_path` (e.g. /etc/subuid), appends a
/// range mapping (container 1 → range start, size = range count).
///
/// Rootless user-namespace mapping is a Linux/libcontainer concept; on Windows
/// containers run via HCS so this helper is unix-only.
#[cfg(unix)]
fn build_rootless_id_mappings(
    host_id: u32,
    subid_path: &str,
    username: &str,
) -> Vec<oci_spec::runtime::LinuxIdMapping> {
    let mut mappings = vec![LinuxIdMappingBuilder::default()
        .container_id(0_u32)
        .host_id(host_id)
        .size(1_u32)
        .build()
        .unwrap()];
    if !username.is_empty() {
        if let Some((start, count)) = read_subid_range(subid_path, username) {
            mappings.push(
                LinuxIdMappingBuilder::default()
                    .container_id(1_u32)
                    .host_id(start)
                    .size(count)
                    .build()
                    .unwrap(),
            );
        }
    }
    mappings
}

/// Read /etc/subuid (or /etc/subgid) and return the (start, count) range
/// allocated to the given username, if any. Returns None on any I/O error
/// or when the user has no entry — callers must fall back to a single-id
/// mapping in that case.
///
/// Subuid files are a Linux concept and the only caller is the unix-gated
/// `build_rootless_id_mappings`, so this helper is unix-only as well.
#[cfg(unix)]
fn read_subid_range(path: &str, username: &str) -> Option<(u32, u32)> {
    let contents = std::fs::read_to_string(path).ok()?;
    for line in contents.lines() {
        let mut parts = line.splitn(3, ':');
        let user = parts.next()?;
        if user != username {
            continue;
        }
        let start: u32 = parts.next()?.parse().ok()?;
        let count: u32 = parts.next()?.parse().ok()?;
        return Some((start, count));
    }
    None
}

impl BundleBuilder {
    /// Create a new `BundleBuilder` with the specified bundle directory
    ///
    /// The bundle directory will be created if it doesn't exist.
    /// The structure will be:
    /// ```text
    /// {bundle_dir}/
    /// ├── config.json
    /// └── rootfs/  (symlink to actual rootfs or mount point)
    /// ```
    #[must_use]
    pub fn new(bundle_dir: PathBuf) -> Self {
        Self {
            bundle_dir,
            rootfs_path: None,
            hostname: None,
            extra_env: Vec::new(),
            cwd: None,
            args: None,
            volume_paths: HashMap::new(),
            image_config: None,
            host_network: false,
            secrets_provider: None,
            deployment_scope: None,
            socket_path: None,
            cdi_registry: None,
        }
    }

    /// Override the CDI registry used for GPU device resolution.
    ///
    /// When unset, [`build_oci_spec`](Self::build_oci_spec) discovers CDI
    /// specs lazily from the standard system search paths (`/etc/cdi`,
    /// `/var/run/cdi`, plus `$CDI_SPEC_DIRS`). Tests use this setter to
    /// inject fixture-backed registries pointed at a temp directory.
    #[must_use]
    pub fn with_cdi_registry(mut self, registry: Arc<CdiRegistry>) -> Self {
        self.cdi_registry = Some(registry);
        self
    }

    /// Create a `BundleBuilder` for a container in the default bundle location
    #[must_use]
    pub fn for_container(container_id: &ContainerId) -> Self {
        let bundle_dir = zlayer_paths::ZLayerDirs::system_default()
            .bundles()
            .join(container_id.to_string());
        Self::new(bundle_dir)
    }

    /// Set the rootfs path (from unpacked image layers)
    ///
    /// This path will be symlinked into the bundle as `rootfs/`
    #[must_use]
    pub fn with_rootfs(mut self, rootfs_path: PathBuf) -> Self {
        self.rootfs_path = Some(rootfs_path);
        self
    }

    /// Set a custom hostname for the container
    #[must_use]
    pub fn with_hostname(mut self, hostname: String) -> Self {
        self.hostname = Some(hostname);
        self
    }

    /// Add extra environment variables
    #[must_use]
    pub fn with_env(mut self, key: String, value: String) -> Self {
        self.extra_env.push((key, value));
        self
    }

    /// Set the working directory
    #[must_use]
    pub fn with_cwd(mut self, cwd: String) -> Self {
        self.cwd = Some(cwd);
        self
    }

    /// Set the command/args to run
    #[must_use]
    pub fn with_args(mut self, args: Vec<String>) -> Self {
        self.args = Some(args);
        self
    }

    /// Set pre-resolved volume paths from `StorageManager`
    ///
    /// These are used to map named/anonymous/S3 volumes to their host paths
    /// when building storage mounts in the OCI spec.
    #[must_use]
    pub fn with_volume_paths(mut self, volume_paths: HashMap<String, PathBuf>) -> Self {
        self.volume_paths = volume_paths;
        self
    }

    /// Set the OCI image configuration (entrypoint, cmd, env, workdir, user)
    ///
    /// When set, the image config provides defaults for the container process
    /// that are used when the deployment spec doesn't override them.
    #[must_use]
    pub fn with_image_config(mut self, config: zlayer_registry::ImageConfig) -> Self {
        self.image_config = Some(config);
        self
    }

    /// Enable host networking mode
    ///
    /// When true, the container will NOT get its own network namespace and will
    /// share the host's network stack. This is equivalent to Docker's `--network host`.
    /// Use this when overlay networking is unavailable or not desired.
    #[must_use]
    pub fn with_host_network(mut self, host_network: bool) -> Self {
        self.host_network = host_network;
        self
    }

    /// Set the secrets provider for resolving `$S:` prefixed environment variables
    ///
    /// When set, environment variables with `$S:secret-name` syntax will be resolved
    /// from this provider at bundle creation time.
    #[must_use]
    pub fn with_secrets_provider(mut self, provider: Arc<dyn SecretsProvider>) -> Self {
        self.secrets_provider = Some(provider);
        self
    }

    /// Set the deployment scope for secret lookups
    ///
    /// This is typically the deployment name and is used as the scope when
    /// resolving `$S:` prefixed environment variables.
    #[must_use]
    pub fn with_deployment_scope(mut self, scope: String) -> Self {
        self.deployment_scope = Some(scope);
        self
    }

    /// Set a host-side Unix socket path to bind-mount into the container at
    /// the default `ZLayer` socket path (read-only).
    #[must_use]
    pub fn with_socket_mount(mut self, path: impl Into<String>) -> Self {
        self.socket_path = Some(path.into());
        self
    }

    /// Get the bundle directory path
    #[must_use]
    pub fn bundle_dir(&self) -> &Path {
        &self.bundle_dir
    }

    /// Build the OCI bundle from a `ServiceSpec`
    ///
    /// Creates the bundle directory structure and generates config.json
    /// based on the provided service specification.
    ///
    /// # Returns
    /// The path to the bundle directory on success
    ///
    /// # Errors
    /// - `AgentError::CreateFailed` if directory creation fails
    /// - `AgentError::InvalidSpec` if the OCI spec generation fails
    ///
    /// # Platform
    /// Unix-only. Uses `tokio::fs::symlink` which is defined in terms of
    /// `std::os::unix::fs::symlink` and does not exist on Windows. The Windows
    /// WSL2 delegate path should call [`BundleBuilder::build_spec_only`] to
    /// obtain the OCI [`Spec`] and pipe it into the WSL2 distro, where the
    /// Linux side of the delegate handles bundle directory creation.
    #[cfg(unix)]
    pub async fn build(&self, container_id: &ContainerId, spec: &ServiceSpec) -> Result<PathBuf> {
        // Create bundle directory
        fs::create_dir_all(&self.bundle_dir)
            .await
            .map_err(|e| AgentError::CreateFailed {
                id: container_id.to_string(),
                reason: format!("failed to create bundle directory: {e}"),
            })?;

        // Set up rootfs (symlink or create empty directory)
        let rootfs_in_bundle = self.bundle_dir.join("rootfs");
        if let Some(ref rootfs_path) = self.rootfs_path {
            // Remove existing rootfs symlink/dir if present
            let _ = fs::remove_file(&rootfs_in_bundle).await;
            let _ = fs::remove_dir(&rootfs_in_bundle).await;

            // Create symlink to actual rootfs.
            // On Unix: `tokio::fs::symlink` (unified file/dir symlink).
            // On Windows: `tokio::fs::symlink_dir` (wraps CreateSymbolicLinkW with
            // SYMBOLIC_LINK_FLAG_DIRECTORY) — rootfs is always an OCI layer directory.
            #[cfg(unix)]
            tokio::fs::symlink(rootfs_path, &rootfs_in_bundle)
                .await
                .map_err(|e| AgentError::CreateFailed {
                    id: container_id.to_string(),
                    reason: format!(
                        "failed to symlink rootfs from {} to {}: {}",
                        rootfs_path.display(),
                        rootfs_in_bundle.display(),
                        e
                    ),
                })?;

            #[cfg(windows)]
            tokio::fs::symlink_dir(rootfs_path, &rootfs_in_bundle)
                .await
                .map_err(|e| AgentError::CreateFailed {
                    id: container_id.to_string(),
                    reason: format!(
                        "failed to symlink rootfs from {} to {}: {}",
                        rootfs_path.display(),
                        rootfs_in_bundle.display(),
                        e
                    ),
                })?;
        } else {
            // Create empty rootfs directory (for bind mounts)
            fs::create_dir_all(&rootfs_in_bundle)
                .await
                .map_err(|e| AgentError::CreateFailed {
                    id: container_id.to_string(),
                    reason: format!("failed to create rootfs directory: {e}"),
                })?;
        }

        // Generate OCI runtime spec
        let oci_spec = self
            .build_spec_only(container_id, spec, &self.volume_paths)
            .await?;

        // Write config.json
        let config_path = self.bundle_dir.join("config.json");
        let config_json =
            serde_json::to_string_pretty(&oci_spec).map_err(|e| AgentError::CreateFailed {
                id: container_id.to_string(),
                reason: format!("failed to serialize OCI spec: {e}"),
            })?;

        fs::write(&config_path, config_json)
            .await
            .map_err(|e| AgentError::CreateFailed {
                id: container_id.to_string(),
                reason: format!("failed to write config.json: {e}"),
            })?;

        tracing::debug!(
            "Created OCI bundle at {} for container {}",
            self.bundle_dir.display(),
            container_id
        );

        Ok(self.bundle_dir.clone())
    }

    /// Render the OCI runtime spec without creating a bundle directory
    /// or writing `config.json`.
    ///
    /// This is the cross-platform entry point for OCI spec generation and is
    /// the only bundle-builder method that is callable on Windows. Used by the
    /// WSL2 delegate runtime (`runtimes/wsl2_delegate.rs`): the Windows host
    /// renders the spec, then streams the JSON into the WSL distro filesystem
    /// where `youki` will consume it. The bundle path passed to
    /// `BundleBuilder::new` is purely informational in that flow; this method
    /// never touches the filesystem.
    ///
    /// Unix hosts that want both the spec *and* the on-disk bundle layout
    /// (rootfs symlink, `config.json`, parent directories) should continue to
    /// use [`BundleBuilder::build`] or [`BundleBuilder::write_config`].
    ///
    /// # Errors
    /// Returns [`AgentError::InvalidSpec`] if any of the OCI `*Builder` types
    /// reject the configuration, or if environment-variable secret resolution
    /// fails.
    pub async fn build_spec_only(
        &self,
        container_id: &ContainerId,
        spec: &ServiceSpec,
        volume_paths: &std::collections::HashMap<String, PathBuf>,
    ) -> Result<oci_spec::runtime::Spec> {
        self.build_oci_spec(container_id, spec, volume_paths).await
    }

    /// Resolve CDI edits for a service spec's GPU request, if any.
    ///
    /// Returns:
    /// - `Ok(None)` when the spec has no `GpuSpec`, when the vendor isn't a
    ///   known CDI-published kind (e.g. `"apple"`), or when no explicit
    ///   registry was set and lazy discovery turned up no installed specs
    ///   (production fallback — baked-in defaults take over).
    /// - `Ok(Some(vec))` with one entry per requested device when CDI specs
    ///   are available and resolution succeeds.
    /// - `Err(AgentError::InvalidSpec(...))` when the caller explicitly opted
    ///   into CDI (via `with_cdi_registry`) but the resolution fails —
    ///   surfaces [`cdi::CdiError::SpecMissing`] /
    ///   [`cdi::CdiError::DeviceMissing`] / [`cdi::CdiError::NoDevices`] as
    ///   actionable strings.
    fn resolve_cdi_edits(&self, spec: &ServiceSpec) -> Result<Option<Vec<CdiContainerEdits>>> {
        let Some(ref gpu) = spec.resources.gpu else {
            return Ok(None);
        };

        // Map short vendor to CDI kind. Unknown vendors (e.g. "apple") fall
        // back to baked-in behavior.
        let Some(kind) = cdi::vendor_to_cdi_kind(&gpu.vendor) else {
            return Ok(None);
        };

        // Decide registry source:
        // - Explicit override: strict mode. Missing kind/device == hard error.
        // - Lazy discover: opportunistic. Missing kind == silent fallback to
        //   baked-in defaults so prod hosts without CDI installed keep
        //   working.
        let (registry, strict) = if let Some(reg) = &self.cdi_registry {
            (reg.clone(), true)
        } else {
            let reg = Arc::new(CdiRegistry::discover());
            if reg.is_empty() {
                return Ok(None);
            }
            (reg, false)
        };

        let device_names: Vec<String> = (0..gpu.count).map(|i| i.to_string()).collect();

        match registry.resolve_for_kind(kind, &device_names) {
            Ok(edits) => Ok(Some(edits)),
            Err(err) => {
                if strict {
                    Err(AgentError::InvalidSpec(format!(
                        "CDI resolution failed for vendor '{}': {err}",
                        gpu.vendor
                    )))
                } else {
                    tracing::warn!(
                        vendor = %gpu.vendor,
                        kind = %kind,
                        error = %err,
                        "CDI resolution failed; falling back to baked-in GPU device passthrough"
                    );
                    Ok(None)
                }
            }
        }
    }

    /// Build the OCI runtime spec from `ServiceSpec`.
    ///
    /// The full, CDI-aware implementation that backs both
    /// [`BundleBuilder::build_spec_only`] (cross-platform, public) and the
    /// Unix-only [`BundleBuilder::build`] / [`BundleBuilder::write_config`]
    /// paths that additionally manage the bundle directory on disk.
    ///
    /// # Errors
    /// Returns [`AgentError::InvalidSpec`] if any of the OCI `*Builder` types
    /// reject the configuration, or if environment-variable secret resolution
    /// fails.
    ///
    /// # Panics
    /// Panics if the builder-internal `MountBuilder::build()` call fails for
    /// the optional `ZLayer` API socket bind-mount. This is only reachable when
    /// [`BundleBuilder::with_socket_mount`] has been used with a malformed
    /// path, and is treated as a programmer error because all fields are
    /// statically constructed from known-good inputs.
    #[allow(clippy::too_many_lines)]
    async fn build_oci_spec(
        &self,
        container_id: &ContainerId,
        spec: &ServiceSpec,
        volume_paths: &std::collections::HashMap<String, PathBuf>,
    ) -> Result<Spec> {
        // Resolve CDI edits up front. When present, these replace the
        // baked-in vendor device-node / env injection below; when absent
        // (no CDI installed, unknown vendor), the legacy code paths run.
        let cdi_edits = self.resolve_cdi_edits(spec)?;

        // Build user: image config user > root (spec doesn't currently have user override)
        let user = {
            let (uid, gid) = if let Some(user_str) = self
                .image_config
                .as_ref()
                .and_then(|c| c.user.as_ref())
                .filter(|u| !u.is_empty())
            {
                // Parse "uid:gid" or "uid" format from image config
                let parts: Vec<&str> = user_str.splitn(2, ':').collect();
                let uid = parts[0].parse::<u32>().unwrap_or(0);
                let gid = if parts.len() > 1 {
                    parts[1].parse::<u32>().unwrap_or(0)
                } else {
                    uid
                };
                (uid, gid)
            } else {
                (0u32, 0u32)
            };

            UserBuilder::default()
                .uid(uid)
                .gid(gid)
                .build()
                .map_err(|e| AgentError::InvalidSpec(format!("failed to build user: {e}")))?
        };

        // Build environment variables
        // Layer: image config env (base) -> defaults -> spec env -> builder extra env
        let mut env: Vec<String> = Vec::new();
        let mut env_keys: HashSet<String> = HashSet::new();

        // Seed with image config env first (lowest priority)
        if let Some(img_env) = self.image_config.as_ref().and_then(|c| c.env.as_ref()) {
            for entry in img_env {
                if let Some(key) = entry.split('=').next() {
                    env_keys.insert(key.to_string());
                }
                env.push(entry.clone());
            }
        }

        // If image config didn't provide PATH, add the default
        if !env_keys.contains("PATH") {
            env.push(
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin".to_string(),
            );
            env_keys.insert("PATH".to_string());
        }

        // Add TERM for interactive compatibility (if not already set)
        if !env_keys.contains("TERM") {
            env.push("TERM=xterm".to_string());
            env_keys.insert("TERM".to_string());
        }

        // Add service-specific env vars, resolving $S: and $E: prefixed references
        // These override image config env for same keys
        //
        // When a secrets provider is available, use the full secrets-aware resolver
        // that handles both $S: (secret) and $E: (env) prefixed values.
        // Otherwise fall back to the env-only resolver.
        if let (Some(secrets_provider), Some(scope)) =
            (&self.secrets_provider, &self.deployment_scope)
        {
            let resolved_map =
                crate::env::resolve_env_with_secrets(&spec.env, secrets_provider.as_ref(), scope)
                    .await
                    .map_err(|e| {
                        AgentError::InvalidSpec(format!(
                            "environment variable resolution failed: {e}"
                        ))
                    })?;

            for (key, value) in &resolved_map {
                if env_keys.contains(key.as_str()) {
                    env.retain(|e| e.split('=').next() != Some(key.as_str()));
                }
                env_keys.insert(key.clone());
                env.push(format!("{key}={value}"));
            }
        } else {
            let resolved = crate::env::resolve_env_vars_with_warnings(&spec.env).map_err(|e| {
                AgentError::InvalidSpec(format!("environment variable resolution failed: {e}"))
            })?;

            // Log any warnings about resolved env vars
            for warning in &resolved.warnings {
                tracing::warn!(container = %container_id, "{}", warning);
            }

            // Merge spec env: spec values take precedence over image config for same keys
            for var in &resolved.vars {
                if let Some(key) = var.split('=').next() {
                    if env_keys.contains(key) {
                        // Remove the old entry from image config
                        env.retain(|e| e.split('=').next() != Some(key));
                    }
                    env_keys.insert(key.to_string());
                }
                env.push(var.clone());
            }
        }

        // Add extra env vars from builder (highest priority)
        for (key, value) in &self.extra_env {
            if env_keys.contains(key.as_str()) {
                env.retain(|e| e.split('=').next() != Some(key.as_str()));
            }
            env_keys.insert(key.clone());
            env.push(format!("{key}={value}"));
        }

        // GPU device visibility environment variables.
        //
        // When CDI edits are available, the vendor-supplied spec is the
        // source of truth (e.g. NVIDIA's `nvidia-ctk cdi generate` emits
        // `NVIDIA_VISIBLE_DEVICES` plus driver-capability env on every
        // device entry). Otherwise fall back to the historical baked-in
        // strings so non-CDI hosts continue to advertise the right devices
        // to CUDA/ROCm/oneAPI runtimes.
        if let Some(ref edits_per_device) = cdi_edits {
            for edits in edits_per_device {
                for entry in &edits.env {
                    if let Some(key) = entry.split('=').next() {
                        if env_keys.contains(key) {
                            env.retain(|e| e.split('=').next() != Some(key));
                        }
                        env_keys.insert(key.to_string());
                    }
                    env.push(entry.clone());
                }
            }
        } else if let Some(ref gpu) = spec.resources.gpu {
            // Default to 0..count when no explicit indices are provided
            let indices: Vec<String> = (0..gpu.count).map(|i| i.to_string()).collect();
            let device_list = indices.join(",");
            match gpu.vendor.as_str() {
                "nvidia" => {
                    env.push(format!("NVIDIA_VISIBLE_DEVICES={device_list}"));
                    env.push(format!("CUDA_VISIBLE_DEVICES={device_list}"));
                }
                "amd" => {
                    env.push(format!("ROCR_VISIBLE_DEVICES={device_list}"));
                    env.push(format!("HIP_VISIBLE_DEVICES={device_list}"));
                }
                "intel" => {
                    env.push(format!("ZE_AFFINITY_MASK={device_list}"));
                }
                _ => {}
            }
        }

        // GPU sharing (MPS / time-slicing) env injection.
        //
        // Layered on top of the CDI / baked-in `*_VISIBLE_DEVICES` block above:
        // * MPS: validate host pipe/log dirs exist (error otherwise) and
        //   export `CUDA_MPS_PIPE_DIRECTORY` / `CUDA_MPS_LOG_DIRECTORY`.
        // * Time-slicing: override `CUDA_VISIBLE_DEVICES` to the configured
        //   slice index so the workload sees a single virtualised GPU rather
        //   than the full 0..count list emitted above.
        //
        // The mount side (bind-mounting the MPS dirs / time-slicing config
        // file) is handled further down where the rest of the mounts get
        // assembled.
        let mps_dirs = if let Some(ref gpu) = spec.resources.gpu {
            resolve_mps_dirs(gpu)?
        } else {
            None
        };
        if let Some(ref dirs) = mps_dirs {
            let pipe = format!("CUDA_MPS_PIPE_DIRECTORY={}", dirs.pipe_dir.display());
            let log = format!("CUDA_MPS_LOG_DIRECTORY={}", dirs.log_dir.display());
            if env_keys.contains("CUDA_MPS_PIPE_DIRECTORY") {
                env.retain(|e| e.split('=').next() != Some("CUDA_MPS_PIPE_DIRECTORY"));
            }
            if env_keys.contains("CUDA_MPS_LOG_DIRECTORY") {
                env.retain(|e| e.split('=').next() != Some("CUDA_MPS_LOG_DIRECTORY"));
            }
            env_keys.insert("CUDA_MPS_PIPE_DIRECTORY".to_string());
            env_keys.insert("CUDA_MPS_LOG_DIRECTORY".to_string());
            env.push(pipe);
            env.push(log);
        }
        if let Some(ref gpu) = spec.resources.gpu {
            if gpu.sharing == Some(GpuSharingMode::TimeSlice) {
                if let Some(idx) = gpu.time_slice_index {
                    // Time-slicing virtualises a single physical GPU as N
                    // slices; the workload sees one device, addressed by
                    // its slice index. Override whatever the CDI / baked-in
                    // path emitted earlier.
                    env.retain(|e| e.split('=').next() != Some("CUDA_VISIBLE_DEVICES"));
                    env_keys.insert("CUDA_VISIBLE_DEVICES".to_string());
                    env.push(format!("CUDA_VISIBLE_DEVICES={idx}"));
                }
            }
        }

        // Inject distributed training coordination env vars when configured.
        // MASTER_ADDR uses the service DNS name (resolved by the overlay DNS).
        // RANK defaults to 0 (overridden by the agent when placing specific replicas).
        if let Some(ref gpu) = spec.resources.gpu {
            if let Some(ref dist) = gpu.distributed {
                env.push(format!("MASTER_PORT={}", dist.master_port));
                env.push(format!("MASTER_ADDR={}", container_id.service));
                env.push("WORLD_SIZE=1".to_string());
                env.push("RANK=0".to_string());
                env.push("LOCAL_RANK=0".to_string());
                match dist.backend.as_str() {
                    "nccl" => env.push("NCCL_SOCKET_IFNAME=eth0".to_string()),
                    "gloo" => env.push("GLOO_SOCKET_IFNAME=eth0".to_string()),
                    _ => {}
                }
            }
        }

        // Build capabilities
        let capabilities = self.build_capabilities(spec)?;

        // Determine working directory: builder override > spec.command.workdir > image config > "/"
        let cwd = self
            .cwd
            .clone()
            .or_else(|| spec.command.workdir.clone())
            .or_else(|| {
                self.image_config
                    .as_ref()
                    .and_then(|c| c.working_dir.as_ref())
                    .filter(|w| !w.is_empty())
                    .cloned()
            })
            .unwrap_or_else(|| "/".to_string());

        // Resolve process args: builder override > spec command > image config > /bin/sh
        let process_args = if let Some(ref args) = self.args {
            args.clone()
        } else {
            Self::resolve_command_from_spec(spec, self.image_config.as_ref())
        };

        // Build process
        let mut process_builder = ProcessBuilder::default()
            .terminal(false)
            .user(user)
            .env(env)
            .args(process_args)
            .cwd(cwd)
            .no_new_privileges(!spec.privileged && spec.capabilities.is_empty());

        // Set capabilities if we have them
        if let Some(caps) = capabilities {
            process_builder = process_builder.capabilities(caps);
        }

        let process = process_builder
            .build()
            .map_err(|e| AgentError::InvalidSpec(format!("failed to build process: {e}")))?;

        // Build root filesystem config
        // Note: "rootfs" is relative to the bundle directory per OCI spec
        let root = RootBuilder::default()
            .path("rootfs".to_string())
            .readonly(false)
            .build()
            .map_err(|e| AgentError::InvalidSpec(format!("failed to build root: {e}")))?;

        // Build default mounts
        let mut mounts = self.build_default_mounts(spec)?;

        // Add storage mounts from spec
        let storage_mounts = self.build_storage_mounts(spec, volume_paths)?;
        mounts.extend(storage_mounts);

        // Add ZLayer API socket bind-mount if configured.
        // Use typ("bind") so libcontainer's mount code handles the source path
        // correctly for sockets (canonicalize + file-based mount point creation).
        if let Some(ref socket_path) = self.socket_path {
            mounts.push(
                MountBuilder::default()
                    .destination(zlayer_paths::ZLayerDirs::default_socket_path())
                    .typ("bind")
                    .source(socket_path.clone())
                    .options(vec!["rbind".into(), "ro".into()])
                    .build()
                    .expect("valid socket mount"),
            );
        }

        // Append CDI-provided mounts (e.g. vendor driver libraries that the
        // GPU runtime needs to expose to the container).
        if let Some(ref edits_per_device) = cdi_edits {
            for edits in edits_per_device {
                for cdi_mount in &edits.mounts {
                    let mut opts = cdi_mount.options.clone();
                    if !opts.iter().any(|o| o == "bind" || o == "rbind") {
                        opts.push("rbind".to_string());
                    }
                    mounts.push(
                        MountBuilder::default()
                            .destination(cdi_mount.container_path.clone())
                            .typ("bind")
                            .source(cdi_mount.host_path.clone())
                            .options(opts)
                            .build()
                            .map_err(|e| {
                                AgentError::InvalidSpec(format!("failed to build CDI mount: {e}"))
                            })?,
                    );
                }
            }
        }

        // GPU sharing mounts.
        //
        // MPS: bind-mount the host pipe / log directories into the container
        // at the same path so the in-container CUDA runtime can talk to the
        // MPS daemon over its UNIX socket and append to the shared log.
        // The env vars (`CUDA_MPS_PIPE_DIRECTORY` / `CUDA_MPS_LOG_DIRECTORY`)
        // are exported earlier in the env-assembly block.
        //
        // Time-slicing: optionally surface the host's slicing config YAML at
        // a well-known read-only path so introspection tools inside the
        // container can read it.
        if let Some(ref dirs) = mps_dirs {
            mounts.push(
                MountBuilder::default()
                    .destination(dirs.pipe_dir.clone())
                    .typ("bind")
                    .source(dirs.pipe_dir.clone())
                    .options(vec!["rbind".into(), "rw".into()])
                    .build()
                    .map_err(|e| {
                        AgentError::InvalidSpec(format!("failed to build MPS pipe mount: {e}"))
                    })?,
            );
            mounts.push(
                MountBuilder::default()
                    .destination(dirs.log_dir.clone())
                    .typ("bind")
                    .source(dirs.log_dir.clone())
                    .options(vec!["rbind".into(), "rw".into()])
                    .build()
                    .map_err(|e| {
                        AgentError::InvalidSpec(format!("failed to build MPS log mount: {e}"))
                    })?,
            );
        }
        if let Some(ref gpu) = spec.resources.gpu {
            if gpu.sharing == Some(GpuSharingMode::TimeSlice) {
                if let Some(ref cfg_path) = gpu.time_slicing_config_path {
                    let host = PathBuf::from(cfg_path);
                    if !host.is_file() {
                        return Err(AgentError::GpuSharingUnavailable {
                            mode: "time-slice".to_string(),
                            reason: format!(
                                "time-slicing config {} is not a regular file on the host",
                                host.display()
                            ),
                        });
                    }
                    mounts.push(
                        MountBuilder::default()
                            .destination(PathBuf::from(TIMESLICE_CONFIG_CONTAINER_PATH))
                            .typ("bind")
                            .source(host)
                            .options(vec!["rbind".into(), "ro".into()])
                            .build()
                            .map_err(|e| {
                                AgentError::InvalidSpec(format!(
                                    "failed to build time-slicing config mount: {e}"
                                ))
                            })?,
                    );
                }
            }
        }

        // Build Linux-specific config
        let linux = self.build_linux_config(container_id, spec, cdi_edits.as_deref())?;

        // Determine hostname
        let hostname = self
            .hostname
            .clone()
            .unwrap_or_else(|| container_id.to_string());

        // Build the complete spec, attaching any CDI-provided hooks.
        let mut spec_builder = SpecBuilder::default()
            .version("1.0.2".to_string())
            .root(root)
            .process(process)
            .hostname(hostname)
            .mounts(mounts)
            .linux(linux);

        if let Some(ref edits_per_device) = cdi_edits {
            if let Some(hooks) = Self::build_hooks_from_cdi(edits_per_device)? {
                spec_builder = spec_builder.hooks(hooks);
            }
        }

        let oci_spec = spec_builder
            .build()
            .map_err(|e| AgentError::InvalidSpec(format!("failed to build OCI spec: {e}")))?;

        Ok(oci_spec)
    }

    /// Convert the union of CDI hooks across all resolved devices into an
    /// OCI [`Hooks`] block.
    ///
    /// Returns `Ok(None)` when no device contributed hooks (so the spec
    /// builder skips the empty block — `oci-spec` treats `null` as "no
    /// hooks" while serializers may emit empty arrays otherwise).
    fn build_hooks_from_cdi(edits_per_device: &[CdiContainerEdits]) -> Result<Option<Hooks>> {
        let mut prestart: Vec<Hook> = Vec::new();
        let mut create_runtime: Vec<Hook> = Vec::new();
        let mut create_container: Vec<Hook> = Vec::new();
        let mut start_container: Vec<Hook> = Vec::new();
        let mut poststart: Vec<Hook> = Vec::new();
        let mut poststop: Vec<Hook> = Vec::new();

        for edits in edits_per_device {
            let Some(ref h) = edits.hooks else { continue };
            for hook in &h.prestart {
                prestart.push(convert_cdi_hook(hook)?);
            }
            for hook in &h.create_runtime {
                create_runtime.push(convert_cdi_hook(hook)?);
            }
            for hook in &h.create_container {
                create_container.push(convert_cdi_hook(hook)?);
            }
            for hook in &h.start_container {
                start_container.push(convert_cdi_hook(hook)?);
            }
            for hook in &h.poststart {
                poststart.push(convert_cdi_hook(hook)?);
            }
            for hook in &h.poststop {
                poststop.push(convert_cdi_hook(hook)?);
            }
        }

        if prestart.is_empty()
            && create_runtime.is_empty()
            && create_container.is_empty()
            && start_container.is_empty()
            && poststart.is_empty()
            && poststop.is_empty()
        {
            return Ok(None);
        }

        let mut builder = HooksBuilder::default();
        if !prestart.is_empty() {
            #[allow(deprecated)]
            {
                builder = builder.prestart(prestart);
            }
        }
        if !create_runtime.is_empty() {
            builder = builder.create_runtime(create_runtime);
        }
        if !create_container.is_empty() {
            builder = builder.create_container(create_container);
        }
        if !start_container.is_empty() {
            builder = builder.start_container(start_container);
        }
        if !poststart.is_empty() {
            builder = builder.poststart(poststart);
        }
        if !poststop.is_empty() {
            builder = builder.poststop(poststop);
        }

        let hooks = builder
            .build()
            .map_err(|e| AgentError::InvalidSpec(format!("failed to build CDI hooks: {e}")))?;
        Ok(Some(hooks))
    }

    /// Build Linux capabilities configuration
    #[allow(clippy::unused_self)]
    fn build_capabilities(
        &self,
        spec: &ServiceSpec,
    ) -> Result<Option<oci_spec::runtime::LinuxCapabilities>> {
        if spec.privileged {
            // Privileged mode: all capabilities
            let all_caps: HashSet<Capability> = ALL_CAPABILITIES.iter().copied().collect();
            let empty_caps: HashSet<Capability> = HashSet::new();

            let caps = LinuxCapabilitiesBuilder::default()
                .bounding(all_caps.clone())
                .effective(all_caps.clone())
                .permitted(all_caps)
                .inheritable(empty_caps.clone())
                .ambient(empty_caps)
                .build()
                .map_err(|e| {
                    AgentError::InvalidSpec(format!("failed to build capabilities: {e}"))
                })?;

            Ok(Some(caps))
        } else if !spec.capabilities.is_empty() {
            // Specific capabilities requested
            let caps: HashSet<Capability> = spec
                .capabilities
                .iter()
                .filter_map(|c| {
                    // Normalize capability name (add CAP_ prefix if missing, uppercase)
                    let cap_name = if c.starts_with("CAP_") {
                        c.to_uppercase()
                    } else {
                        format!("CAP_{}", c.to_uppercase())
                    };
                    Capability::from_str(&cap_name).ok()
                })
                .collect();

            let empty_caps: HashSet<Capability> = HashSet::new();

            let built_caps = LinuxCapabilitiesBuilder::default()
                .bounding(caps.clone())
                .effective(caps.clone())
                .permitted(caps)
                .inheritable(empty_caps.clone())
                .ambient(empty_caps)
                .build()
                .map_err(|e| {
                    AgentError::InvalidSpec(format!("failed to build capabilities: {e}"))
                })?;

            Ok(Some(built_caps))
        } else {
            // Default: minimal capabilities for basic container operation
            let default_caps: HashSet<Capability> = [
                Capability::Chown,
                Capability::DacOverride,
                Capability::Fsetid,
                Capability::Fowner,
                Capability::Mknod,
                Capability::NetRaw,
                Capability::Setgid,
                Capability::Setuid,
                Capability::Setfcap,
                Capability::Setpcap,
                Capability::NetBindService,
                Capability::SysChroot,
                Capability::Kill,
                Capability::AuditWrite,
            ]
            .into_iter()
            .collect();

            let empty_caps: HashSet<Capability> = HashSet::new();

            let built_caps = LinuxCapabilitiesBuilder::default()
                .bounding(default_caps.clone())
                .effective(default_caps.clone())
                .permitted(default_caps)
                .inheritable(empty_caps.clone())
                .ambient(empty_caps)
                .build()
                .map_err(|e| {
                    AgentError::InvalidSpec(format!("failed to build capabilities: {e}"))
                })?;

            Ok(Some(built_caps))
        }
    }

    /// Build default filesystem mounts for the container
    #[allow(clippy::unused_self, clippy::too_many_lines)]
    fn build_default_mounts(&self, spec: &ServiceSpec) -> Result<Vec<Mount>> {
        let mut mounts = Vec::new();

        // /proc
        mounts.push(
            MountBuilder::default()
                .destination("/proc".to_string())
                .typ("proc".to_string())
                .source("proc".to_string())
                .options(vec![
                    "nosuid".to_string(),
                    "noexec".to_string(),
                    "nodev".to_string(),
                ])
                .build()
                .map_err(|e| {
                    AgentError::InvalidSpec(format!("failed to build /proc mount: {e}"))
                })?,
        );

        // /dev
        mounts.push(
            MountBuilder::default()
                .destination("/dev".to_string())
                .typ("tmpfs".to_string())
                .source("tmpfs".to_string())
                .options(vec![
                    "nosuid".to_string(),
                    "strictatime".to_string(),
                    "mode=755".to_string(),
                    "size=65536k".to_string(),
                ])
                .build()
                .map_err(|e| AgentError::InvalidSpec(format!("failed to build /dev mount: {e}")))?,
        );

        // /dev/pts
        mounts.push(
            MountBuilder::default()
                .destination("/dev/pts".to_string())
                .typ("devpts".to_string())
                .source("devpts".to_string())
                .options(vec![
                    "nosuid".to_string(),
                    "noexec".to_string(),
                    "newinstance".to_string(),
                    "ptmxmode=0666".to_string(),
                    "mode=0620".to_string(),
                    "gid=5".to_string(),
                ])
                .build()
                .map_err(|e| {
                    AgentError::InvalidSpec(format!("failed to build /dev/pts mount: {e}"))
                })?,
        );

        // /dev/shm
        mounts.push(
            MountBuilder::default()
                .destination("/dev/shm".to_string())
                .typ("tmpfs".to_string())
                .source("shm".to_string())
                .options(vec![
                    "nosuid".to_string(),
                    "noexec".to_string(),
                    "nodev".to_string(),
                    "mode=1777".to_string(),
                    "size=65536k".to_string(),
                ])
                .build()
                .map_err(|e| {
                    AgentError::InvalidSpec(format!("failed to build /dev/shm mount: {e}"))
                })?,
        );

        // /dev/mqueue
        mounts.push(
            MountBuilder::default()
                .destination("/dev/mqueue".to_string())
                .typ("mqueue".to_string())
                .source("mqueue".to_string())
                .options(vec![
                    "nosuid".to_string(),
                    "noexec".to_string(),
                    "nodev".to_string(),
                ])
                .build()
                .map_err(|e| {
                    AgentError::InvalidSpec(format!("failed to build /dev/mqueue mount: {e}"))
                })?,
        );

        // /sys - read-only unless privileged
        let sys_options = if spec.privileged {
            vec![
                "nosuid".to_string(),
                "noexec".to_string(),
                "nodev".to_string(),
            ]
        } else {
            vec![
                "nosuid".to_string(),
                "noexec".to_string(),
                "nodev".to_string(),
                "ro".to_string(),
            ]
        };

        mounts.push(
            MountBuilder::default()
                .destination("/sys".to_string())
                .typ("sysfs".to_string())
                .source("sysfs".to_string())
                .options(sys_options)
                .build()
                .map_err(|e| AgentError::InvalidSpec(format!("failed to build /sys mount: {e}")))?,
        );

        // /sys/fs/cgroup - for cgroup access
        mounts.push(
            MountBuilder::default()
                .destination("/sys/fs/cgroup".to_string())
                .typ("cgroup2".to_string())
                .source("cgroup".to_string())
                .options(vec![
                    "nosuid".to_string(),
                    "noexec".to_string(),
                    "nodev".to_string(),
                    "relatime".to_string(),
                ])
                .build()
                .map_err(|e| {
                    AgentError::InvalidSpec(format!("failed to build cgroup mount: {e}"))
                })?,
        );

        Ok(mounts)
    }

    /// Build storage mounts from `ServiceSpec` storage entries
    ///
    /// Converts `StorageSpec` entries to OCI Mount entries.
    /// Note: Named and Anonymous volumes require `StorageManager` to prepare paths.
    /// S3 volumes require s3fs FUSE mount (handled separately).
    #[allow(clippy::unused_self, clippy::too_many_lines)]
    fn build_storage_mounts(
        &self,
        spec: &ServiceSpec,
        volume_paths: &std::collections::HashMap<String, PathBuf>,
    ) -> Result<Vec<Mount>> {
        let mut mounts = Vec::new();

        for storage in &spec.storage {
            let mount = match storage {
                StorageSpec::Bind {
                    source,
                    target,
                    readonly,
                } => {
                    let mut options = vec!["rbind".to_string()];
                    if *readonly {
                        options.push("ro".to_string());
                    } else {
                        options.push("rw".to_string());
                    }

                    MountBuilder::default()
                        .destination(target.clone())
                        .typ("none".to_string())
                        .source(source.clone())
                        .options(options)
                        .build()
                        .map_err(|e| {
                            AgentError::InvalidSpec(format!(
                                "failed to build bind mount for {target}: {e}"
                            ))
                        })?
                }

                StorageSpec::Named {
                    name,
                    target,
                    readonly,
                    tier,
                    ..
                } => {
                    // Get the prepared volume path from StorageManager
                    let source = volume_paths.get(name).ok_or_else(|| {
                        AgentError::InvalidSpec(format!(
                            "volume '{name}' not prepared - ensure StorageManager.ensure_volume() was called"
                        ))
                    })?;

                    // Warn about SQLite safety for non-local tiers
                    if matches!(tier, StorageTier::Network) {
                        tracing::warn!(
                            volume = %name,
                            tier = ?tier,
                            "Network storage tier is NOT SQLite-safe. Avoid using SQLite databases on this volume."
                        );
                    }

                    let mut options = vec!["rbind".to_string()];
                    if *readonly {
                        options.push("ro".to_string());
                    } else {
                        options.push("rw".to_string());
                    }

                    MountBuilder::default()
                        .destination(target.clone())
                        .typ("none".to_string())
                        .source(source.to_string_lossy().to_string())
                        .options(options)
                        .build()
                        .map_err(|e| {
                            AgentError::InvalidSpec(format!(
                                "failed to build named volume mount for {target}: {e}"
                            ))
                        })?
                }

                StorageSpec::Anonymous { target, tier } => {
                    // Anonymous volumes should have been created by StorageManager
                    // and the path passed in volume_paths with key "_anon_{target}"
                    let key = format!("_anon_{}", target.trim_start_matches('/').replace('/', "_"));
                    let source = volume_paths.get(&key).ok_or_else(|| {
                        AgentError::InvalidSpec(format!(
                            "anonymous volume for '{target}' not prepared"
                        ))
                    })?;

                    if matches!(tier, StorageTier::Network) {
                        tracing::warn!(
                            target = %target,
                            tier = ?tier,
                            "Network storage tier is NOT SQLite-safe."
                        );
                    }

                    let options = vec!["rbind".to_string(), "rw".to_string()];

                    MountBuilder::default()
                        .destination(target.clone())
                        .typ("none".to_string())
                        .source(source.to_string_lossy().to_string())
                        .options(options)
                        .build()
                        .map_err(|e| {
                            AgentError::InvalidSpec(format!(
                                "failed to build anonymous volume mount for {target}: {e}"
                            ))
                        })?
                }

                StorageSpec::Tmpfs { target, size, mode } => {
                    let mut options = vec!["nosuid".to_string(), "nodev".to_string()];

                    if let Some(size_str) = size {
                        options.push(format!("size={size_str}"));
                    }

                    if let Some(mode_val) = mode {
                        options.push(format!("mode={mode_val:o}"));
                    }

                    MountBuilder::default()
                        .destination(target.clone())
                        .typ("tmpfs".to_string())
                        .source("tmpfs".to_string())
                        .options(options)
                        .build()
                        .map_err(|e| {
                            AgentError::InvalidSpec(format!(
                                "failed to build tmpfs mount for {target}: {e}"
                            ))
                        })?
                }

                StorageSpec::S3 {
                    bucket,
                    prefix,
                    target,
                    readonly,
                    endpoint: _,
                    credentials: _,
                } => {
                    // S3 mounts are handled via s3fs FUSE
                    // The StorageManager should have mounted the bucket and passed the path
                    let key = format!("_s3_{}_{}", bucket, prefix.as_deref().unwrap_or(""));
                    let source = volume_paths.get(&key).ok_or_else(|| {
                        AgentError::InvalidSpec(format!(
                            "S3 volume for bucket '{bucket}' not mounted - ensure StorageManager.mount_s3() was called"
                        ))
                    })?;

                    tracing::warn!(
                        bucket = %bucket,
                        target = %target,
                        "S3 storage is NOT SQLite-safe. Use for read-heavy workloads only."
                    );

                    let mut options = vec!["rbind".to_string()];
                    if *readonly {
                        options.push("ro".to_string());
                    } else {
                        options.push("rw".to_string());
                    }

                    MountBuilder::default()
                        .destination(target.clone())
                        .typ("none".to_string())
                        .source(source.to_string_lossy().to_string())
                        .options(options)
                        .build()
                        .map_err(|e| {
                            AgentError::InvalidSpec(format!(
                                "failed to build S3 mount for {target}: {e}"
                            ))
                        })?
                }
            };

            mounts.push(mount);
        }

        Ok(mounts)
    }

    /// Build Linux-specific configuration
    #[allow(clippy::similar_names)] // euid/egid are POSIX-standard paired names
    #[allow(clippy::too_many_lines)]
    fn build_linux_config(
        &self,
        container_id: &ContainerId,
        spec: &ServiceSpec,
        cdi_edits: Option<&[CdiContainerEdits]>,
    ) -> Result<oci_spec::runtime::Linux> {
        // Build namespaces
        let mut namespaces = vec![
            LinuxNamespaceBuilder::default()
                .typ(LinuxNamespaceType::Pid)
                .build()
                .unwrap(),
            LinuxNamespaceBuilder::default()
                .typ(LinuxNamespaceType::Ipc)
                .build()
                .unwrap(),
            LinuxNamespaceBuilder::default()
                .typ(LinuxNamespaceType::Uts)
                .build()
                .unwrap(),
            LinuxNamespaceBuilder::default()
                .typ(LinuxNamespaceType::Mount)
                .build()
                .unwrap(),
        ];

        // Only add Network namespace when NOT using host networking.
        // In host networking mode, the container shares the host's network stack
        // (like Docker's --network host).
        if !self.host_network {
            namespaces.push(
                LinuxNamespaceBuilder::default()
                    .typ(LinuxNamespaceType::Network)
                    .build()
                    .unwrap(),
            );
        }

        // `nix::unistd` is unix-only. On non-unix targets (Windows), libcontainer
        // is not the runtime path (HCS is) and this function is effectively dead
        // code — so we statically force `rootless = false` there and skip the
        // user-namespace mapping block entirely.
        #[cfg(unix)]
        let rootless = !nix::unistd::geteuid().is_root();
        #[cfg(not(unix))]
        let rootless = false;

        if rootless {
            namespaces.push(
                LinuxNamespaceBuilder::default()
                    .typ(LinuxNamespaceType::User)
                    .build()
                    .unwrap(),
            );
            namespaces.push(
                LinuxNamespaceBuilder::default()
                    .typ(LinuxNamespaceType::Cgroup)
                    .build()
                    .unwrap(),
            );
        }

        let mut linux_builder = LinuxBuilder::default().namespaces(namespaces);

        #[cfg(unix)]
        if rootless {
            let euid = nix::unistd::geteuid();
            let egid = nix::unistd::getegid();
            let username = nix::unistd::User::from_uid(euid)
                .ok()
                .flatten()
                .map(|u| u.name)
                .unwrap_or_default();
            linux_builder = linux_builder
                .uid_mappings(build_rootless_id_mappings(
                    euid.as_raw(),
                    "/etc/subuid",
                    &username,
                ))
                .gid_mappings(build_rootless_id_mappings(
                    egid.as_raw(),
                    "/etc/subgid",
                    &username,
                ));
        }

        // Build resources (CPU, memory, devices)
        let resources = self.build_resources(spec)?;
        if let Some(resources) = resources {
            linux_builder = linux_builder.resources(resources);
        }

        // Build device entries for passthrough.
        //
        // When CDI edits are present, the vendor-supplied device-node list
        // replaces our baked-in vendor-specific defaults — CDI knows the
        // host's exact device geometry (which majors/minors map to which
        // GPUs) so we trust it over our static `/dev/nvidiaN` enumeration.
        let mut devices = self.build_devices(spec, None, cdi_edits.is_some())?;
        if let Some(edits_per_device) = cdi_edits {
            for edits in edits_per_device {
                for node in &edits.device_nodes {
                    devices.push(cdi_node_to_oci_device(node)?);
                }
            }
        }
        if !devices.is_empty() {
            linux_builder = linux_builder.devices(devices);
        }

        // Set rootfs propagation (matches Docker default)
        linux_builder = linux_builder.rootfs_propagation("private".to_string());

        // Set masked/readonly paths based on privileged mode
        if spec.privileged {
            // Privileged containers get no masked paths (full access)
            linux_builder = linux_builder.masked_paths(vec![]).readonly_paths(vec![]);
        } else {
            // Set masked paths for security (hide sensitive host info)
            let masked_paths = vec![
                "/proc/acpi".to_string(),
                "/proc/asound".to_string(),
                "/proc/kcore".to_string(),
                "/proc/keys".to_string(),
                "/proc/latency_stats".to_string(),
                "/proc/timer_list".to_string(),
                "/proc/timer_stats".to_string(),
                "/proc/sched_debug".to_string(),
                "/proc/scsi".to_string(),
                "/sys/firmware".to_string(),
            ];

            // Set readonly paths for security
            let readonly_paths = vec![
                "/proc/bus".to_string(),
                "/proc/fs".to_string(),
                "/proc/irq".to_string(),
                "/proc/sys".to_string(),
                "/proc/sysrq-trigger".to_string(),
            ];

            linux_builder = linux_builder
                .masked_paths(masked_paths)
                .readonly_paths(readonly_paths);
        }

        // Determine cgroups_path so libcontainer creates the container cgroup
        // under the current process's cgroup rather than at the v2 root. This
        // is required when running inside another container (e.g. Forgejo CI
        // `container:` block) where `/sys/fs/cgroup/cgroup.subtree_control` is
        // read-only. Precedence:
        //   1. spec.cgroup_parent (per-service override)         — all platforms
        //   2. ZLAYER_CGROUP_PARENT env var (host-wide override) — all platforms
        //   3. /proc/self/cgroup (auto-detect when nested)       — Linux only
        //   4. unset (default — bare-metal happy path; also the WSL2-delegate
        //      case on non-Linux hosts, where libcontainer inside the WSL
        //      distro resolves the parent at `zlayer runtime create` time)
        let cid = container_id.to_string();

        // Explicit overrides are honored on every platform: a user might pin a
        // cgroup_parent for a WSL-delegate-bound spec even when this process
        // is running on Windows.
        let explicit_parent: Option<(String, &'static str)> =
            if let Some(p) = spec.cgroup_parent.as_deref().filter(|s| !s.is_empty()) {
                Some((p.to_string(), "spec"))
            } else if let Some(p) = std::env::var("ZLAYER_CGROUP_PARENT")
                .ok()
                .filter(|s| !s.is_empty())
            {
                Some((p, "env"))
            } else {
                None
            };

        // Auto-detect (and the "no writable parent" hard error below) are
        // Linux-only: they inspect /proc/self/cgroup and /sys/fs/cgroup, which
        // don't exist on Windows hosts. When the bundle is destined for the
        // WSL2 delegate, cgroup-parent resolution happens inside the distro
        // at `zlayer runtime create` time, not here on the host.
        #[cfg(target_os = "linux")]
        let auto_parent: Option<(String, &'static str)> =
            if let Some(p) = crate::capability::ensure_daemon_leaf_and_container_parent() {
                Some((p, "auto-init"))
            } else if let Some(p) = crate::capability::current_cgroup_v2_path() {
                // Fallback: migration failed (likely cgroup root is read-only); use the
                // raw scope path. Pre-fix behaviour — surfaces the original error.
                Some((p, "auto"))
            } else {
                None
            };
        #[cfg(not(target_os = "linux"))]
        let auto_parent: Option<(String, &'static str)> = None;

        let (cgroup_parent_value, cgroup_parent_source): (Option<String>, &'static str) =
            explicit_parent
                .or(auto_parent)
                .map_or((None, "none"), |(p, s)| (Some(p), s));

        // Diagnostic guard rail: capability survey says we're nested, but we
        // couldn't resolve a cgroup parent here. This combination should not
        // normally happen because both code paths consult the same
        // `current_cgroup_v2_path()` helper. Surface it so an operator can
        // investigate; do not fail container creation. Linux-only — the
        // capability survey is itself a no-op on non-Linux.
        #[cfg(target_os = "linux")]
        if cgroup_parent_value.is_none() && crate::capability::DaemonCapabilities::get().is_nested {
            tracing::warn!(
                container_id = %cid,
                "capability survey reports nested daemon but cgroup_parent could not be resolved — proceeding with v2 root"
            );
        }

        if let Some(parent) = cgroup_parent_value {
            let parent = parent.trim_end_matches('/');
            let full = format!("{parent}/{cid}");
            match cgroup_parent_source {
                "spec" => tracing::info!(
                    container_id = %cid,
                    source = "spec",
                    path = %full,
                    "cgroup_parent selected"
                ),
                "env" => tracing::info!(
                    container_id = %cid,
                    source = "env",
                    path = %full,
                    "cgroup_parent selected"
                ),
                "auto" => tracing::info!(
                    container_id = %cid,
                    source = "auto",
                    path = %full,
                    "cgroup_parent selected (from /proc/self/cgroup)"
                ),
                "auto-init" => tracing::info!(
                    container_id = %cid,
                    source = "auto-init",
                    path = %full,
                    "cgroup_parent selected (migrated daemon to <scope>/init; containers go under <scope>/containers)"
                ),
                _ => unreachable!(),
            }
            linux_builder = linux_builder.cgroups_path(std::path::PathBuf::from(full));
        } else {
            // Auto-detect found nothing AND no explicit override. Behaviour
            // differs by platform:
            //   - Linux: this is a real error in nested-container envs where
            //     the cgroup root is read-only. Emit the hard error so an
            //     operator fixes the env.
            //   - Non-Linux (Windows host building a bundle for the WSL2
            //     delegate): expected path; cgroup setup happens inside the
            //     distro at runtime-create time.
            #[cfg(target_os = "linux")]
            {
                let caps = crate::capability::DaemonCapabilities::get();
                if !caps.can_write_cgroup_root {
                    return Err(AgentError::InvalidSpec(format!(
                        "cannot create container {cid}: no writable cgroup parent. \
                         /proc/self/cgroup reports the cgroup-v2 root, and \
                         /sys/fs/cgroup is read-only to this process. Fix one of: \
                         (a) run the daemon's outer container with --cgroupns=host \
                         so /proc/self/cgroup reports a real parent; \
                         (b) set ZLAYER_CGROUP_PARENT=/path/to/writable/cgroup; \
                         (c) grant the daemon write access to /sys/fs/cgroup."
                    )));
                }
                tracing::info!(
                    container_id = %cid,
                    "cgroup_parent unset — libcontainer will use v2 root (cgroup root is writable here)"
                );
            }
            #[cfg(not(target_os = "linux"))]
            tracing::debug!(
                container_id = %cid,
                "non-Linux host — cgroup_parent unset; libcontainer inside the WSL distro will resolve a parent from its cgroup-v2 root"
            );
        }

        linux_builder
            .build()
            .map_err(|e| AgentError::InvalidSpec(format!("failed to build linux config: {e}")))
    }

    /// Build resource limits (CPU, memory, device cgroups)
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    fn build_resources(
        &self,
        spec: &ServiceSpec,
    ) -> Result<Option<oci_spec::runtime::LinuxResources>> {
        let mut resources_builder = LinuxResourcesBuilder::default();
        let mut has_resources = false;

        // CPU limits
        if let Some(cpu_limit) = spec.resources.cpu {
            // Convert CPU cores to microseconds quota
            // 100000 microseconds = 1 core's worth of time per period
            let quota = (cpu_limit * 100_000.0) as i64;
            let cpu = LinuxCpuBuilder::default()
                .quota(quota)
                .period(100_000u64)
                .build()
                .map_err(|e| AgentError::InvalidSpec(format!("failed to build CPU limits: {e}")))?;

            resources_builder = resources_builder.cpu(cpu);
            has_resources = true;
        }

        // Memory limits
        if let Some(ref memory_str) = spec.resources.memory {
            let bytes = parse_memory_string(memory_str)
                .map_err(|e| AgentError::InvalidSpec(format!("invalid memory limit: {e}")))?;

            let memory = LinuxMemoryBuilder::default()
                .limit(bytes as i64)
                .build()
                .map_err(|e| {
                    AgentError::InvalidSpec(format!("failed to build memory limits: {e}"))
                })?;

            resources_builder = resources_builder.memory(memory);
            has_resources = true;
        }

        // Device cgroup rules
        let device_rules = self.build_device_cgroup_rules(spec, None)?;
        if !device_rules.is_empty() {
            resources_builder = resources_builder.devices(device_rules);
            has_resources = true;
        }

        if has_resources {
            let resources = resources_builder
                .build()
                .map_err(|e| AgentError::InvalidSpec(format!("failed to build resources: {e}")))?;
            Ok(Some(resources))
        } else {
            Ok(None)
        }
    }

    /// Build device cgroup rules
    #[allow(clippy::unused_self, clippy::too_many_lines)]
    fn build_device_cgroup_rules(
        &self,
        spec: &ServiceSpec,
        _gpu_indices: Option<&[u32]>,
    ) -> Result<Vec<oci_spec::runtime::LinuxDeviceCgroup>> {
        let mut rules = Vec::new();

        if spec.privileged {
            // Privileged mode: allow all devices
            let rule = LinuxDeviceCgroupBuilder::default()
                .allow(true)
                .access("rwm".to_string())
                .build()
                .map_err(|e| {
                    AgentError::InvalidSpec(format!("failed to build device cgroup rule: {e}"))
                })?;
            rules.push(rule);
        } else {
            // Default: deny all, then allow specific devices
            let deny_all = LinuxDeviceCgroupBuilder::default()
                .allow(false)
                .access("rwm".to_string())
                .build()
                .map_err(|e| AgentError::InvalidSpec(format!("failed to build deny rule: {e}")))?;
            rules.push(deny_all);

            // Allow standard container devices
            // /dev/null, /dev/zero, /dev/full, /dev/random, /dev/urandom, /dev/tty
            let standard_char_devices = [
                (1, 3, "rwm"),    // /dev/null
                (1, 5, "rwm"),    // /dev/zero
                (1, 7, "rwm"),    // /dev/full
                (1, 8, "rwm"),    // /dev/random
                (1, 9, "rwm"),    // /dev/urandom
                (5, 0, "rwm"),    // /dev/tty
                (5, 1, "rwm"),    // /dev/console
                (5, 2, "rwm"),    // /dev/ptmx
                (136, -1, "rwm"), // /dev/pts/* (wildcard minor)
            ];

            for (major, minor, access) in standard_char_devices {
                let mut builder = LinuxDeviceCgroupBuilder::default()
                    .allow(true)
                    .typ(LinuxDeviceType::C)
                    .major(i64::from(major))
                    .access(access.to_string());

                if minor >= 0 {
                    builder = builder.minor(i64::from(minor));
                }

                let rule = builder.build().map_err(|e| {
                    AgentError::InvalidSpec(format!("failed to build char device rule: {e}"))
                })?;
                rules.push(rule);
            }

            // Allow specific devices from spec (Unix-only: requires /dev/* fs
            // probing via `MetadataExt::rdev`). On Windows the WSL2 delegate
            // path regenerates these inside the Linux distro, so we skip here.
            #[cfg(unix)]
            for device in &spec.devices {
                if let Ok((major, minor)) = get_device_major_minor(&device.path) {
                    let dev_type = get_device_type(&device.path).unwrap_or(LinuxDeviceType::C);

                    // Build access string
                    let mut access = String::new();
                    if device.read {
                        access.push('r');
                    }
                    if device.write {
                        access.push('w');
                    }
                    if device.mknod {
                        access.push('m');
                    }
                    if access.is_empty() {
                        access = "rw".to_string();
                    }

                    let rule = LinuxDeviceCgroupBuilder::default()
                        .allow(true)
                        .typ(dev_type)
                        .major(major)
                        .minor(minor)
                        .access(access)
                        .build()
                        .map_err(|e| {
                            AgentError::InvalidSpec(format!(
                                "failed to build device rule for {}: {}",
                                device.path, e
                            ))
                        })?;
                    rules.push(rule);
                } else {
                    tracing::warn!("Failed to get device info for {}, skipping", device.path);
                }
            }

            // Auto-allow GPU devices in cgroup when gpu spec is set
            if let Some(ref gpu) = spec.resources.gpu {
                match gpu.vendor.as_str() {
                    "nvidia" => {
                        // Allow all nvidia devices (major 195 for nvidia GPUs)
                        let rule = LinuxDeviceCgroupBuilder::default()
                            .allow(true)
                            .typ(LinuxDeviceType::C)
                            .major(195i64)
                            .access("rwm".to_string())
                            .build()
                            .map_err(|e| {
                                AgentError::InvalidSpec(format!(
                                    "failed to build GPU cgroup rule: {e}"
                                ))
                            })?;
                        rules.push(rule);

                        // nvidia-uvm (major 510 or check dynamically)
                        let uvm_rule = LinuxDeviceCgroupBuilder::default()
                            .allow(true)
                            .typ(LinuxDeviceType::C)
                            .major(510i64)
                            .access("rwm".to_string())
                            .build()
                            .map_err(|e| {
                                AgentError::InvalidSpec(format!(
                                    "failed to build GPU UVM cgroup rule: {e}"
                                ))
                            })?;
                        rules.push(uvm_rule);
                    }
                    "amd" => {
                        // AMD ROCm: /dev/dri/renderD* and /dev/dri/card* (major 226)
                        let dri_rule = LinuxDeviceCgroupBuilder::default()
                            .allow(true)
                            .typ(LinuxDeviceType::C)
                            .major(226i64)
                            .access("rwm".to_string())
                            .build()
                            .map_err(|e| {
                                AgentError::InvalidSpec(format!(
                                    "failed to build AMD DRI cgroup rule: {e}"
                                ))
                            })?;
                        rules.push(dri_rule);

                        // /dev/kfd - AMD Kernel Fusion Driver for compute (major 234)
                        let kfd_rule = LinuxDeviceCgroupBuilder::default()
                            .allow(true)
                            .typ(LinuxDeviceType::C)
                            .major(234i64)
                            .access("rwm".to_string())
                            .build()
                            .map_err(|e| {
                                AgentError::InvalidSpec(format!(
                                    "failed to build AMD KFD cgroup rule: {e}"
                                ))
                            })?;
                        rules.push(kfd_rule);
                    }
                    "intel" => {
                        // Intel GPU: /dev/dri/renderD* and /dev/dri/card* (major 226)
                        let dri_rule = LinuxDeviceCgroupBuilder::default()
                            .allow(true)
                            .typ(LinuxDeviceType::C)
                            .major(226i64)
                            .access("rwm".to_string())
                            .build()
                            .map_err(|e| {
                                AgentError::InvalidSpec(format!(
                                    "failed to build Intel DRI cgroup rule: {e}"
                                ))
                            })?;
                        rules.push(dri_rule);
                    }
                    other => {
                        // Unknown vendor - allow DRI devices as a reasonable default
                        tracing::warn!(
                            vendor = %other,
                            "Unknown GPU vendor, allowing DRI devices (major 226)"
                        );
                        let dri_rule = LinuxDeviceCgroupBuilder::default()
                            .allow(true)
                            .typ(LinuxDeviceType::C)
                            .major(226i64)
                            .access("rwm".to_string())
                            .build()
                            .map_err(|e| {
                                AgentError::InvalidSpec(format!(
                                    "failed to build GPU DRI cgroup rule: {e}"
                                ))
                            })?;
                        rules.push(dri_rule);
                    }
                }
            }
        }

        Ok(rules)
    }

    /// Build Linux device entries for passthrough
    ///
    /// # Platform
    /// Every branch below walks `/dev/*` on the host to resolve major/minor
    /// numbers via `MetadataExt::rdev`. On Windows (where this module is
    /// compiled only to feed the WSL2 delegate's cross-platform spec path) we
    /// skip device discovery and return an empty list — the Linux side of the
    /// delegate re-runs this step inside the WSL2 distro.
    #[allow(clippy::unused_self, clippy::too_many_lines)]
    #[cfg_attr(not(unix), allow(clippy::unnecessary_wraps, clippy::needless_return))]
    fn build_devices(
        &self,
        spec: &ServiceSpec,
        gpu_indices: Option<&[u32]>,
        skip_gpu_defaults: bool,
    ) -> Result<Vec<oci_spec::runtime::LinuxDevice>> {
        #[cfg(not(unix))]
        {
            let _ = (spec, gpu_indices, skip_gpu_defaults);
            return Ok(Vec::new());
        }

        #[cfg(unix)]
        {
            let mut devices = Vec::new();

            for device in &spec.devices {
                if let Ok((major, minor)) = get_device_major_minor(&device.path) {
                    let dev_type = get_device_type(&device.path).unwrap_or(LinuxDeviceType::C);

                    let linux_device = LinuxDeviceBuilder::default()
                        .path(device.path.clone())
                        .typ(dev_type)
                        .major(major)
                        .minor(minor)
                        .file_mode(0o666u32)
                        .uid(0u32)
                        .gid(0u32)
                        .build()
                        .map_err(|e| {
                            AgentError::InvalidSpec(format!(
                                "failed to build device {}: {}",
                                device.path, e
                            ))
                        })?;

                    devices.push(linux_device);
                }
            }

            // When CDI is providing GPU device descriptors the caller will
            // append the vendor-supplied entries; skip our hard-coded
            // `/dev/nvidiaN` enumeration so we don't end up with both sources
            // of truth.
            if skip_gpu_defaults {
                return Ok(devices);
            }

            // Auto-inject GPU devices when gpu spec is set
            if let Some(ref gpu) = spec.resources.gpu {
                let indices: Vec<u32> =
                    gpu_indices.map_or_else(|| (0..gpu.count).collect(), <[u32]>::to_vec);

                match gpu.vendor.as_str() {
                    "nvidia" => {
                        // Always needed: nvidiactl, nvidia-uvm, nvidia-uvm-tools
                        let always_devices =
                            ["/dev/nvidiactl", "/dev/nvidia-uvm", "/dev/nvidia-uvm-tools"];
                        for dev_path in &always_devices {
                            if let Ok((major, minor)) = get_device_major_minor(dev_path) {
                                let dev_type =
                                    get_device_type(dev_path).unwrap_or(LinuxDeviceType::C);
                                let linux_device = LinuxDeviceBuilder::default()
                                    .path((*dev_path).to_string())
                                    .typ(dev_type)
                                    .major(major)
                                    .minor(minor)
                                    .file_mode(0o666u32)
                                    .uid(0u32)
                                    .gid(0u32)
                                    .build()
                                    .map_err(|e| {
                                        AgentError::InvalidSpec(format!(
                                            "failed to build GPU device {dev_path}: {e}"
                                        ))
                                    })?;
                                devices.push(linux_device);
                            } else {
                                tracing::warn!(
                                    "GPU device {} not found on host, skipping",
                                    dev_path
                                );
                            }
                        }

                        // Per-GPU devices: /dev/nvidia0, /dev/nvidia1, etc.
                        for i in &indices {
                            let dev_path = format!("/dev/nvidia{i}");
                            if let Ok((major, minor)) = get_device_major_minor(&dev_path) {
                                let dev_type =
                                    get_device_type(&dev_path).unwrap_or(LinuxDeviceType::C);
                                let linux_device = LinuxDeviceBuilder::default()
                                    .path(dev_path.clone())
                                    .typ(dev_type)
                                    .major(major)
                                    .minor(minor)
                                    .file_mode(0o666u32)
                                    .uid(0u32)
                                    .gid(0u32)
                                    .build()
                                    .map_err(|e| {
                                        AgentError::InvalidSpec(format!(
                                            "failed to build GPU device {dev_path}: {e}"
                                        ))
                                    })?;
                                devices.push(linux_device);
                            } else {
                                tracing::warn!(
                                    "GPU device {} not found on host, skipping",
                                    dev_path
                                );
                            }
                        }
                    }
                    "amd" => {
                        // AMD ROCm: /dev/kfd is always required for compute
                        let amd_always_devices = ["/dev/kfd"];
                        for dev_path in &amd_always_devices {
                            if let Ok((major, minor)) = get_device_major_minor(dev_path) {
                                let dev_type =
                                    get_device_type(dev_path).unwrap_or(LinuxDeviceType::C);
                                let linux_device = LinuxDeviceBuilder::default()
                                    .path((*dev_path).to_string())
                                    .typ(dev_type)
                                    .major(major)
                                    .minor(minor)
                                    .file_mode(0o666u32)
                                    .uid(0u32)
                                    .gid(0u32)
                                    .build()
                                    .map_err(|e| {
                                        AgentError::InvalidSpec(format!(
                                            "failed to build GPU device {dev_path}: {e}"
                                        ))
                                    })?;
                                devices.push(linux_device);
                            } else {
                                tracing::warn!(
                                    "GPU device {} not found on host, skipping",
                                    dev_path
                                );
                            }
                        }

                        // DRI render nodes: /dev/dri/renderD128, renderD129, etc.
                        for i in &indices {
                            let dev_path = format!("/dev/dri/renderD{}", 128 + i);
                            if let Ok((major, minor)) = get_device_major_minor(&dev_path) {
                                let dev_type =
                                    get_device_type(&dev_path).unwrap_or(LinuxDeviceType::C);
                                let linux_device = LinuxDeviceBuilder::default()
                                    .path(dev_path.clone())
                                    .typ(dev_type)
                                    .major(major)
                                    .minor(minor)
                                    .file_mode(0o666u32)
                                    .uid(0u32)
                                    .gid(0u32)
                                    .build()
                                    .map_err(|e| {
                                        AgentError::InvalidSpec(format!(
                                            "failed to build GPU device {dev_path}: {e}"
                                        ))
                                    })?;
                                devices.push(linux_device);
                            } else {
                                tracing::warn!(
                                    "GPU device {} not found on host, skipping",
                                    dev_path
                                );
                            }
                        }

                        // DRI card nodes: /dev/dri/card0, card1, etc.
                        for i in &indices {
                            let dev_path = format!("/dev/dri/card{i}");
                            if let Ok((major, minor)) = get_device_major_minor(&dev_path) {
                                let dev_type =
                                    get_device_type(&dev_path).unwrap_or(LinuxDeviceType::C);
                                let linux_device = LinuxDeviceBuilder::default()
                                    .path(dev_path.clone())
                                    .typ(dev_type)
                                    .major(major)
                                    .minor(minor)
                                    .file_mode(0o666u32)
                                    .uid(0u32)
                                    .gid(0u32)
                                    .build()
                                    .map_err(|e| {
                                        AgentError::InvalidSpec(format!(
                                            "failed to build GPU device {dev_path}: {e}"
                                        ))
                                    })?;
                                devices.push(linux_device);
                            } else {
                                tracing::warn!(
                                    "GPU device {} not found on host, skipping",
                                    dev_path
                                );
                            }
                        }
                    }
                    "intel" => {
                        // Intel GPU: DRI render nodes /dev/dri/renderD128, etc.
                        for i in &indices {
                            let dev_path = format!("/dev/dri/renderD{}", 128 + i);
                            if let Ok((major, minor)) = get_device_major_minor(&dev_path) {
                                let dev_type =
                                    get_device_type(&dev_path).unwrap_or(LinuxDeviceType::C);
                                let linux_device = LinuxDeviceBuilder::default()
                                    .path(dev_path.clone())
                                    .typ(dev_type)
                                    .major(major)
                                    .minor(minor)
                                    .file_mode(0o666u32)
                                    .uid(0u32)
                                    .gid(0u32)
                                    .build()
                                    .map_err(|e| {
                                        AgentError::InvalidSpec(format!(
                                            "failed to build GPU device {dev_path}: {e}"
                                        ))
                                    })?;
                                devices.push(linux_device);
                            } else {
                                tracing::warn!(
                                    "GPU device {} not found on host, skipping",
                                    dev_path
                                );
                            }
                        }

                        // Intel DRI card nodes: /dev/dri/card0, card1, etc.
                        for i in &indices {
                            let dev_path = format!("/dev/dri/card{i}");
                            if let Ok((major, minor)) = get_device_major_minor(&dev_path) {
                                let dev_type =
                                    get_device_type(&dev_path).unwrap_or(LinuxDeviceType::C);
                                let linux_device = LinuxDeviceBuilder::default()
                                    .path(dev_path.clone())
                                    .typ(dev_type)
                                    .major(major)
                                    .minor(minor)
                                    .file_mode(0o666u32)
                                    .uid(0u32)
                                    .gid(0u32)
                                    .build()
                                    .map_err(|e| {
                                        AgentError::InvalidSpec(format!(
                                            "failed to build GPU device {dev_path}: {e}"
                                        ))
                                    })?;
                                devices.push(linux_device);
                            } else {
                                tracing::warn!(
                                    "GPU device {} not found on host, skipping",
                                    dev_path
                                );
                            }
                        }
                    }
                    other => {
                        // Unknown vendor - try DRI render nodes as default
                        tracing::warn!(
                            vendor = %other,
                            "Unknown GPU vendor, attempting DRI device passthrough"
                        );
                        for i in &indices {
                            let dev_path = format!("/dev/dri/renderD{}", 128 + i);
                            if let Ok((major, minor)) = get_device_major_minor(&dev_path) {
                                let dev_type =
                                    get_device_type(&dev_path).unwrap_or(LinuxDeviceType::C);
                                let linux_device = LinuxDeviceBuilder::default()
                                    .path(dev_path.clone())
                                    .typ(dev_type)
                                    .major(major)
                                    .minor(minor)
                                    .file_mode(0o666u32)
                                    .uid(0u32)
                                    .gid(0u32)
                                    .build()
                                    .map_err(|e| {
                                        AgentError::InvalidSpec(format!(
                                            "failed to build GPU device {dev_path}: {e}"
                                        ))
                                    })?;
                                devices.push(linux_device);
                            } else {
                                tracing::warn!(
                                    "GPU device {} not found on host, skipping",
                                    dev_path
                                );
                            }
                        }
                    }
                }
            }

            Ok(devices)
        } // end #[cfg(unix)]
    }

    /// Generate the OCI spec and write config.json to the bundle directory
    ///
    /// Unlike `build()`, this does NOT create the bundle directory or set up rootfs.
    /// Use this when the bundle directory and rootfs already exist (e.g., rootfs was
    /// extracted directly by `LayerUnpacker`).
    ///
    /// # Errors
    /// Returns an error if the OCI spec cannot be built or config.json cannot be written.
    ///
    /// # Returns
    /// The path to the bundle directory on success
    pub async fn write_config(
        &self,
        container_id: &ContainerId,
        spec: &ServiceSpec,
    ) -> Result<PathBuf> {
        // Generate OCI runtime spec
        let oci_spec = self
            .build_spec_only(container_id, spec, &self.volume_paths)
            .await?;

        // Write config.json
        let config_path = self.bundle_dir.join("config.json");
        let config_json =
            serde_json::to_string_pretty(&oci_spec).map_err(|e| AgentError::CreateFailed {
                id: container_id.to_string(),
                reason: format!("failed to serialize OCI spec: {e}"),
            })?;

        fs::write(&config_path, config_json)
            .await
            .map_err(|e| AgentError::CreateFailed {
                id: container_id.to_string(),
                reason: format!("failed to write config.json: {e}"),
            })?;

        tracing::debug!(
            "Wrote OCI config.json at {} for container {}",
            config_path.display(),
            container_id
        );

        Ok(self.bundle_dir.clone())
    }

    /// Resolve command from `ServiceSpec` and optional image config following Docker/OCI semantics
    ///
    /// Resolution order:
    /// 1. spec entrypoint + args -> use those
    /// 2. spec entrypoint only -> use entrypoint
    /// 3. spec args only -> use args
    /// 4. `image_config` entrypoint/cmd -> use `image_config.full_command()`
    /// 5. fallback to /bin/sh
    fn resolve_command_from_spec(
        spec: &ServiceSpec,
        image_config: Option<&zlayer_registry::ImageConfig>,
    ) -> Vec<String> {
        let mut args = Vec::new();

        match (&spec.command.entrypoint, &spec.command.args) {
            (Some(entrypoint), Some(cmd_args)) => {
                args.extend_from_slice(entrypoint);
                args.extend_from_slice(cmd_args);
            }
            (Some(entrypoint), None) => {
                args.extend_from_slice(entrypoint);
            }
            (None, Some(cmd_args)) if !cmd_args.is_empty() => {
                args.extend_from_slice(cmd_args);
            }
            _ => {
                // No spec command - try image config
                if let Some(img_cmd) =
                    image_config.and_then(zlayer_registry::ImageConfig::full_command)
                {
                    if img_cmd.is_empty() {
                        args.push("/bin/sh".to_string());
                    } else {
                        args.extend(img_cmd);
                    }
                } else {
                    args.push("/bin/sh".to_string());
                }
            }
        }

        args
    }

    /// Clean up a bundle directory
    ///
    /// Removes the bundle directory and all its contents.
    ///
    /// # Errors
    /// Returns an error if the bundle directory cannot be removed.
    pub async fn cleanup(&self) -> Result<()> {
        if self.bundle_dir.exists() {
            fs::remove_dir_all(&self.bundle_dir)
                .await
                .map_err(|e| AgentError::CreateFailed {
                    id: "cleanup".to_string(),
                    reason: format!(
                        "failed to remove bundle directory {}: {}",
                        self.bundle_dir.display(),
                        e
                    ),
                })?;
        }
        Ok(())
    }
}

/// Create a bundle for a container
///
/// Convenience function that creates a bundle in the default location.
///
/// # Errors
/// Returns an error if bundle creation fails.
///
/// # Platform
/// Unix-only — wraps [`BundleBuilder::build`], which uses
/// `tokio::fs::symlink` (not available on Windows). Windows callers should
/// use [`BundleBuilder::build_spec_only`] directly and pipe the result into
/// a WSL2 delegate.
#[cfg(unix)]
pub async fn create_bundle(
    container_id: &ContainerId,
    spec: &ServiceSpec,
    rootfs_path: Option<PathBuf>,
) -> Result<PathBuf> {
    let mut builder =
        BundleBuilder::for_container(container_id).with_host_network(spec.host_network);

    if let Some(rootfs) = rootfs_path {
        builder = builder.with_rootfs(rootfs);
    }

    builder.build(container_id, spec).await
}

/// Clean up a container's bundle
///
/// Convenience function to remove a bundle from the default location.
///
/// # Errors
/// Returns an error if cleanup fails.
pub async fn cleanup_bundle(container_id: &ContainerId) -> Result<()> {
    let builder = BundleBuilder::for_container(container_id);
    builder.cleanup().await
}

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

    fn mock_spec() -> ServiceSpec {
        serde_yaml::from_str::<DeploymentSpec>(
            r"
version: v1
deployment: test
services:
  test:
    rtype: service
    image:
      name: test:latest
    endpoints:
      - name: http
        protocol: http
        port: 8080
",
        )
        .unwrap()
        .services
        .remove("test")
        .unwrap()
    }

    #[cfg(target_os = "linux")]
    fn mock_spec_with_resources() -> ServiceSpec {
        serde_yaml::from_str::<DeploymentSpec>(
            r"
version: v1
deployment: test
services:
  test:
    rtype: service
    image:
      name: test:latest
    resources:
      cpu: 0.5
      memory: 512Mi
    env:
      MY_VAR: my_value
      ANOTHER: value2
    endpoints:
      - name: http
        protocol: http
        port: 8080
",
        )
        .unwrap()
        .services
        .remove("test")
        .unwrap()
    }

    #[cfg(target_os = "linux")]
    fn mock_privileged_spec() -> ServiceSpec {
        serde_yaml::from_str::<DeploymentSpec>(
            r"
version: v1
deployment: test
services:
  test:
    rtype: service
    image:
      name: test:latest
    privileged: true
    endpoints:
      - name: http
        protocol: http
        port: 8080
",
        )
        .unwrap()
        .services
        .remove("test")
        .unwrap()
    }

    #[test]
    fn test_parse_memory_string() {
        assert_eq!(parse_memory_string("512Mi").unwrap(), 512 * 1024 * 1024);
        assert_eq!(parse_memory_string("1Gi").unwrap(), 1024 * 1024 * 1024);
        assert_eq!(parse_memory_string("2G").unwrap(), 2 * 1000 * 1000 * 1000);
        assert_eq!(parse_memory_string("1024").unwrap(), 1024);
        assert_eq!(parse_memory_string("512Ki").unwrap(), 512 * 1024);
    }

    #[test]
    fn test_parse_memory_string_errors() {
        assert!(parse_memory_string("").is_err());
        assert!(parse_memory_string("abc").is_err());
        assert!(parse_memory_string("12.5Mi").is_err());
    }

    #[test]
    fn test_bundle_builder_new() {
        let builder = BundleBuilder::new("/tmp/test-bundle".into());
        assert_eq!(builder.bundle_dir(), Path::new("/tmp/test-bundle"));
        assert!(builder.rootfs_path.is_none());
    }

    #[test]
    fn test_bundle_builder_for_container() {
        let dirs = zlayer_paths::ZLayerDirs::system_default();
        let id = ContainerId::new("myservice".to_string(), 1);
        let builder = BundleBuilder::for_container(&id);
        assert_eq!(builder.bundle_dir(), dirs.bundles().join("myservice-rep-1"));
    }

    #[test]
    fn test_bundle_builder_with_rootfs() {
        let dirs = zlayer_paths::ZLayerDirs::system_default();
        let builder = BundleBuilder::new("/tmp/test-bundle".into())
            .with_rootfs(dirs.rootfs().join("myimage"));
        assert_eq!(builder.rootfs_path, Some(dirs.rootfs().join("myimage")));
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn test_build_oci_spec_basic() {
        let id = ContainerId::new("test".to_string(), 1);
        let spec = mock_spec();
        let builder = BundleBuilder::new("/tmp/test-bundle".into());

        let oci_spec = builder
            .build_spec_only(&id, &spec, &std::collections::HashMap::new())
            .await
            .unwrap();

        assert_eq!(oci_spec.version(), "1.0.2");
        assert!(oci_spec.root().is_some());
        assert_eq!(
            oci_spec.root().as_ref().unwrap().path(),
            std::path::Path::new("rootfs")
        );
        assert!(oci_spec.process().is_some());
        assert!(oci_spec.linux().is_some());
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn test_build_oci_spec_with_resources() {
        let id = ContainerId::new("test".to_string(), 1);
        let spec = mock_spec_with_resources();
        let builder = BundleBuilder::new("/tmp/test-bundle".into());

        let oci_spec = builder
            .build_spec_only(&id, &spec, &std::collections::HashMap::new())
            .await
            .unwrap();

        // Check that resources are set
        let linux = oci_spec.linux().as_ref().unwrap();
        let resources = linux.resources().as_ref().unwrap();

        // Check CPU
        let cpu = resources.cpu().as_ref().unwrap();
        assert_eq!(cpu.quota(), Some(50_000)); // 0.5 cores * 100000
        assert_eq!(cpu.period(), Some(100_000));

        // Check memory
        let memory = resources.memory().as_ref().unwrap();
        assert_eq!(memory.limit(), Some(512 * 1024 * 1024)); // 512Mi
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn test_build_oci_spec_privileged() {
        let id = ContainerId::new("test".to_string(), 1);
        let spec = mock_privileged_spec();
        let builder = BundleBuilder::new("/tmp/test-bundle".into());

        let oci_spec = builder
            .build_spec_only(&id, &spec, &std::collections::HashMap::new())
            .await
            .unwrap();

        // Check that all capabilities are set
        let process = oci_spec.process().as_ref().unwrap();
        let caps = process.capabilities().as_ref().unwrap();
        let bounding = caps.bounding().as_ref().unwrap();

        // Should have all capabilities
        assert!(bounding.contains(&Capability::SysAdmin));
        assert!(bounding.contains(&Capability::NetAdmin));

        // Check that masked paths are NOT set for privileged
        let linux = oci_spec.linux().as_ref().unwrap();
        assert!(
            linux.masked_paths().is_none() || linux.masked_paths().as_ref().unwrap().is_empty()
        );
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn test_build_oci_spec_environment() {
        let id = ContainerId::new("test".to_string(), 1);
        let spec = mock_spec_with_resources();
        let builder = BundleBuilder::new("/tmp/test-bundle".into())
            .with_env("EXTRA_VAR".to_string(), "extra_value".to_string());

        let oci_spec = builder
            .build_spec_only(&id, &spec, &std::collections::HashMap::new())
            .await
            .unwrap();

        let process = oci_spec.process().as_ref().unwrap();
        let env = process.env().as_ref().unwrap();

        // Check service env vars are present
        assert!(env.iter().any(|e| e == "MY_VAR=my_value"));
        assert!(env.iter().any(|e| e == "ANOTHER=value2"));
        // Check extra env var is present
        assert!(env.iter().any(|e| e == "EXTRA_VAR=extra_value"));
        // Check PATH is present
        assert!(env.iter().any(|e| e.starts_with("PATH=")));
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn test_build_namespaces() {
        let id = ContainerId::new("test".to_string(), 1);
        let spec = mock_spec();
        let builder = BundleBuilder::new("/tmp/test-bundle".into());

        let oci_spec = builder
            .build_spec_only(&id, &spec, &std::collections::HashMap::new())
            .await
            .unwrap();
        let linux = oci_spec.linux().as_ref().unwrap();
        let namespaces = linux.namespaces().as_ref().unwrap();

        // Check we have the expected namespaces
        let namespace_types: Vec<_> = namespaces
            .iter()
            .map(oci_spec::runtime::LinuxNamespace::typ)
            .collect();
        assert!(namespace_types.contains(&LinuxNamespaceType::Pid));
        assert!(namespace_types.contains(&LinuxNamespaceType::Ipc));
        assert!(namespace_types.contains(&LinuxNamespaceType::Uts));
        assert!(namespace_types.contains(&LinuxNamespaceType::Mount));
        assert!(namespace_types.contains(&LinuxNamespaceType::Network));
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn test_build_namespaces_host_network() {
        let id = ContainerId::new("test".to_string(), 1);
        let spec = mock_spec();
        let builder = BundleBuilder::new("/tmp/test-bundle".into()).with_host_network(true);

        let oci_spec = builder
            .build_spec_only(&id, &spec, &std::collections::HashMap::new())
            .await
            .unwrap();
        let linux = oci_spec.linux().as_ref().unwrap();
        let namespaces = linux.namespaces().as_ref().unwrap();

        // Check we have the expected namespaces (NO Network namespace)
        let namespace_types: Vec<_> = namespaces
            .iter()
            .map(oci_spec::runtime::LinuxNamespace::typ)
            .collect();
        assert!(namespace_types.contains(&LinuxNamespaceType::Pid));
        assert!(namespace_types.contains(&LinuxNamespaceType::Ipc));
        assert!(namespace_types.contains(&LinuxNamespaceType::Uts));
        assert!(namespace_types.contains(&LinuxNamespaceType::Mount));
        assert!(
            !namespace_types.contains(&LinuxNamespaceType::Network),
            "Network namespace should NOT be present in host_network mode"
        );
    }

    #[test]
    fn test_build_default_mounts() {
        let spec = mock_spec();
        let builder = BundleBuilder::new("/tmp/test-bundle".into());

        let mounts = builder.build_default_mounts(&spec).unwrap();

        // Check we have the expected mounts
        let mount_destinations: Vec<_> = mounts
            .iter()
            .map(|m| m.destination().to_string_lossy().to_string())
            .collect();
        assert!(mount_destinations.contains(&"/proc".to_string()));
        assert!(mount_destinations.contains(&"/dev".to_string()));
        assert!(mount_destinations.contains(&"/dev/pts".to_string()));
        assert!(mount_destinations.contains(&"/dev/shm".to_string()));
        assert!(mount_destinations.contains(&"/sys".to_string()));
    }

    #[test]
    fn test_build_storage_mounts_bind() {
        let spec = serde_yaml::from_str::<zlayer_spec::DeploymentSpec>(
            r"
version: v1
deployment: test
services:
  test:
    image:
      name: test:latest
    storage:
      - type: bind
        source: /host/data
        target: /app/data
        readonly: true
",
        )
        .unwrap()
        .services
        .remove("test")
        .unwrap();

        let builder = BundleBuilder::new("/tmp/test-bundle".into());
        let volume_paths = std::collections::HashMap::new();

        let mounts = builder.build_storage_mounts(&spec, &volume_paths).unwrap();

        assert_eq!(mounts.len(), 1);
        assert_eq!(mounts[0].destination().to_string_lossy(), "/app/data");
        assert_eq!(
            mounts[0]
                .source()
                .as_ref()
                .map(|s| s.to_string_lossy().to_string()),
            Some("/host/data".to_string())
        );
        let options = mounts[0].options().as_ref().unwrap();
        assert!(options.contains(&"rbind".to_string()));
        assert!(options.contains(&"ro".to_string()));
    }

    #[test]
    fn test_build_storage_mounts_named() {
        let spec = serde_yaml::from_str::<zlayer_spec::DeploymentSpec>(
            r"
version: v1
deployment: test
services:
  test:
    image:
      name: test:latest
    storage:
      - type: named
        name: my-volume
        target: /app/data
",
        )
        .unwrap()
        .services
        .remove("test")
        .unwrap();

        let dirs = zlayer_paths::ZLayerDirs::system_default();
        let builder = BundleBuilder::new("/tmp/test-bundle".into());
        let mut volume_paths = std::collections::HashMap::new();
        volume_paths.insert("my-volume".to_string(), dirs.volumes().join("my-volume"));

        let mounts = builder.build_storage_mounts(&spec, &volume_paths).unwrap();

        assert_eq!(mounts.len(), 1);
        assert_eq!(mounts[0].destination().to_string_lossy(), "/app/data");
        assert_eq!(
            mounts[0]
                .source()
                .as_ref()
                .map(|s| s.to_string_lossy().to_string()),
            Some(
                dirs.volumes()
                    .join("my-volume")
                    .to_string_lossy()
                    .into_owned()
            )
        );
    }

    #[test]
    fn test_build_storage_mounts_tmpfs() {
        let spec = serde_yaml::from_str::<zlayer_spec::DeploymentSpec>(
            r"
version: v1
deployment: test
services:
  test:
    image:
      name: test:latest
    storage:
      - type: tmpfs
        target: /app/tmp
        size: 256Mi
        mode: 1777
",
        )
        .unwrap()
        .services
        .remove("test")
        .unwrap();

        let builder = BundleBuilder::new("/tmp/test-bundle".into());
        let volume_paths = std::collections::HashMap::new();

        let mounts = builder.build_storage_mounts(&spec, &volume_paths).unwrap();

        assert_eq!(mounts.len(), 1);
        assert_eq!(mounts[0].destination().to_string_lossy(), "/app/tmp");
        assert_eq!(mounts[0].typ().as_ref().map(String::as_str), Some("tmpfs"));
        let options = mounts[0].options().as_ref().unwrap();
        assert!(options.iter().any(|o| o.starts_with("size=")));
        assert!(options.iter().any(|o| o.starts_with("mode=")));
    }

    #[test]
    fn test_build_storage_mounts_multiple() {
        let spec = serde_yaml::from_str::<zlayer_spec::DeploymentSpec>(
            r"
version: v1
deployment: test
services:
  test:
    image:
      name: test: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
",
        )
        .unwrap()
        .services
        .remove("test")
        .unwrap();

        let dirs = zlayer_paths::ZLayerDirs::system_default();
        let builder = BundleBuilder::new("/tmp/test-bundle".into());
        let mut volume_paths = std::collections::HashMap::new();
        volume_paths.insert("app-data".to_string(), dirs.volumes().join("app-data"));

        let mounts = builder.build_storage_mounts(&spec, &volume_paths).unwrap();

        assert_eq!(mounts.len(), 3);

        // Verify each mount is correct type
        let destinations: Vec<String> = mounts
            .iter()
            .map(|m| m.destination().to_string_lossy().to_string())
            .collect();
        assert!(destinations.contains(&"/app/config".to_string()));
        assert!(destinations.contains(&"/app/data".to_string()));
        assert!(destinations.contains(&"/app/tmp".to_string()));
    }

    #[test]
    fn test_build_storage_mounts_anonymous_missing_path() {
        let spec = serde_yaml::from_str::<zlayer_spec::DeploymentSpec>(
            r"
version: v1
deployment: test
services:
  test:
    image:
      name: test:latest
    storage:
      - type: anonymous
        target: /app/cache
",
        )
        .unwrap()
        .services
        .remove("test")
        .unwrap();

        let builder = BundleBuilder::new("/tmp/test-bundle".into());
        let volume_paths = std::collections::HashMap::new(); // No path provided

        let result = builder.build_storage_mounts(&spec, &volume_paths);

        // Should fail because anonymous volume path not prepared
        assert!(result.is_err());
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn test_oci_spec_includes_storage_mounts() {
        let id = ContainerId::new("test".to_string(), 1);
        let spec = serde_yaml::from_str::<zlayer_spec::DeploymentSpec>(
            r"
version: v1
deployment: test
services:
  test:
    image:
      name: test:latest
    storage:
      - type: bind
        source: /host/data
        target: /app/data
      - type: tmpfs
        target: /app/tmp
",
        )
        .unwrap()
        .services
        .remove("test")
        .unwrap();

        let builder = BundleBuilder::new("/tmp/test-bundle".into());
        let volume_paths = std::collections::HashMap::new();

        let oci_spec = builder
            .build_spec_only(&id, &spec, &volume_paths)
            .await
            .unwrap();

        // Verify the OCI spec includes storage mounts
        let mounts = oci_spec.mounts().as_ref().unwrap();
        let destinations: Vec<String> = mounts
            .iter()
            .map(|m| m.destination().to_string_lossy().to_string())
            .collect();

        // Should include both default mounts and storage mounts
        assert!(destinations.contains(&"/proc".to_string())); // default
        assert!(destinations.contains(&"/dev".to_string())); // default
        assert!(destinations.contains(&"/app/data".to_string())); // storage bind
        assert!(destinations.contains(&"/app/tmp".to_string())); // storage tmpfs
    }

    fn mock_gpu_spec(vendor: &str, count: u32) -> ServiceSpec {
        let yaml = format!(
            "
version: v1
deployment: test
services:
  test:
    rtype: service
    image:
      name: test:latest
    resources:
      gpu:
        count: {count}
        vendor: {vendor}
    endpoints:
      - name: http
        protocol: http
        port: 8080
"
        );
        serde_yaml::from_str::<DeploymentSpec>(&yaml)
            .unwrap()
            .services
            .remove("test")
            .unwrap()
    }

    fn write_nvidia_cdi_fixture(dir: &std::path::Path, json: &str) {
        std::fs::write(dir.join("nvidia.json"), json).unwrap();
    }

    fn nvidia_cdi_fixture() -> &'static str {
        r#"{
            "cdiVersion": "0.6.0",
            "kind": "nvidia.com/gpu",
            "devices": [{
                "name": "0",
                "containerEdits": {
                    "deviceNodes": [
                        {"path": "/dev/nvidia0", "type": "c", "major": 195, "minor": 0}
                    ],
                    "env": ["NVIDIA_VISIBLE_DEVICES=0"],
                    "hooks": {
                        "createContainer": [{
                            "path": "/usr/bin/nvidia-container-runtime-hook",
                            "args": ["nvidia-container-runtime-hook", "prestart"]
                        }]
                    }
                }
            }]
        }"#
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn gpu_spec_translates_to_cdi_device_nodes() {
        let dir = tempfile::tempdir().unwrap();
        write_nvidia_cdi_fixture(dir.path(), nvidia_cdi_fixture());
        let registry = std::sync::Arc::new(crate::cdi::CdiRegistry::discover_from(&[dir.path()]));

        let id = ContainerId::new("test".to_string(), 1);
        let spec = mock_gpu_spec("nvidia", 1);
        let builder = BundleBuilder::new("/tmp/test-bundle-cdi".into()).with_cdi_registry(registry);

        let oci_spec = builder
            .build_oci_spec(&id, &spec, &std::collections::HashMap::new())
            .await
            .expect("build with CDI fixture");

        // CDI device node merged into linux.devices
        let linux = oci_spec.linux().as_ref().expect("linux config present");
        let devices = linux.devices().as_ref().expect("devices present");
        assert!(
            devices
                .iter()
                .any(|d| d.path() == std::path::Path::new("/dev/nvidia0")),
            "expected /dev/nvidia0 from CDI fixture; got {:?}",
            devices
                .iter()
                .map(oci_spec::runtime::LinuxDevice::path)
                .collect::<Vec<_>>()
        );

        // CDI env var merged into process.env
        let process = oci_spec.process().as_ref().expect("process present");
        let env = process.env().as_ref().expect("env present");
        assert!(
            env.iter().any(|e| e == "NVIDIA_VISIBLE_DEVICES=0"),
            "expected NVIDIA_VISIBLE_DEVICES=0 in env; got {env:?}"
        );

        // CDI hook merged into hooks.createContainer
        let hooks = oci_spec.hooks().as_ref().expect("hooks present");
        let create_container = hooks
            .create_container()
            .as_ref()
            .expect("createContainer hooks present");
        assert_eq!(create_container.len(), 1);
        assert_eq!(
            create_container[0].path(),
            &std::path::PathBuf::from("/usr/bin/nvidia-container-runtime-hook")
        );
    }

    #[tokio::test]
    async fn gpu_spec_with_missing_cdi_returns_error() {
        // Empty tempdir — no CDI specs installed at all.
        let dir = tempfile::tempdir().unwrap();
        let registry = std::sync::Arc::new(crate::cdi::CdiRegistry::discover_from(&[dir.path()]));

        let id = ContainerId::new("test".to_string(), 1);
        let spec = mock_gpu_spec("nvidia", 1);
        let builder =
            BundleBuilder::new("/tmp/test-bundle-cdi-missing".into()).with_cdi_registry(registry);

        let err = builder
            .build_oci_spec(&id, &spec, &std::collections::HashMap::new())
            .await
            .expect_err("should fail when CDI registry is empty");

        match err {
            AgentError::InvalidSpec(msg) => {
                assert!(
                    msg.contains("nvidia") || msg.contains("CDI"),
                    "error should mention CDI / vendor; got: {msg}"
                );
            }
            other => panic!("expected InvalidSpec, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn gpu_spec_with_unknown_device_returns_error() {
        // Spec has device "0" but the request will ask for two GPUs (so the
        // resolver will look for "1" and fail).
        let dir = tempfile::tempdir().unwrap();
        write_nvidia_cdi_fixture(dir.path(), nvidia_cdi_fixture());
        let registry = std::sync::Arc::new(crate::cdi::CdiRegistry::discover_from(&[dir.path()]));

        let id = ContainerId::new("test".to_string(), 1);
        let spec = mock_gpu_spec("nvidia", 2);
        let builder =
            BundleBuilder::new("/tmp/test-bundle-cdi-unknown".into()).with_cdi_registry(registry);

        let err = builder
            .build_oci_spec(&id, &spec, &std::collections::HashMap::new())
            .await
            .expect_err("should fail when device '1' is not declared");
        match err {
            AgentError::InvalidSpec(msg) => {
                assert!(
                    msg.contains("'1'") || msg.contains("device"),
                    "error should mention the missing device; got: {msg}"
                );
            }
            other => panic!("expected InvalidSpec, got {other:?}"),
        }
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn gpu_spec_with_all_devices_expands_to_all_in_spec() {
        // Fixture with two declared devices ("0" and "1").
        let dir = tempfile::tempdir().unwrap();
        let fixture = r#"{
            "cdiVersion": "0.6.0",
            "kind": "nvidia.com/gpu",
            "devices": [
                {
                    "name": "0",
                    "containerEdits": {
                        "env": ["NVIDIA_VISIBLE_DEVICES=0"],
                        "deviceNodes": [
                            {"path": "/dev/nvidia0", "type": "c", "major": 195, "minor": 0}
                        ]
                    }
                },
                {
                    "name": "1",
                    "containerEdits": {
                        "env": ["NVIDIA_VISIBLE_DEVICES=1"],
                        "deviceNodes": [
                            {"path": "/dev/nvidia1", "type": "c", "major": 195, "minor": 1}
                        ]
                    }
                }
            ]
        }"#;
        write_nvidia_cdi_fixture(dir.path(), fixture);
        let registry = std::sync::Arc::new(crate::cdi::CdiRegistry::discover_from(&[dir.path()]));

        // Resolve "all" via the registry directly to validate expansion
        // semantics independently of how we map count -> names.
        let edits = registry
            .resolve_for_kind("nvidia.com/gpu", &["all".to_string()])
            .expect("resolve all");
        assert_eq!(edits.len(), 2);

        // Now build the bundle for a 2-GPU service and confirm both nodes
        // land in linux.devices.
        let id = ContainerId::new("test".to_string(), 1);
        let spec = mock_gpu_spec("nvidia", 2);
        let builder =
            BundleBuilder::new("/tmp/test-bundle-cdi-all".into()).with_cdi_registry(registry);

        let oci_spec = builder
            .build_oci_spec(&id, &spec, &std::collections::HashMap::new())
            .await
            .expect("build with 2-device fixture");

        let devices = oci_spec
            .linux()
            .as_ref()
            .unwrap()
            .devices()
            .as_ref()
            .expect("devices present");
        let paths: Vec<_> = devices.iter().map(|d| d.path().clone()).collect();
        assert!(paths.contains(&std::path::PathBuf::from("/dev/nvidia0")));
        assert!(paths.contains(&std::path::PathBuf::from("/dev/nvidia1")));
    }

    /// Build the standard fixture-backed CDI registry used by the MPS /
    /// time-slicing tests. Identical to the helper used by the 5.A CDI
    /// tests above but expressed as a closure-style helper to keep each test
    /// self-contained.
    fn build_nvidia_cdi_registry(dir: &std::path::Path) -> std::sync::Arc<crate::cdi::CdiRegistry> {
        write_nvidia_cdi_fixture(dir, nvidia_cdi_fixture());
        std::sync::Arc::new(crate::cdi::CdiRegistry::discover_from(&[dir]))
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn gpu_spec_with_mps_sharing_injects_env_and_mounts() {
        // Stage host-side MPS directories in a tempdir so the resolver's
        // `is_dir()` check passes without touching /tmp/nvidia-mps on the
        // real host.
        let cdi_dir = tempfile::tempdir().unwrap();
        let mps_root = tempfile::tempdir().unwrap();
        let pipe_dir = mps_root.path().join("nvidia-mps");
        let log_dir = mps_root.path().join("nvidia-log");
        std::fs::create_dir(&pipe_dir).unwrap();
        std::fs::create_dir(&log_dir).unwrap();
        let registry = build_nvidia_cdi_registry(cdi_dir.path());

        let id = ContainerId::new("test".to_string(), 1);
        let mut spec = mock_gpu_spec("nvidia", 1);
        let gpu = spec.resources.gpu.as_mut().expect("gpu spec set");
        gpu.sharing = Some(zlayer_spec::GpuSharingMode::Mps);
        gpu.mps_pipe_dir = Some(pipe_dir.to_string_lossy().into_owned());
        gpu.mps_log_dir = Some(log_dir.to_string_lossy().into_owned());

        let builder =
            BundleBuilder::new("/tmp/test-bundle-mps-env".into()).with_cdi_registry(registry);
        let oci_spec = builder
            .build_oci_spec(&id, &spec, &std::collections::HashMap::new())
            .await
            .expect("build with MPS sharing");

        let env = oci_spec
            .process()
            .as_ref()
            .and_then(|p| p.env().as_ref())
            .expect("env present");
        let pipe_expect = format!("CUDA_MPS_PIPE_DIRECTORY={}", pipe_dir.display());
        let log_expect = format!("CUDA_MPS_LOG_DIRECTORY={}", log_dir.display());
        assert!(
            env.iter().any(|e| e == &pipe_expect),
            "expected {pipe_expect} in env; got {env:?}"
        );
        assert!(
            env.iter().any(|e| e == &log_expect),
            "expected {log_expect} in env; got {env:?}"
        );

        let mounts = oci_spec.mounts().as_ref().expect("mounts present");
        assert!(
            mounts
                .iter()
                .any(|m| m.destination() == &pipe_dir && m.source().as_ref() == Some(&pipe_dir)),
            "expected bind mount of MPS pipe dir {}; got destinations {:?}",
            pipe_dir.display(),
            mounts.iter().map(Mount::destination).collect::<Vec<_>>()
        );
        assert!(
            mounts
                .iter()
                .any(|m| m.destination() == &log_dir && m.source().as_ref() == Some(&log_dir)),
            "expected bind mount of MPS log dir {}",
            log_dir.display()
        );
    }

    #[tokio::test]
    async fn gpu_spec_with_mps_sharing_fails_when_pipe_dir_missing() {
        let cdi_dir = tempfile::tempdir().unwrap();
        let registry = build_nvidia_cdi_registry(cdi_dir.path());

        let id = ContainerId::new("test".to_string(), 1);
        let mut spec = mock_gpu_spec("nvidia", 1);
        let gpu = spec.resources.gpu.as_mut().expect("gpu spec set");
        gpu.sharing = Some(zlayer_spec::GpuSharingMode::Mps);
        // Path that demonstrably does not exist — tempdir() returns a unique
        // path so appending "definitely-not-here" gives a guaranteed miss.
        let missing = tempfile::tempdir().unwrap();
        let missing_path = missing.path().join("definitely-not-here");
        gpu.mps_pipe_dir = Some(missing_path.to_string_lossy().into_owned());

        let builder =
            BundleBuilder::new("/tmp/test-bundle-mps-missing".into()).with_cdi_registry(registry);
        let err = builder
            .build_oci_spec(&id, &spec, &std::collections::HashMap::new())
            .await
            .expect_err("should fail when MPS pipe dir is missing");
        match err {
            AgentError::GpuSharingUnavailable { mode, reason } => {
                assert_eq!(mode, "mps");
                assert!(
                    reason.contains("pipe") || reason.contains(&missing_path.display().to_string()),
                    "reason should mention the missing path; got: {reason}"
                );
            }
            other => panic!("expected GpuSharingUnavailable, got {other:?}"),
        }
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn gpu_spec_with_timeslicing_injects_visible_devices() {
        let cdi_dir = tempfile::tempdir().unwrap();
        let registry = build_nvidia_cdi_registry(cdi_dir.path());

        let id = ContainerId::new("test".to_string(), 1);
        let mut spec = mock_gpu_spec("nvidia", 1);
        let gpu = spec.resources.gpu.as_mut().expect("gpu spec set");
        gpu.sharing = Some(zlayer_spec::GpuSharingMode::TimeSlice);
        gpu.time_slice_index = Some(2);

        let builder =
            BundleBuilder::new("/tmp/test-bundle-timeslice".into()).with_cdi_registry(registry);
        let oci_spec = builder
            .build_oci_spec(&id, &spec, &std::collections::HashMap::new())
            .await
            .expect("build with time-slicing");

        let env = oci_spec
            .process()
            .as_ref()
            .and_then(|p| p.env().as_ref())
            .expect("env present");
        // Time-slicing must clobber any earlier `CUDA_VISIBLE_DEVICES` (e.g.
        // the CDI-emitted full-device list) to advertise exactly the slice.
        let cuda_entries: Vec<&String> = env
            .iter()
            .filter(|e| e.starts_with("CUDA_VISIBLE_DEVICES="))
            .collect();
        assert_eq!(
            cuda_entries.len(),
            1,
            "exactly one CUDA_VISIBLE_DEVICES expected; got {cuda_entries:?}"
        );
        assert_eq!(cuda_entries[0], "CUDA_VISIBLE_DEVICES=2");
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn gpu_spec_without_sharing_omits_mps_env() {
        let cdi_dir = tempfile::tempdir().unwrap();
        let registry = build_nvidia_cdi_registry(cdi_dir.path());

        let id = ContainerId::new("test".to_string(), 1);
        let spec = mock_gpu_spec("nvidia", 1);
        assert!(spec.resources.gpu.as_ref().unwrap().sharing.is_none());

        let builder =
            BundleBuilder::new("/tmp/test-bundle-no-sharing".into()).with_cdi_registry(registry);
        let oci_spec = builder
            .build_oci_spec(&id, &spec, &std::collections::HashMap::new())
            .await
            .expect("build without sharing");

        let env = oci_spec
            .process()
            .as_ref()
            .and_then(|p| p.env().as_ref())
            .expect("env present");
        assert!(
            !env.iter().any(|e| e.starts_with("CUDA_MPS_")),
            "no CUDA_MPS_* env should be present without sharing; got {env:?}"
        );

        // No MPS mount should be added either. The 5.A CDI fixture mounts a
        // /dev/nvidia0 device but never bind-mounts /tmp/nvidia-mps; verify
        // we don't sneak that in.
        let mounts = oci_spec.mounts().as_ref().expect("mounts present");
        assert!(
            !mounts
                .iter()
                .any(|m| { m.destination().to_string_lossy().contains("nvidia-mps") }),
            "no MPS pipe mount should be present without sharing"
        );
    }

    #[cfg(unix)]
    mod subid_tests {
        use super::super::read_subid_range;
        use std::io::Write;

        #[test]
        fn read_subid_range_returns_range_for_user() {
            let mut tmp = tempfile::NamedTempFile::new().unwrap();
            writeln!(tmp, "alice:100000:65536").unwrap();
            writeln!(tmp, "bob:165536:65536").unwrap();
            tmp.flush().unwrap();
            let path = tmp.path().to_str().unwrap();
            assert_eq!(read_subid_range(path, "bob"), Some((165_536, 65_536)));
            assert_eq!(read_subid_range(path, "alice"), Some((100_000, 65_536)));
        }

        #[test]
        fn read_subid_range_returns_none_for_unknown_user() {
            let mut tmp = tempfile::NamedTempFile::new().unwrap();
            writeln!(tmp, "alice:100000:65536").unwrap();
            tmp.flush().unwrap();
            assert_eq!(
                read_subid_range(tmp.path().to_str().unwrap(), "carol"),
                None
            );
        }

        #[test]
        fn read_subid_range_returns_none_on_missing_file() {
            assert_eq!(
                read_subid_range("/this/path/does/not/exist/subuid", "anyone"),
                None
            );
        }
    }
}