devsandbox 0.11.1

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
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
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use anyhow::{anyhow, bail, Context, Result};
use serde::Deserialize;
use toml::{Table, Value};

use crate::runtime::identity::Identity;

/// Default config file name, written by `run`'s example-config offer.
pub const CONFIG_FILE: &str = "devsandboxes.toml";
/// Every accepted config file name; more than one present is an error rather
/// than a silent precedence pick.
const CONFIG_FILES: [&str; 3] = [CONFIG_FILE, "devsandboxes.yaml", "devsandboxes.yml"];
/// Pre-0.5.1 name. Still read when nothing else exists, and renamed to
/// [`CONFIG_FILE`] by [`migrate_legacy`].
const LEGACY_CONFIG_FILE: &str = "config.toml";

/// Every path [`find`] may pick in `dir`, present or not: what a watcher
/// stamps to notice an edit, a new file or a rename between them.
pub fn candidates(dir: &Path) -> impl Iterator<Item = PathBuf> + '_ {
    CONFIG_FILES.iter().chain([&LEGACY_CONFIG_FILE]).map(move |f| dir.join(f))
}

/// The config file in `dir`: one of [`CONFIG_FILES`], else a legacy
/// `config.toml` that looks like a devsandbox config, else `None`.
pub fn find(dir: &Path) -> Result<Option<PathBuf>> {
    let present: Vec<PathBuf> =
        CONFIG_FILES.iter().map(|f| dir.join(f)).filter(|p| p.is_file()).collect();
    match present.as_slice() {
        [] => Ok(legacy(dir)),
        [one] => Ok(Some(one.clone())),
        many => bail!(
            "several config files in {}: {}; keep only one",
            dir.display(),
            many.iter().filter_map(|p| p.file_name()?.to_str()).collect::<Vec<_>>().join(", ")
        ),
    }
}

/// The config file [`Config::load`] reads in `dir`, for messages: the default
/// name when there is none (or the lookup fails).
pub fn display_path(dir: &Path) -> PathBuf {
    find(dir).ok().flatten().unwrap_or_else(|| dir.join(CONFIG_FILE))
}

/// A legacy `config.toml` in `dir`, only if it has a devsandbox top-level
/// table: the name is common enough (Hugo, …) that an unrelated file must not
/// be read, let alone renamed.
fn legacy(dir: &Path) -> Option<PathBuf> {
    let path = dir.join(LEGACY_CONFIG_FILE);
    let table: Table = toml::from_str(&std::fs::read_to_string(&path).ok()?).ok()?;
    ["sandbox", "template", "services"]
        .iter()
        .any(|k| table.contains_key(*k))
        .then_some(path)
}

/// Rename a legacy `config.toml` in `dir` to [`CONFIG_FILE`] when no current
/// config file exists. Returns the new path when it renamed.
pub fn migrate_legacy(dir: &Path) -> Result<Option<PathBuf>> {
    let Some(old) = find(dir)? else { return Ok(None) };
    if old.file_name().and_then(|n| n.to_str()) != Some(LEGACY_CONFIG_FILE) {
        return Ok(None);
    }
    let new = dir.join(CONFIG_FILE);
    std::fs::rename(&old, &new)
        .with_context(|| format!("cannot rename {} to {}", old.display(), new.display()))?;
    Ok(Some(new))
}

/// Raw `devsandboxes.toml` (or `.yaml`) contents (TOML or YAML, same schema). Template and sandbox bodies are kept as
/// free-form tables so `extends` can deep-merge them; the merged result is
/// validated into [`SandboxProperties`] by `resolve_sandbox`.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    #[serde(default)]
    pub services: BTreeMap<String, Table>,
    #[serde(default, rename = "template")]
    pub templates: BTreeMap<String, Table>,
    #[serde(default, rename = "sandbox")]
    pub sandboxes: BTreeMap<String, Table>,
    /// `[profiles.<name>]`: the profiles a sandbox's instances may be in
    /// (docs/architecture/instances/profiles.md). Names are checked by
    /// [`check_profile_name`] at parse.
    #[serde(default)]
    pub profiles: BTreeMap<String, Profile>,
    /// `[updates]`: per feature update, by name, how often it runs
    /// (`"never"` or a duration), overriding the feature's `every`. Root
    /// level, so never in a sandbox's `config_hash`.
    #[serde(default)]
    pub updates: BTreeMap<String, crate::updates::Interval>,
}

/// A `[profiles.<name>]` table. Empty: any key in it is an error until
/// profiles carry settings of their own.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Profile {}

/// `[a-z0-9][a-z0-9_.-]*`: a profile name. Config has no sandbox-name rule
/// to share; this one is safe as a TOML bare key, a path segment and a
/// container-name part, wherever a profile ends up later.
pub fn check_profile_name(name: &str) -> Result<()> {
    let lower_alnum = |c: char| c.is_ascii_lowercase() || c.is_ascii_digit();
    let mut chars = name.chars();
    let ok = chars.next().is_some_and(lower_alnum) && chars.all(|c| lower_alnum(c) || matches!(c, '_' | '.' | '-'));
    if !ok {
        bail!(
            "profile name `{}`: lowercase letters, digits, `_`, `.` and `-`, starting with a letter or digit",
            name.escape_debug()
        );
    }
    Ok(())
}

/// A sandbox's config as text ([`Config::sandbox_text`]): what the
/// dashboard's config view shows, and the daemon's `sandboxes.get` answer.
#[cfg_attr(not(unix), allow(dead_code))] // only the dashboard and daemon (unix) use it
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, Deserialize)]
pub struct SandboxText {
    /// `[sandbox.<name>]` as written, `extends` included.
    pub original: String,
    /// The merged table (`extends` resolved and dropped), or why it doesn't merge.
    pub resolved: String,
    /// The merged table's config hash; empty when it doesn't merge.
    pub hash: String,
}

/// A table as TOML text for display; a table that won't serialize shows
/// the error instead, so the view still renders something.
#[cfg_attr(not(unix), allow(dead_code))] // only the dashboard and daemon (unix) use it
pub fn table_text(table: &Table) -> String {
    match toml::to_string_pretty(table) {
        Ok(s) => s,
        Err(e) => format!("cannot serialize config: {e}"),
    }
}

/// The exact set of properties a sandbox accepts: the devcontainer.json
/// schema plus the devsandbox extras (`extends`, `folder`, `services`,
/// `caches`, `persist-shell-history`). Unknown keys are a hard error (`deny_unknown_fields`);
/// valid-but-unimplemented ones are surfaced by [`Self::ignored`] so `run`
/// can warn before creating the container.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SandboxProperties {
    // devsandbox extras
    pub folder: Option<String>,
    pub services: Option<Vec<String>>,
    /// Package-manager caches to persist and share across the config root (e.g.
    /// `["pnpm", "cargo"]`). Each expands into a shared bind mount plus the env
    /// vars that point the tool at it. See [`known_cache`].
    pub caches: Option<Vec<String>>,
    /// When true, provision a per-instance `.zsh_history` on the host and
    /// bind-mount it, so shell history survives rebuilds without being shared
    /// between concurrent instances.
    #[serde(rename = "persist-shell-history")]
    pub persist_shell_history: Option<bool>,
    /// Branch for a worktree instance (created unless it exists, see
    /// `create_worktree`). A pattern supporting the same `${…}` variables as
    /// `mounts` (notably `${instance}`); defaults to `sandbox/${instance}`
    /// when unset. A `run --branch` overrides it.
    #[serde(rename = "worktree-branch")]
    pub worktree_branch: Option<String>,
    /// Start point for a worktree instance's branch (any commit-ish, e.g.
    /// `origin/develop`). Unset: the remote's default branch is detected
    /// after a fetch. A `run --base` overrides it.
    #[serde(rename = "worktree-base")]
    pub worktree_base: Option<String>,
    /// Extra `.worktreeinclude` patterns (gitignore syntax): gitignored files
    /// copied from the base repo into each worktree, on `run` and every
    /// `rebuild` (never overwriting). Applied after the
    /// repo's own `.worktreeinclude`, so they can negate its patterns.
    #[serde(rename = "worktree-include")]
    pub worktree_include: Option<Vec<String>>,
    /// Repo-relative gitignored paths shared live by every instance: kept in
    /// `shared-files/<repo>-<hash>/` (one per base folder, shared by every
    /// sandbox on it) and symlinked into each working tree, the
    /// store mounted at its host path (docs/architecture/instances/worktrees.md).
    #[serde(rename = "worktree-link")]
    pub worktree_link: Option<Vec<String>>,
    /// Host shell snippets (relative to the config dir, `${…}` variables as in
    /// `mounts`) sourced by the container's interactive `~/.zshrc` and
    /// `~/.bashrc`. Each file is bind-mounted read-only via its parent dir and
    /// a guarded `. <file>` line is appended to both rc files once at create.
    /// Arrays concatenate under `extends`, so a template's aliases and a
    /// sandbox's additions are all sourced.
    #[serde(rename = "shell-rc")]
    pub shell_rc: Option<Vec<String>>,
    /// Extra VS Code workspace roots: container path -> host folder (relative
    /// to the config dir). Each entry is bind-mounted at its key and listed in
    /// the generated `.code-workspace` file after `workspaceFolder`. A value is
    /// the host dir, or a table adding its `worktree` mode (docs/architecture/instances/worktrees.md).
    pub folders: Option<BTreeMap<String, FolderEntry>>,
    /// Bring this sandbox's instances up once per host boot (docs/architecture/automations/autostart.md).
    /// Excluded from `config_hash` so toggling it never marks instances drifted.
    pub autostart: Option<Autostart>,
    /// Makes this sandbox a dispatcher: its instances may create and manage
    /// child instances over the control API (docs/architecture/automations/dispatchers.md). Read from
    /// config on every request and baked into nothing, so it's excluded from
    /// `config_hash` like `autostart`.
    pub dispatcher: Option<Dispatcher>,
    /// `inbox = true` lets this sandbox's instances own Inbox threads
    /// (`devsbd thread put|rm|ls`, `devsbd events`; docs/architecture/inbox/threads-and-feed.md,
    /// _Ownership_). Separate from `dispatcher`, which only grants child ops.
    /// Checked on every request, so excluded from `config_hash`.
    pub inbox: Option<bool>,
    /// `placement = "home"` pins the sandbox to the host whose config names
    /// it: a `run --place` runs it here (fleet plan decision 40, reported as
    /// a tie by `serve::fleet::code::ties`). Host-side only, so excluded
    /// from `config_hash`.
    pub placement: Option<Placement>,
    /// The `[profiles.*]` this sandbox's instances may be in, in preference
    /// order (docs/architecture/instances/profiles.md); unset: every declared
    /// one ([`Config::allowed_profiles`]). Deduplicated and checked against
    /// the declared profiles by `resolve_sandbox`. Host-side only, so
    /// excluded from `config_hash`.
    pub profiles: Option<Vec<String>>,
    /// `access.<kind>`: what this sandbox asks of the home's credential of
    /// that claim kind (docs/plans/active/credential-broker.md, *Policy*).
    /// Policy the broker reads per call from the host's config, baked into
    /// nothing, so excluded from `config_hash`.
    pub access: Option<BTreeMap<String, Access>>,
    /// The host agent's keys the relay offers while a git-host claim
    /// applies (docs/architecture/helper/ssh-agent.md, *Key filtering*);
    /// none by default. Read per agent connection, so excluded from
    /// `config_hash`.
    #[serde(rename = "ssh-keys")]
    pub ssh_keys: Option<Vec<SshKey>>,

    // implemented devcontainer properties
    pub image: Option<String>,
    pub build: Option<Build>,
    pub workspace_folder: Option<String>,
    pub container_env: Option<BTreeMap<String, String>>,
    pub remote_env: Option<BTreeMap<String, String>>,
    pub initialize_command: Option<LifecycleCommand>,
    pub on_create_command: Option<LifecycleCommand>,
    pub update_content_command: Option<LifecycleCommand>,
    pub post_create_command: Option<LifecycleCommand>,
    pub post_start_command: Option<LifecycleCommand>,
    pub post_attach_command: Option<LifecycleCommand>,
    pub customizations: Option<Customizations>,
    /// devcontainer `features`: a map of feature ref (e.g.
    /// `"ghcr.io/devcontainers/features/node:1"`) to its options.
    pub features: Option<BTreeMap<String, FeatureOptions>>,
    /// Run the container `--privileged`. OR-ed with any enabled feature's
    /// `privileged` (as the official CLI does), so `false` cannot veto a
    /// feature that needs it.
    pub privileged: Option<bool>,
    /// Ports the daemon forwards to the host while their owner runs
    /// (docs/architecture/daemon/forwards.md, _Configured forwards (`forwardPorts`)_). Host-side only, so
    /// excluded from `config_hash`.
    pub forward_ports: Option<Vec<ForwardPort>>,
    pub mounts: Option<Vec<Mount>>,
    pub container_user: Option<String>,
    pub remote_user: Option<String>,
    /// Who you are inside: `host` adopts the image's user at the host
    /// uid/gid, `image` takes users literally. Read through [`Self::identity`]; changes how the container
    /// is created, so it stays in `config_hash`.
    pub identity: Option<Identity>,
    /// devcontainer's knob, read as a hint for [`Self::identity`]: `false`
    /// means `identity = "image"`. Hashed like `identity`.
    #[serde(rename = "updateRemoteUserUID")]
    pub update_remote_user_uid: Option<bool>,
    /// Let unprivileged processes create user namespaces (what a browser's
    /// sandbox needs): on docker, `run` passes devsandbox's seccomp profile
    /// (`runtime::seccomp`). Read through [`Self::userns`]; changes create
    /// args, so it stays in `config_hash`.
    pub userns: Option<bool>,
    pub init: Option<bool>,

    // devcontainer properties not implemented yet ([`Self::ignored`])
    pub name: Option<Value>,
    pub app_port: Option<Value>,
    pub ports_attributes: Option<Value>,
    pub other_ports_attributes: Option<Value>,
    pub run_args: Option<Value>,
    pub workspace_mount: Option<Value>,
    pub override_feature_install_order: Option<Value>,
    pub user_env_probe: Option<Value>,
    pub override_command: Option<Value>,
    pub shutdown_action: Option<Value>,
    pub cap_add: Option<Value>,
    pub security_opt: Option<Value>,
    /// devcontainer `hostRequirements`: `gpu` decides the run's GPU flags
    /// (`commands::run::gpu_decision`); every other set key is
    /// [`Self::ignored`].
    pub host_requirements: Option<HostRequirements>,
    pub wait_for: Option<Value>,
    pub secrets: Option<Value>,
}

/// `autostart` mode: `false` / `true` / `"runtime"`. `Runtime` also gets the
/// devsandbox-driven pass; on backends with restart policies its containers
/// additionally carry `--restart unless-stopped` (`commands::autostart`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Autostart {
    #[default]
    Off,
    /// The first devsandbox process after a boot starts the instances.
    Devsandbox,
    /// The container runtime restarts the containers on boot.
    Runtime,
}

/// `placement`: where a placed `run` may put the sandbox. Only `"home"`
/// (the host whose config names it) exists.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Placement {
    Home,
}

/// `[sandbox.<name>.access.<kind>]`. Arrays concatenate under `extends`
/// (deduplicated at resolve), so a template's scopes reach every sandbox
/// extending it and a sandbox can only add to them.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Access {
    /// Scopes allowed outright.
    #[serde(default)]
    pub scopes: Vec<String>,
    /// Scopes held for an answer instead of denied.
    #[serde(default)]
    pub ask: Vec<String>,
    /// The home's credential to take (`sentry-work`), over the one granted
    /// to the instance's profile.
    pub credential: Option<String>,
    // Read from github-and-sentry-access step 2.
    #[serde(default)]
    pub repos: Vec<String>,
    #[serde(default)]
    pub branches: Vec<String>,
    /// Narrows the credential's `orgs`, for a claim with an org fence.
    #[serde(default)]
    pub orgs: Vec<String>,
    /// The token kind to take the credential as (`user` | `app`), within
    /// what the home offers (`credentials::tokens::pick`).
    #[serde(rename = "as")]
    pub as_: Option<String>,
}

/// One `ssh-keys` entry: `{ key, destinations, signing-only }`.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(try_from = "RawSshKey")]
pub struct SshKey {
    pub key: KeyRef,
    /// `None`: any host, GitHub over ssh included. Hosts as `known_hosts`
    /// names them (`host`, `[host]:port`).
    pub destinations: Option<Vec<String>>,
    pub signing_only: bool,
}

/// How an `ssh-keys` entry names an agent key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyRef {
    /// `SHA256:<base64>` as `ssh-add -l` prints it; holds the base64.
    Fingerprint(String),
    /// The key blob of a public key line (`ssh-ed25519 AAAA… comment`).
    Blob(Vec<u8>),
}

impl KeyRef {
    pub fn matches(&self, blob: &[u8]) -> bool {
        match self {
            KeyRef::Blob(b) => b == blob,
            KeyRef::Fingerprint(fp) => *fp == fingerprint_b64(blob),
        }
    }
}

/// The base64 part of an OpenSSH `SHA256:` fingerprint: unpadded.
pub fn fingerprint_b64(blob: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    let full = crate::broker::redact::base64(&Sha256::digest(blob));
    String::from_utf8_lossy(&full).trim_end_matches('=').to_string()
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawSshKey {
    key: String,
    destinations: Option<Vec<String>>,
    #[serde(default, rename = "signing-only")]
    signing_only: bool,
}

impl TryFrom<RawSshKey> for SshKey {
    type Error = String;

    fn try_from(raw: RawSshKey) -> Result<SshKey, String> {
        let key = parse_key_ref(raw.key.trim())?;
        match &raw.destinations {
            Some(_) if raw.signing_only => {
                return Err("`ssh-keys`: a `signing-only` key logs in nowhere, so it takes no `destinations`".into());
            }
            Some(d) if d.is_empty() => {
                return Err("`ssh-keys`: `destinations` is empty: name hosts, or leave it out for every host".into());
            }
            Some(d) if d.iter().any(|h| h.is_empty() || h.contains(char::is_whitespace) || h.starts_with('-')) => {
                return Err("`ssh-keys`: a destination is a host as `known_hosts` names it (`host`, `[host]:port`)".into());
            }
            _ => {}
        }
        Ok(SshKey { key, destinations: raw.destinations, signing_only: raw.signing_only })
    }
}

fn parse_key_ref(s: &str) -> Result<KeyRef, String> {
    if let Some(fp) = s.strip_prefix("SHA256:") {
        let padded = format!("{fp}{}", "=".repeat((4 - fp.len() % 4) % 4));
        return match crate::broker::redact::base64_decode(padded.as_bytes()) {
            Some(digest) if digest.len() == 32 => Ok(KeyRef::Fingerprint(fp.to_string())),
            _ => Err(format!("`ssh-keys`: `{s}` isn't a SHA256 fingerprint as `ssh-add -l` prints it")),
        };
    }
    let mut words = s.split_whitespace();
    let (Some(kind), Some(b64)) = (words.next(), words.next()) else {
        return Err(format!("`ssh-keys`: `{s}` is neither a `SHA256:` fingerprint nor a public key line"));
    };
    let blob = crate::broker::redact::base64_decode(b64.as_bytes())
        .ok_or_else(|| format!("`ssh-keys`: the public key line for `{kind}` has bad base64"))?;
    // The blob opens with its own type name: a line whose two disagree was mangled.
    let named = blob.get(..4).map(|n| u32::from_be_bytes([n[0], n[1], n[2], n[3]]) as usize);
    if named.and_then(|n| blob.get(4..4 + n)) != Some(kind.as_bytes()) {
        return Err(format!("`ssh-keys`: the public key line's blob isn't a `{kind}` key"));
    }
    Ok(KeyRef::Blob(blob))
}

/// `dispatcher = { spawn = [...], max-instances = N }`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Dispatcher {
    /// Sandboxes of this config root the dispatcher may instantiate;
    /// [`Dispatcher::ANY`] allows every one.
    #[serde(default)]
    pub spawn: Vec<String>,
    /// Cap on the dispatcher's children (all recorded ones, stopped included);
    /// unset = [`Dispatcher::DEFAULT_MAX_INSTANCES`] (see [`Dispatcher::cap`]).
    #[serde(rename = "max-instances")]
    pub max_instances: Option<u32>,
}

impl Dispatcher {
    pub const ANY: &'static str = "*";

    /// `max-instances` when unset: a runaway (or hostile) dispatcher can't
    /// fill the host with children by default.
    pub const DEFAULT_MAX_INSTANCES: u32 = 10;

    /// The effective cap on children.
    pub fn cap(&self) -> u32 {
        self.max_instances.unwrap_or(Self::DEFAULT_MAX_INSTANCES)
    }

    /// Whether `spawn` lists `sandbox` (or [`Dispatcher::ANY`]). `"*"` never
    /// covers dispatcher sandboxes, this one included: children can't be
    /// dispatchers, which `commands::dispatch` enforces on `ensure` whatever
    /// `spawn` says.
    pub fn may_spawn(&self, sandbox: &str) -> bool {
        self.spawn.iter().any(|s| s == Self::ANY || s == sandbox)
    }
}

/// A `folders` value: `"<host dir>"` or `{ path = "<host dir>", worktree = … }`.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(
    untagged,
    expecting = "a host dir string or { path = \"…\", worktree = \"auto\" | \"always\" | \"never\" }"
)]
pub enum FolderEntry {
    Path(String),
    Table(FolderTable),
}

/// Table form of a [`FolderEntry`]. A separate struct because
/// `deny_unknown_fields` is a container attribute, so typos like `wroktree`
/// error instead of silently defaulting the mode.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FolderTable {
    pub path: String,
    #[serde(default)]
    pub worktree: Option<FolderWorktree>,
}

/// When a `folders` entry gets its own git worktree (docs/architecture/instances/worktrees.md).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum FolderWorktree {
    /// Worktree only when the checkout is owned or directly mounted elsewhere.
    #[default]
    Auto,
    /// Always a worktree; the folder must be a git repo root.
    Always,
    /// Always the live host dir.
    Never,
}

impl FolderEntry {
    /// The host dir, unsubstituted and relative to the config dir.
    pub fn path(&self) -> &str {
        match self {
            Self::Path(path) => path,
            Self::Table(table) => &table.path,
        }
    }

    pub fn worktree_mode(&self) -> FolderWorktree {
        match self {
            Self::Path(_) => FolderWorktree::Auto,
            Self::Table(table) => table.worktree.unwrap_or_default(),
        }
    }
}

/// devcontainer `hostRequirements`, on a sandbox or (a devsandbox extension)
/// a `[services.*]` table. Spelled as the spec spells it.
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HostRequirements {
    pub gpu: Option<GpuRequirement>,
    pub cpus: Option<Value>,
    pub memory: Option<Value>,
    pub storage: Option<Value>,
}

/// `hostRequirements.gpu`: `true` | `false` | `"optional"` |
/// `{ cores, memory }` (the table form counts as required).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GpuRequirement {
    /// `false`: no GPU asked for.
    No,
    Required,
    Optional,
    /// The spec's minimums; parsed, not enforced.
    Min { cores: Option<u64>, memory: Option<String> },
}

/// What a sandbox or service needs of a GPU, from [`HostRequirements::gpu_need`].
/// Serde is the `fleet.place` wire's (`"required"` | `"optional"`); the
/// config parses [`GpuRequirement`] instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GpuNeed {
    Required,
    Optional,
}

impl HostRequirements {
    /// The GPU asked for, `None` when unset or `false`.
    pub fn gpu_need(&self) -> Option<GpuNeed> {
        match self.gpu.as_ref()? {
            GpuRequirement::No => None,
            GpuRequirement::Required | GpuRequirement::Min { .. } => Some(GpuNeed::Required),
            GpuRequirement::Optional => Some(GpuNeed::Optional),
        }
    }

    /// Dotted names (under `hostRequirements.`) of the keys set that
    /// nothing acts on: `gpu` itself is, its minimums aren't.
    fn set_keys(&self) -> Vec<String> {
        let mut out = Vec::new();
        if let Some(GpuRequirement::Min { cores, memory }) = &self.gpu {
            if cores.is_some() {
                out.push("hostRequirements.gpu.cores".to_string());
            }
            if memory.is_some() {
                out.push("hostRequirements.gpu.memory".into());
            }
        }
        for (set, name) in [
            (self.cpus.is_some(), "cpus"),
            (self.memory.is_some(), "memory"),
            (self.storage.is_some(), "storage"),
        ] {
            if set {
                out.push(format!("hostRequirements.{name}"));
            }
        }
        out
    }
}

impl<'de> Deserialize<'de> for GpuRequirement {
    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> std::result::Result<Self, D::Error> {
        /// The table form, its own struct so unknown keys error.
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Min {
            cores: Option<u64>,
            memory: Option<String>,
        }
        struct V;
        impl<'de> serde::de::Visitor<'de> for V {
            type Value = GpuRequirement;
            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("`true`, `false`, `\"optional\"` or `{ cores = …, memory = \"…\" }`")
            }
            fn visit_bool<E: serde::de::Error>(self, v: bool) -> std::result::Result<GpuRequirement, E> {
                Ok(if v { GpuRequirement::Required } else { GpuRequirement::No })
            }
            fn visit_str<E: serde::de::Error>(self, v: &str) -> std::result::Result<GpuRequirement, E> {
                match v {
                    "optional" => Ok(GpuRequirement::Optional),
                    _ => Err(E::invalid_value(serde::de::Unexpected::Str(v), &self)),
                }
            }
            fn visit_map<A: serde::de::MapAccess<'de>>(
                self,
                map: A,
            ) -> std::result::Result<GpuRequirement, A::Error> {
                let Min { cores, memory } =
                    Min::deserialize(serde::de::value::MapAccessDeserializer::new(map))?;
                Ok(GpuRequirement::Min { cores, memory })
            }
        }
        de.deserialize_any(V)
    }
}

impl<'de> Deserialize<'de> for Autostart {
    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> std::result::Result<Self, D::Error> {
        struct V;
        impl serde::de::Visitor<'_> for V {
            type Value = Autostart;
            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("`true`, `false` or `\"runtime\"`")
            }
            fn visit_bool<E: serde::de::Error>(self, v: bool) -> std::result::Result<Autostart, E> {
                Ok(if v { Autostart::Devsandbox } else { Autostart::Off })
            }
            fn visit_str<E: serde::de::Error>(self, v: &str) -> std::result::Result<Autostart, E> {
                match v {
                    "runtime" => Ok(Autostart::Runtime),
                    _ => Err(E::invalid_value(serde::de::Unexpected::Str(v), &self)),
                }
            }
        }
        de.deserialize_any(V)
    }
}

impl SandboxProperties {
    /// The effective `identity`: an explicit one wins, else
    /// `updateRemoteUserUID = false` means [`Identity::Image`], else
    /// [`Identity::Host`].
    pub fn identity(&self) -> Identity {
        match (self.identity, self.update_remote_user_uid) {
            (Some(identity), _) => identity,
            (None, Some(false)) => Identity::Image,
            (None, _) => Identity::Host,
        }
    }

    /// The effective `userns`: on unless set to `false`.
    pub fn userns(&self) -> bool {
        self.userns != Some(false)
    }

    /// Names of valid devcontainer properties that are set but not
    /// implemented yet.
    pub fn ignored(&self) -> Vec<String> {
        let mut out = Vec::new();
        macro_rules! flag {
            ($($field:ident => $name:literal),* $(,)?) => {
                $(if self.$field.is_some() { out.push($name.to_string()); })*
            };
        }
        flag!(
            name => "name",
            app_port => "appPort",
            ports_attributes => "portsAttributes",
            other_ports_attributes => "otherPortsAttributes",
            run_args => "runArgs",
            workspace_mount => "workspaceMount",
            override_feature_install_order => "overrideFeatureInstallOrder",
            user_env_probe => "userEnvProbe",
            override_command => "overrideCommand",
            shutdown_action => "shutdownAction",
            cap_add => "capAdd",
            security_opt => "securityOpt",
            wait_for => "waitFor",
            secrets => "secrets",
        );
        if let Some(host) = &self.host_requirements {
            out.extend(host.set_keys());
        }
        if let Some(customizations) = &self.customizations {
            if let Some(vscode) = &customizations.vscode {
                if vscode.settings.is_some() {
                    out.push("customizations.vscode.settings".into());
                }
                for key in vscode.other.keys() {
                    out.push(format!("customizations.vscode.{key}"));
                }
            }
            for tool in customizations.other.keys() {
                out.push(format!("customizations.{tool}"));
            }
        }
        out
    }

    pub fn vscode_extensions(&self) -> Option<&[String]> {
        self.customizations
            .as_ref()?
            .vscode
            .as_ref()?
            .extensions
            .as_deref()
    }
}

/// A `forwardPorts` entry, `[host:][service:]port`: `3000`, `"8080:3000"`,
/// `"db:5432"` (the devcontainer form for a service port), `"15432:db:5432"`.
/// A leading number is always the host port; the host port forms are a
/// devsandbox extension.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ForwardPort {
    /// Host port to start the search from; the target port when unset.
    pub host: Option<u16>,
    /// Service whose port is forwarded; the instance's own port when unset.
    pub service: Option<String>,
    pub port: u16,
}

impl ForwardPort {
    pub fn parse(entry: &str) -> std::result::Result<ForwardPort, String> {
        let port = |s: &str| match s.parse::<u16>() {
            Ok(0) | Err(_) => Err(format!("forwardPorts entry `{entry}`: `{s}` is not a port number")),
            Ok(p) => Ok(p),
        };
        let service = |s: &str| {
            if s.is_empty() || s.parse::<u16>().is_ok() {
                Err(format!("forwardPorts entry `{entry}`: `{s}` is not a service name"))
            } else {
                Ok(s.to_string())
            }
        };
        match entry.split(':').collect::<Vec<_>>()[..] {
            [p] => Ok(ForwardPort { host: None, service: None, port: port(p)? }),
            [a, p] if a.parse::<u16>().is_ok() => Ok(ForwardPort { host: Some(port(a)?), service: None, port: port(p)? }),
            [s, p] => Ok(ForwardPort { host: None, service: Some(service(s)?), port: port(p)? }),
            [h, s, p] => Ok(ForwardPort { host: Some(port(h)?), service: Some(service(s)?), port: port(p)? }),
            _ => Err(format!("forwardPorts entry `{entry}`: expected `[host:][service:]port`")),
        }
    }

    /// Canonical form (`3000` and `"3000"` agree): the key the chosen host
    /// port is saved under in state.
    pub fn key(&self) -> String {
        let mut key = String::new();
        if let Some(host) = self.host {
            key.push_str(&format!("{host}:"));
        }
        if let Some(service) = &self.service {
            key.push_str(&format!("{service}:"));
        }
        key.push_str(&self.port.to_string());
        key
    }

    /// Where the host port search starts.
    pub fn base(&self) -> u16 {
        self.host.unwrap_or(self.port)
    }
}

impl<'de> Deserialize<'de> for ForwardPort {
    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> std::result::Result<Self, D::Error> {
        struct V;
        impl serde::de::Visitor<'_> for V {
            type Value = ForwardPort;
            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("a port number or a `[host:][service:]port` string")
            }
            fn visit_i64<E: serde::de::Error>(self, v: i64) -> std::result::Result<ForwardPort, E> {
                ForwardPort::parse(&v.to_string()).map_err(E::custom)
            }
            fn visit_u64<E: serde::de::Error>(self, v: u64) -> std::result::Result<ForwardPort, E> {
                ForwardPort::parse(&v.to_string()).map_err(E::custom)
            }
            fn visit_str<E: serde::de::Error>(self, v: &str) -> std::result::Result<ForwardPort, E> {
                ForwardPort::parse(v).map_err(E::custom)
            }
        }
        de.deserialize_any(V)
    }
}

/// Options for a single `features` entry: an options table, a bare string
/// (devcontainer shorthand for the `version` option), or a bool (`true` = no
/// options).
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum FeatureOptions {
    Options(BTreeMap<String, Value>),
    Version(String),
    Enabled(bool),
}

/// A `mounts` entry: the docker `--mount` shorthand string
/// (`source=…,target=…,type=bind`) or the devcontainer object form.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum Mount {
    Shorthand(String),
    Object(MountObject),
}

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct MountObject {
    #[serde(rename = "type")]
    pub kind: Option<String>,
    pub source: Option<String>,
    pub target: String,
    pub readonly: Option<bool>,
}

/// Values for the devcontainer `${…}` variables devsandbox substitutes in mount
/// sources. `localEnv:*` is read from the process environment separately.
#[derive(Clone, Copy)]
pub struct MountContext<'a> {
    /// Directory holding `devsandboxes.toml` (`${configDir}`).
    pub config_dir: &'a str,
    /// Host path of the project checkout (`${localWorkspaceFolder}`).
    pub workspace_folder: &'a str,
    /// Its basename (`${localWorkspaceFolderBasename}`).
    pub workspace_folder_basename: &'a str,
    /// `<configDir>/shared-volumes` (`${sharedVolumes}`), the host-backed
    /// persistent-state root.
    pub shared_volumes: &'a str,
    /// Persistent id of the instance being run (`${instance}`), e.g. `web` /
    /// `web-2` — anchors per-instance state under `${sharedVolumes}`. This is
    /// `Instance::instance_id` (the name at creation, unique forever), not the
    /// current display name, so renames never move `${instance}`-anchored paths.
    pub instance: &'a str,
    /// What `${containerEnv:NAME}` reads, known once the image is built
    /// (`run` only). `None` (`ls`, the snapshot) leaves it verbatim.
    pub container_env: Option<&'a ContainerEnv>,
}

/// The env `${containerEnv:NAME}` reads at create time, in order: the
/// sandbox's `containerEnv` (substituted), the image's `ENV`, then for
/// `HOME` the adopted account's home (`runtime::identity::container_home`).
/// A name none of them sets reads as its `${containerEnv:NAME:default}`,
/// else empty, like an unset `localEnv:`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ContainerEnv {
    /// The sandbox's `containerEnv`, its values substituted.
    pub sandbox: BTreeMap<String, String>,
    /// The image's `ENV`, in order (a later entry wins).
    pub image: Vec<(String, String)>,
    /// `HOME` when neither sets it.
    pub home: String,
}

impl ContainerEnv {
    /// `name`'s value, in [`ContainerEnv`]'s order; `None` when none of
    /// them sets it (what `${containerEnv:NAME:default}` falls back on).
    fn get(&self, name: &str) -> Option<String> {
        match self.sandbox.get(name) {
            Some(v) => Some(v.clone()),
            None => self.from_image(name),
        }
    }

    /// `name` from the image's env, else the home fallback.
    fn from_image(&self, name: &str) -> Option<String> {
        match self.image.iter().rev().find(|(k, _)| k == name) {
            Some((_, v)) => Some(v.clone()),
            None if name == "HOME" => Some(self.home.clone()),
            None => None,
        }
    }

    /// Build it from the image's env, the home fallback and the sandbox's
    /// raw `containerEnv`, whose values get the other `${…}` variables of
    /// `ctx` substituted. In those values `${containerEnv:X}` reads only the
    /// image env and the home, as devcontainer's does: `PATH =
    /// "${containerEnv:PATH}:…"` extends the image's `PATH`, and no order
    /// between keys matters.
    pub fn resolve(
        sandbox_env: Option<&BTreeMap<String, String>>,
        image: Vec<(String, String)>,
        home: String,
        ctx: &MountContext,
    ) -> ContainerEnv {
        let mut env = ContainerEnv { sandbox: BTreeMap::new(), image, home };
        let image_only = MountContext { container_env: Some(&env), ..*ctx };
        let resolved = sandbox_env
            .into_iter()
            .flatten()
            .map(|(key, value)| (key.clone(), substitute(value, &image_only)))
            .collect();
        env.sandbox = resolved;
        env
    }
}

/// A mount with variables substituted and defaults applied, ready to hand to
/// `docker run --mount`.
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedMount {
    pub kind: String,
    pub source: Option<String>,
    pub target: String,
    pub readonly: bool,
    /// A `volume` whose source names it after the instance (`${instance}` /
    /// `${devcontainerId}`), so it belongs to that instance alone and `rm`
    /// deletes it. Shared named volumes are never touched.
    pub per_instance: bool,
    /// The unsubstituted source names the instance, whatever the kind: a
    /// bind source devsandbox creates on that ground is the instance's own
    /// (`Instance::bind_dirs`).
    pub instance_source: bool,
}

/// Variables that resolve to the instance id; a volume named with one is
/// per-instance.
pub(crate) const INSTANCE_VARS: [&str; 2] = ["${instance}", "${devcontainerId}"];

impl Mount {
    /// Apply variable substitution and defaults. `bind` mounts require a source.
    pub fn resolve(&self, ctx: &MountContext) -> Result<ResolvedMount> {
        let (kind, source, target, readonly) = match self {
            Mount::Shorthand(s) => parse_shorthand(s)?,
            Mount::Object(o) => (
                o.kind.clone(),
                o.source.clone(),
                o.target.clone(),
                o.readonly.unwrap_or(false),
            ),
        };
        let kind = kind.unwrap_or_else(|| "bind".to_string());
        let instance_source = source
            .as_deref()
            .is_some_and(|s| INSTANCE_VARS.iter().any(|v| s.contains(v)));
        let per_instance = kind == "volume" && instance_source;
        let source = source.map(|s| substitute(&s, ctx));
        let target = substitute(&target, ctx);
        if kind == "bind" && source.is_none() {
            bail!("bind mount to `{target}` is missing a source");
        }
        Ok(ResolvedMount {
            kind,
            source,
            target,
            readonly,
            per_instance,
            instance_source,
        })
    }
}

impl ResolvedMount {
    /// The value for a `docker run --mount <value>` flag.
    pub fn to_arg(&self) -> String {
        let mut arg = format!("type={}", self.kind);
        if let Some(source) = &self.source {
            arg.push_str(&format!(",source={source}"));
        }
        arg.push_str(&format!(",target={}", self.target));
        if self.readonly {
            arg.push_str(",readonly");
        }
        arg
    }
}

pub(crate) type MountParts = (Option<String>, Option<String>, String, bool);

/// Parse a docker `--mount` shorthand (`key=value,…`) into
/// (type, source, target, readonly).
pub(crate) fn parse_shorthand(spec: &str) -> Result<MountParts> {
    let (mut kind, mut source, mut target, mut readonly) = (None, None, None, false);
    for part in spec.split(',') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }
        let (key, value) = match part.split_once('=') {
            Some((k, v)) => (k.trim(), Some(v.trim().to_string())),
            None => (part, None),
        };
        match key {
            "type" => kind = value,
            "source" | "src" => source = value,
            "target" | "destination" | "dst" => target = value,
            "readonly" | "ro" => readonly = value.as_deref() != Some("false"),
            "consistency" | "bind-propagation" => {} // docker hints, no-op here
            other => bail!("unknown mount field `{other}` in `{spec}`"),
        }
    }
    let target = target.with_context(|| format!("mount `{spec}` is missing a target"))?;
    Ok((kind, source, target, readonly))
}

/// Package-manager caches supported by the `caches` field, in a stable order.
pub const SUPPORTED_CACHES: &[&str] = &["pnpm", "cargo", "npm", "yarn", "go", "pip"];

/// Resolve a cache name to `(source subdirectory under shared-volumes, mount
/// target in the container, env vars that must point at the target)`. Returns
/// `None` for an unknown name.
///
/// Targets sit under `/var/cache/devsandbox/`, not a home directory: the env
/// vars are what point each tool at its cache, so no user's home is needed,
/// and a non-root `remoteUser`/`containerUser` can't reach `/root` (0700).
/// The bind source is created on the host, so it is as writable in the
/// container as the workspace mount is.
pub fn known_cache(name: &str) -> Option<(&'static str, &'static str, &'static [&'static str])> {
    Some(match name {
        "pnpm" => (
            "pnpm-store",
            "/var/cache/devsandbox/pnpm-store",
            &["npm_config_store_dir", "pnpm_config_store_dir"],
        ),
        "cargo" => ("cargo", "/var/cache/devsandbox/cargo", &["CARGO_HOME"]),
        "npm" => ("npm", "/var/cache/devsandbox/npm", &["npm_config_cache"]),
        "yarn" => ("yarn", "/var/cache/devsandbox/yarn", &["YARN_CACHE_FOLDER"]),
        "go" => ("go-mod", "/var/cache/devsandbox/go-mod", &["GOMODCACHE"]),
        "pip" => ("pip", "/var/cache/devsandbox/pip", &["PIP_CACHE_DIR"]),
        _ => return None,
    })
}

/// Replace the devcontainer `${…}` variables devsandbox supports; unknown
/// expressions are left verbatim.
pub fn substitute(input: &str, ctx: &MountContext) -> String {
    let mut out = String::new();
    let mut rest = input;
    while let Some(start) = rest.find("${") {
        out.push_str(&rest[..start]);
        let after = &rest[start + 2..];
        match after.find('}') {
            Some(end) => {
                let expr = &after[..end];
                match resolve_var(expr, ctx) {
                    Some(value) => out.push_str(&value),
                    None => out.push_str(&rest[start..start + 2 + end + 1]),
                }
                rest = &after[end + 1..];
            }
            None => {
                out.push_str(&rest[start..]);
                return out;
            }
        }
    }
    out.push_str(rest);
    out
}

fn resolve_var(expr: &str, ctx: &MountContext) -> Option<String> {
    resolve_var_with(
        expr,
        ctx,
        |name| crate::worker_policy::local_env_allowed(Path::new(ctx.config_dir), name),
        |name| std::env::var_os(name).map(|v| v.to_string_lossy().into_owned()),
    )
}

/// [`resolve_var`] over a given `localEnv` gate and host env.
fn resolve_var_with(
    expr: &str,
    ctx: &MountContext,
    local_env_allowed: impl Fn(&str) -> bool,
    local_env: impl Fn(&str) -> Option<String>,
) -> Option<String> {
    if let Some(rest) = expr.strip_prefix("localEnv:") {
        let (name, default) = env_name_and_default(rest);
        // Under a fleet root the config is the control plane's: the worker's env only
        // for names `member.toml` allows, else left verbatim (`run` refuses
        // such a config before this, `worker_policy::Policy::check_config`;
        // this is for what no check saw, e.g. a control plane's `run --branch`).
        if !local_env_allowed(name) {
            return None;
        }
        return Some(local_env(name).unwrap_or_else(|| default.to_string()));
    }
    if let Some(rest) = expr.strip_prefix("containerEnv:") {
        let (name, default) = env_name_and_default(rest);
        return ctx.container_env.map(|env| env.get(name).unwrap_or_else(|| default.to_string()));
    }
    match expr {
        "configDir" => Some(ctx.config_dir.to_string()),
        "localWorkspaceFolder" => Some(ctx.workspace_folder.to_string()),
        "localWorkspaceFolderBasename" => Some(ctx.workspace_folder_basename.to_string()),
        "sharedVolumes" => Some(ctx.shared_volumes.to_string()),
        // devcontainer's stable per-container id (features use it to name
        // their volumes, e.g. docker-in-docker's `/var/lib/docker`). The
        // instance id has the same properties: unique, and stable across
        // rebuilds and renames.
        "instance" | "devcontainerId" => Some(ctx.instance.to_string()),
        _ => None,
    }
}

/// `NAME` and the default of a `localEnv:`/`containerEnv:` body
/// (`NAME[:default]`): the name ends at the first `:`, the default is all
/// the rest, `:`s included (`${localEnv:URL:http://x:1}` defaults to
/// `http://x:1`). devcontainer semantics: a set variable is its value,
/// even empty; an unset one is the default, empty without one.
fn env_name_and_default(body: &str) -> (&str, &str) {
    body.split_once(':').unwrap_or((body, ""))
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Build {
    pub dockerfile: Option<String>,
    pub context: Option<String>,
    pub args: Option<BTreeMap<String, String>>,
    pub target: Option<String>,
    pub cache_from: Option<StringOrList>,
    pub options: Option<Vec<String>>,
}

#[derive(Debug, Deserialize)]
pub struct Customizations {
    pub vscode: Option<VscodeCustomizations>,
    // Customizations for other tools; nothing to validate.
    #[serde(flatten)]
    pub other: Table,
}

#[derive(Debug, Deserialize)]
pub struct VscodeCustomizations {
    pub extensions: Option<Vec<String>>,
    pub settings: Option<Value>,
    #[serde(flatten)]
    pub other: Table,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum StringOrList {
    One(String),
    Many(Vec<String>),
}

impl StringOrList {
    pub fn to_vec(&self) -> Vec<&str> {
        match self {
            Self::One(s) => vec![s],
            Self::Many(v) => v.iter().map(String::as_str).collect(),
        }
    }
}

/// devcontainer lifecycle command: a shell string, an argv array, or a named
/// map of either.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum LifecycleCommand {
    Simple(SimpleCommand),
    Parallel(BTreeMap<String, SimpleCommand>),
}

#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum SimpleCommand {
    Shell(String),
    Args(Vec<String>),
}

impl SimpleCommand {
    fn argv(&self) -> Vec<String> {
        match self {
            Self::Shell(s) => vec!["sh".into(), "-c".into(), s.clone()],
            Self::Args(a) => a.clone(),
        }
    }
}

impl LifecycleCommand {
    /// Argv lists to run, in order. The map form is documented as parallel;
    /// we run its entries sequentially for now.
    pub fn commands(&self) -> Vec<Vec<String>> {
        match self {
            Self::Simple(c) => vec![c.argv()],
            Self::Parallel(map) => map.values().map(SimpleCommand::argv).collect(),
        }
    }
}

/// A sandbox with its `extends` template merged in and validated.
#[derive(Debug)]
pub struct ResolvedSandbox {
    pub name: String,
    pub properties: SandboxProperties,
    /// Stable hash of the merged config, used to detect drift on reuse.
    pub config_hash: String,
}

impl ResolvedSandbox {
    pub fn folder(&self) -> Option<&str> {
        self.properties.folder.as_deref()
    }

    /// Short description of what the sandbox is built from.
    pub fn source(&self) -> String {
        if let Some(image) = &self.properties.image {
            return format!("image {image}");
        }
        if let Some(dockerfile) = self
            .properties
            .build
            .as_ref()
            .and_then(|b| b.dockerfile.as_deref())
        {
            return format!("dockerfile {dockerfile}");
        }
        "?".into()
    }
}

/// How a service is shared. `isolated` (the default) gives every sandbox
/// instance its own container; `global` is a single container shared across the
/// whole config root.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ServiceScope {
    #[default]
    Isolated,
    Global,
}

/// A service definition (`[services.<name>]`). Backed by an `image` or a
/// `build`. Free-form beyond the fields devsandbox acts on; unknown keys are
/// rejected so typos surface.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Service {
    #[serde(default)]
    pub scope: ServiceScope,
    pub image: Option<String>,
    pub build: Option<Build>,
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    #[serde(default)]
    pub ports: Vec<String>,
    #[serde(default)]
    pub command: Option<StringOrList>,
    /// The sandbox key, on a service (a devsandbox extension); in the
    /// service's `config_hash` like every key. Only `gpu` is acted on
    /// (`commands::run::gpu_decision`); the other keys are ignored,
    /// unwarned.
    #[serde(default, rename = "hostRequirements")]
    pub host_requirements: Option<HostRequirements>,
}

/// A validated service with a stable hash of its definition.
#[derive(Debug)]
pub struct ResolvedService {
    pub name: String,
    pub spec: Service,
    pub config_hash: String,
}

impl Config {
    pub fn parse(contents: &str) -> Result<Self> {
        let config: Self = toml::from_str(contents).context("invalid config")?;
        config.validate()
    }

    /// Checks over the whole file rather than one sandbox, run by both
    /// parsers so every consumer sees them.
    fn validate(self) -> Result<Self> {
        for name in self.profiles.keys() {
            check_profile_name(name).context("invalid config")?;
        }
        for name in self.updates.keys() {
            crate::updates::check_name(name).context("invalid config: `updates`")?;
        }
        Ok(self)
    }

    /// YAML lands in the same `toml::Table`s as TOML, so `extends`, merging
    /// and drift hashes behave identically: the same config in either format
    /// hashes the same.
    pub fn parse_yaml(contents: &str) -> Result<Self> {
        // An empty (or comment-only) document is an empty config, as in TOML.
        let config: Option<Self> =
            serde_saphyr::from_str(contents).map_err(|e| anyhow!("{e}")).context("invalid config")?;
        config.unwrap_or_default().validate()
    }

    pub fn resolve_service(&self, name: &str) -> Result<ResolvedService> {
        let table = self
            .services
            .get(name)
            .with_context(|| format!("unknown service `{name}`"))?;
        let config_hash = config_hash(table);
        let spec: Service = table
            .clone()
            .try_into()
            .map_err(|e| anyhow!("service `{name}`: {e}"))?;
        match (&spec.image, &spec.build) {
            (Some(_), Some(_)) => bail!("service `{name}`: set only one of `image` or `build`"),
            (None, None) => bail!("service `{name}`: needs an `image` or a `build`"),
            _ => {}
        }
        Ok(ResolvedService {
            name: name.to_string(),
            spec,
            config_hash,
        })
    }

    pub fn load(dir: &Path) -> Result<Self> {
        let path = find(dir)?.unwrap_or_else(|| dir.join(CONFIG_FILE));
        let contents = std::fs::read_to_string(&path)
            .with_context(|| format!("cannot read {}", path.display()))?;
        let parsed = match path.extension().and_then(|e| e.to_str()) {
            Some("yaml" | "yml") => Self::parse_yaml(&contents),
            _ => Self::parse(&contents),
        };
        parsed.with_context(|| format!("in {}", path.display()))
    }

    pub fn resolve_sandbox(&self, name: &str) -> Result<ResolvedSandbox> {
        let sandbox = self
            .sandboxes
            .get(name)
            .with_context(|| format!("unknown sandbox `{name}`"))?;

        let mut properties = self.resolve_extends(sandbox, &mut Vec::new())?;
        properties.remove("extends");

        let config_hash = sandbox_hash(&properties);
        let mut properties: SandboxProperties = properties
            .try_into()
            .map_err(|e| anyhow!("sandbox `{name}`: {e}"))?;
        if let Some(forwards) = &mut properties.forward_ports {
            // `extends` concatenates arrays, so a template and its sandbox may
            // both list an entry; one forward each is enough.
            let mut seen = std::collections::BTreeSet::new();
            forwards.retain(|f| seen.insert(f.key()));
            let services = properties.services.as_deref().unwrap_or_default();
            for f in forwards.iter() {
                if let Some(svc) = &f.service
                    && !services.contains(svc)
                {
                    bail!("sandbox `{name}`: forwardPorts entry `{}` names `{svc}`, which isn't in its `services`", f.key());
                }
            }
        }
        if let Some(profiles) = &mut properties.profiles {
            // Concatenated under `extends` too: first occurrence keeps its rank.
            let mut seen = std::collections::BTreeSet::new();
            profiles.retain(|p| seen.insert(p.clone()));
            if let Some(p) = profiles.iter().find(|p| !self.profiles.contains_key(*p)) {
                bail!("sandbox `{name}`: profile `{p}` in `profiles` isn't declared (no [profiles.{p}])");
            }
        }
        for (kind, access) in properties.access.iter_mut().flatten() {
            crate::credentials::claim::check_kind(kind).with_context(|| format!("sandbox `{name}`: `access.{kind}`"))?;
            if let Some(c) = &access.credential {
                crate::credentials::check_name(c).with_context(|| format!("sandbox `{name}`: `access.{kind}.credential`"))?;
            }
            if let Some(a) = &access.as_ {
                crate::credentials::claim::TokenKind::parse(a).with_context(|| format!("sandbox `{name}`: `access.{kind}.as`"))?;
            }
            for list in [&mut access.scopes, &mut access.ask, &mut access.repos, &mut access.branches, &mut access.orgs] {
                let mut seen = std::collections::BTreeSet::new();
                list.retain(|s| seen.insert(s.clone()));
            }
        }

        Ok(ResolvedSandbox {
            name: name.to_string(),
            properties,
            config_hash,
        })
    }

    /// The raw `[sandbox.<name>]` table exactly as written (including `extends`),
    /// for the config explorer's "original" view.
    pub fn sandbox_table(&self, name: &str) -> Result<&Table> {
        self.sandboxes
            .get(name)
            .with_context(|| format!("unknown sandbox `{name}`"))
    }

    /// The merged-but-untyped sandbox table: `extends` resolved and dropped, so
    /// it round-trips to TOML for the config explorer's "resolved" view. Unlike
    /// [`Self::resolve_sandbox`] this skips typed validation. Returns the merged
    /// table plus its config hash.
    pub fn resolved_table(&self, name: &str) -> Result<(Table, String)> {
        let sandbox = self.sandbox_table(name)?;
        let mut properties = self.resolve_extends(sandbox, &mut Vec::new())?;
        properties.remove("extends");
        let hash = sandbox_hash(&properties);
        Ok((properties, hash))
    }

    /// Sandbox `name` as the config explorer shows it (`sandboxes.get`): its
    /// own table and the merged one as TOML text, plus the merged one's hash.
    /// A side that fails carries its error as the text (and no hash), so the
    /// view still shows why.
    #[cfg_attr(not(unix), allow(dead_code))] // only the dashboard and daemon (unix) use it
    pub fn sandbox_text(&self, name: &str) -> SandboxText {
        let original = match self.sandbox_table(name) {
            Ok(t) => table_text(t),
            Err(e) => format!("{e:#}"),
        };
        let (resolved, hash) = match self.resolved_table(name) {
            Ok((t, hash)) => (table_text(&t), hash),
            Err(e) => (format!("{e:#}"), String::new()),
        };
        SandboxText { original, resolved, hash }
    }

    /// The raw `[services.<name>]` table as TOML text (`services.get`; services
    /// don't `extends`, so it's also the resolved one), `None` for an unknown one.
    #[cfg_attr(not(unix), allow(dead_code))] // only the dashboard and daemon (unix) use it
    pub fn service_text(&self, name: &str) -> Option<String> {
        self.services.get(name).map(table_text)
    }

    /// Resolve a table's `extends` into a fully-merged table: referenced
    /// templates first (left-to-right, each with its own `extends` resolved
    /// recursively), then the table's own body on top. `stack` tracks the active
    /// resolution path for cycle detection.
    fn resolve_extends(&self, table: &Table, stack: &mut Vec<String>) -> Result<Table> {
        self.merge_extends(table, stack, &mut Vec::new())
    }

    /// The templates `table`'s `extends` reaches, in merge order (each after
    /// the templates it extends itself; one reached twice is listed twice):
    /// the table that sets a scalar last wins it, `table` itself coming after
    /// all of them. Fails as [`Self::resolve_sandbox`] would (unknown
    /// template, cycle, bad `extends`).
    #[cfg_attr(not(test), allow(dead_code))] // config_identity's, wired by identity steps 13–14
    pub fn extends_chain(&self, table: &Table) -> Result<Vec<String>> {
        let mut chain = Vec::new();
        self.merge_extends(table, &mut Vec::new(), &mut chain)?;
        Ok(chain)
    }

    /// [`Self::resolve_extends`], also pushing each template it merges onto
    /// `chain` ([`Self::extends_chain`]).
    fn merge_extends(&self, table: &Table, stack: &mut Vec<String>, chain: &mut Vec<String>) -> Result<Table> {
        let names = match table.get("extends") {
            None => Vec::new(),
            Some(Value::String(name)) => vec![name.clone()],
            Some(Value::Array(items)) => items
                .iter()
                .map(|v| {
                    v.as_str().map(str::to_string).ok_or_else(|| {
                        anyhow!("`extends` array must contain template names (strings)")
                    })
                })
                .collect::<Result<Vec<_>>>()?,
            Some(other) => bail!(
                "`extends` must be a template name or an array of names, got {}",
                other.type_str()
            ),
        };

        let mut merged = Table::new();
        for name in names {
            if stack.contains(&name) {
                bail!("cyclic `extends`: {} -> {name}", stack.join(" -> "));
            }
            let template = self
                .templates
                .get(&name)
                .with_context(|| format!("extends unknown template `{name}`"))?;
            stack.push(name.clone());
            let resolved = self.merge_extends(template, stack, chain)?;
            stack.pop();
            chain.push(name);
            merged = deep_merge(merged, resolved);
        }

        let mut body = table.clone();
        body.remove("extends");
        Ok(deep_merge(merged, body))
    }

    /// The profiles `sandbox`'s instances may be in, in preference order: its
    /// `profiles` if set, else every declared profile by name; empty when
    /// the config declares none.
    pub fn allowed_profiles(&self, sandbox: &ResolvedSandbox) -> Vec<String> {
        match &sandbox.properties.profiles {
            Some(listed) => listed.clone(),
            None => self.profiles.keys().cloned().collect(),
        }
    }

    pub fn resolve_all(&self) -> Result<Vec<ResolvedSandbox>> {
        let all = self
            .sandboxes
            .keys()
            .map(|name| self.resolve_sandbox(name))
            .collect::<Result<Vec<_>>>()?;
        for sandbox in &all {
            self.validate_dispatcher(sandbox)?;
        }
        Ok(all)
    }

    /// Cross-sandbox check `resolve_sandbox` can't do alone: every `spawn`
    /// entry names a sandbox of this config (or is `"*"`).
    pub fn validate_dispatcher(&self, sandbox: &ResolvedSandbox) -> Result<()> {
        let Some(dispatcher) = &sandbox.properties.dispatcher else {
            return Ok(());
        };
        for entry in &dispatcher.spawn {
            if entry != Dispatcher::ANY && !self.sandboxes.contains_key(entry) {
                bail!(
                    "sandbox `{}`: `dispatcher.spawn` names unknown sandbox `{entry}`",
                    sandbox.name
                );
            }
        }
        Ok(())
    }
}

/// Stable FNV-1a hash of arbitrary text, rendered as 16 hex chars.
pub fn short_hash(text: &str) -> String {
    fnv_hex(text.as_bytes())
}

/// [`short_hash`] over raw bytes (feature folders may hold binaries).
fn fnv_hex(bytes: &[u8]) -> String {
    let mut h: u64 = 0xcbf29ce484222325;
    for &b in bytes {
        h ^= b as u64;
        h = h.wrapping_mul(0x100000001b3);
    }
    format!("{h:016x}")
}

/// Short hash of a `build`'s dockerfile *contents*, or `""` when there is no
/// build, no `dockerfile` key, or the file can't be read.
///
/// Hashing the bytes (not the path in the merged config, which `config_hash`
/// already covers) is what lets a dockerfile edit register as drift: the path
/// is unchanged, only the contents moved. Limitation: only the dockerfile file
/// itself is hashed — the build context is not, so edits to it go undetected.
/// Sandboxes also fold in local feature folders: [`sandbox_build_hash`].
pub fn build_hash(dir: &Path, build: Option<&Build>) -> String {
    let Some(dockerfile) = build.and_then(|b| b.dockerfile.as_deref()) else {
        return String::new();
    };
    match std::fs::read(dir.join(dockerfile)) {
        Ok(bytes) => short_hash(&String::from_utf8_lossy(&bytes)),
        Err(_) => String::new(),
    }
}

/// A sandbox's `build_hash` label: [`build_hash`] plus the contents of its
/// enabled local-folder features, so editing a local feature's `install.sh`
/// registers as drift. Without local features it equals [`build_hash`], so
/// existing containers don't drift on upgrade. OCI feature contents are not
/// hashed (their refs are in the config hash; tags are cached).
pub fn sandbox_build_hash(dir: &Path, props: &SandboxProperties) -> String {
    let build = build_hash(dir, props.build.as_ref());
    match crate::features::local_features_fingerprint(dir, props.features.as_ref()) {
        None => build,
        Some(mut bytes) => {
            bytes.extend_from_slice(build.as_bytes());
            fnv_hex(&bytes)
        }
    }
}

/// Stable hash of a merged config table. `Table` is a `BTreeMap`, so its TOML
/// serialization is key-sorted and deterministic across runs.
fn config_hash(table: &Table) -> String {
    short_hash(&toml::to_string(table).unwrap_or_default())
}

/// [`config_hash`] of a merged sandbox table minus the keys that apply without
/// recreating the container (`autostart`, `dispatcher`, `inbox`, `placement`,
/// the host-side `forwardPorts`, `profiles`, `access` and `ssh-keys`), so
/// changing them isn't drift.
fn sandbox_hash(table: &Table) -> String {
    let mut table = table.clone();
    table.remove("autostart");
    table.remove("placement");
    table.remove("dispatcher");
    table.remove("inbox");
    table.remove("forwardPorts");
    table.remove("profiles");
    table.remove("access");
    table.remove("ssh-keys");
    if let Some(toml::Value::Table(folders)) = table.get_mut("folders") {
        normalize_folders(folders);
    }
    config_hash(&table)
}

/// Rewrite `folders` table entries that only restate the default
/// (`{ path = "x" }`, `{ path = "x", worktree = "auto" }`) to the plain string
/// `"x"`, so spelling an entry either way isn't drift. `always`/`never` stay
/// tables: they change the mount, applied on the next `rebuild`.
fn normalize_folders(folders: &mut Table) {
    for (_, entry) in folders.iter_mut() {
        let toml::Value::Table(t) = entry else { continue };
        let Some(toml::Value::String(path)) = t.get("path") else { continue };
        let default_mode = match t.get("worktree") {
            None => true,
            Some(toml::Value::String(mode)) => mode == "auto",
            Some(_) => false,
        };
        if default_mode && t.len() == 1 + usize::from(t.contains_key("worktree")) {
            *entry = toml::Value::String(path.clone());
        }
    }
}

/// Deep merge: nested tables merge recursively, arrays concatenate
/// (base first, then `over`), scalars are replaced by `over`. Concatenating
/// arrays lets a sandbox add to a template's `mounts`/`extensions` without
/// restating them (devcontainer merge semantics). Overriding an inherited
/// mount happens later, at `run`: mounts collapse to the last entry per target
/// (`commands::run::mounts::last_wins_by_target`).
fn deep_merge(base: Table, over: Table) -> Table {
    let mut merged = base;
    for (key, value) in over {
        match (merged.remove(&key), value) {
            (Some(Value::Table(base_table)), Value::Table(over_table)) => {
                merged.insert(key, Value::Table(deep_merge(base_table, over_table)));
            }
            (Some(Value::Array(mut base_arr)), Value::Array(over_arr)) => {
                base_arr.extend(over_arr);
                merged.insert(key, Value::Array(base_arr));
            }
            (_, value) => {
                merged.insert(key, value);
            }
        }
    }
    merged
}

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

    const EXAMPLE: &str = r#"
[services.database]
image = "postgres"

[template.base-sandbox]
caches = ["pnpm"]
build.args = { A = "1", B = "2" }

[sandbox.repository-1]
extends = "base-sandbox"
folder = "../repository-1"
image = "node-22"

[sandbox.repository-2]
extends = "base-sandbox"
folder = "../repository-2"
services = ["database"]
build.dockerfile = "./Dockerfile"
build.args = { B = "3" }
"#;

    #[test]
    fn parses_example() {
        let config = Config::parse(EXAMPLE).unwrap();
        assert_eq!(config.services.len(), 1);
        assert_eq!(config.templates.len(), 1);
        assert_eq!(config.sandboxes.len(), 2);
    }

    const EXAMPLE_YAML: &str = r#"
services:
  database:
    image: postgres

template:
  base-sandbox:
    caches: [pnpm]
    build:
      args: { A: "1", B: "2" }

sandbox:
  repository-1:
    extends: base-sandbox
    folder: ../repository-1
    image: node-22
  repository-2:
    extends: base-sandbox
    folder: ../repository-2
    services: [database]
    build:
      dockerfile: ./Dockerfile
      args: { B: "3" }
"#;

    #[test]
    fn yaml_resolves_and_hashes_like_toml() {
        let toml = Config::parse(EXAMPLE).unwrap();
        let yaml = Config::parse_yaml(EXAMPLE_YAML).unwrap();
        for name in ["repository-1", "repository-2"] {
            let (t, t_hash) = toml.resolved_table(name).unwrap();
            let (y, y_hash) = yaml.resolved_table(name).unwrap();
            assert_eq!(t, y, "{name}");
            assert_eq!(t_hash, y_hash, "{name}");
        }
        assert_eq!(
            toml.resolve_service("database").unwrap().config_hash,
            yaml.resolve_service("database").unwrap().config_hash
        );
    }

    #[test]
    fn yaml_empty_and_invalid() {
        assert!(Config::parse_yaml("").unwrap().sandboxes.is_empty());
        assert!(Config::parse_yaml("# nothing yet\n").unwrap().sandboxes.is_empty());
        assert!(Config::parse_yaml("sandbox: [").is_err());
        // TOML has no null; resolving would otherwise see a key TOML can't express.
        assert!(Config::parse_yaml("sandbox: {s: {image: ~}}").is_err());
    }

    #[test]
    fn a_misspelled_top_level_table_is_an_error() {
        let toml = Config::parse("[sandboxx.a]\nimage = \"x\"\n").unwrap_err();
        assert!(format!("{toml:#}").contains("unknown field `sandboxx`"), "{toml:#}");
        let yaml = Config::parse_yaml("sandboxx: {a: {image: x}}\n").unwrap_err();
        assert!(format!("{yaml:#}").contains("sandboxx"), "{yaml:#}");
    }

    fn scratch(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("devsandbox-cfgfile-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn load_picks_format_by_extension() {
        let dir = scratch("ext");
        std::fs::write(dir.join("devsandboxes.yml"), EXAMPLE_YAML).unwrap();
        assert_eq!(Config::load(&dir).unwrap().sandboxes.len(), 2);
        std::fs::write(dir.join("devsandboxes.toml"), EXAMPLE).unwrap();
        let err = format!("{:#}", Config::load(&dir).unwrap_err());
        assert!(err.contains("devsandboxes.toml, devsandboxes.yml"), "{err}");
        std::fs::remove_file(dir.join("devsandboxes.yml")).unwrap();
        assert_eq!(Config::load(&dir).unwrap().sandboxes.len(), 2);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn legacy_config_is_read_then_migrated() {
        let dir = scratch("legacy");
        std::fs::write(dir.join("config.toml"), EXAMPLE).unwrap();
        assert_eq!(Config::load(&dir).unwrap().sandboxes.len(), 2);
        assert_eq!(migrate_legacy(&dir).unwrap(), Some(dir.join(CONFIG_FILE)));
        assert!(!dir.join("config.toml").exists());
        assert_eq!(Config::load(&dir).unwrap().sandboxes.len(), 2);
        assert_eq!(migrate_legacy(&dir).unwrap(), None);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn unrelated_config_toml_is_left_alone() {
        let dir = scratch("unrelated");
        std::fs::write(dir.join("config.toml"), "baseURL = \"https://example.org\"\n").unwrap();
        assert_eq!(migrate_legacy(&dir).unwrap(), None);
        assert!(dir.join("config.toml").exists());
        assert!(Config::load(&dir).is_err());
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn resolve_merges_template() {
        let config = Config::parse(EXAMPLE).unwrap();
        let sandbox = config.resolve_sandbox("repository-1").unwrap();
        assert_eq!(sandbox.folder(), Some("../repository-1"));
        assert_eq!(sandbox.source(), "image node-22");
        assert_eq!(sandbox.properties.caches.as_deref(), Some(&["pnpm".to_string()][..]));
    }

    #[test]
    fn resolve_deep_merges_nested_tables() {
        let config = Config::parse(EXAMPLE).unwrap();
        let sandbox = config.resolve_sandbox("repository-2").unwrap();
        assert_eq!(sandbox.source(), "dockerfile ./Dockerfile");
        let args = sandbox.properties.build.as_ref().unwrap().args.as_ref().unwrap();
        // A comes from the template, B is overridden by the sandbox.
        assert_eq!(args["A"], "1");
        assert_eq!(args["B"], "3");
    }

    #[test]
    fn folders_parses_and_merges_through_extends() {
        let config = Config::parse(
            r#"
[template.base]
folders = { "/workspaces/.shared" = "../.shared" }

[sandbox.app]
extends = "base"
folder = "../app"
image = "img"
folders = { "/workspaces/docs" = "../docs", "/workspaces/lib" = { path = "../lib", worktree = "always" }, "/workspaces/scratch" = { path = "../scratch", worktree = "never" }, "/workspaces/other" = { path = "../other" } }
"#,
        )
        .unwrap();
        let sandbox = config.resolve_sandbox("app").unwrap();
        assert!(!sandbox.config_hash.is_empty());
        let folders = sandbox.properties.folders.as_ref().unwrap();
        let entry = |k: &str| (folders[k].path(), folders[k].worktree_mode());
        assert_eq!(entry("/workspaces/.shared"), ("../.shared", FolderWorktree::Auto));
        assert_eq!(entry("/workspaces/docs"), ("../docs", FolderWorktree::Auto));
        assert_eq!(entry("/workspaces/lib"), ("../lib", FolderWorktree::Always));
        assert_eq!(entry("/workspaces/scratch"), ("../scratch", FolderWorktree::Never));
        assert_eq!(entry("/workspaces/other"), ("../other", FolderWorktree::Auto));
    }

    #[test]
    fn folders_reject_bad_table_entries() {
        for bad in [
            r#"{ path = "../lib", worktree = "sometimes" }"#,
            r#"{ path = "../lib", wroktree = "never" }"#,
            r#"{ worktree = "never" }"#,
            "1",
        ] {
            let result = Config::parse(&format!(
                "[sandbox.app]\nfolder = \"../app\"\nimage = \"img\"\nfolders = {{ \"/workspaces/lib\" = {bad} }}\n"
            ))
            .and_then(|c| c.resolve_sandbox("app"));
            let err = format!("{:#}", result.unwrap_err());
            assert!(err.contains("host dir string"), "{bad}: {err}");
        }
    }

    #[test]
    fn folders_worktree_mode_changes_config_hash() {
        let hash = |entry: &str| {
            Config::parse(&format!(
                "[sandbox.app]\nfolder = \"../app\"\nimage = \"img\"\nfolders = {{ \"/workspaces/lib\" = {entry} }}\n"
            ))
            .unwrap()
            .resolve_sandbox("app")
            .unwrap()
            .config_hash
        };
        let plain = hash(r#""../lib""#);
        assert_ne!(plain, hash(r#"{ path = "../lib", worktree = "never" }"#));
        assert_ne!(plain, hash(r#"{ path = "../lib", worktree = "always" }"#));
        // Restating the default in table form is not drift.
        assert_eq!(plain, hash(r#"{ path = "../lib" }"#));
        assert_eq!(plain, hash(r#"{ path = "../lib", worktree = "auto" }"#));
        assert_ne!(plain, hash(r#"{ path = "../other" }"#));
    }

    #[test]
    fn config_hash_is_stable_and_sensitive() {
        let config = Config::parse(EXAMPLE).unwrap();
        let a = config.resolve_sandbox("repository-1").unwrap().config_hash;
        let b = config.resolve_sandbox("repository-1").unwrap().config_hash;
        assert_eq!(a, b, "same config must hash identically");
        let c = config.resolve_sandbox("repository-2").unwrap().config_hash;
        assert_ne!(a, c, "different configs must hash differently");
    }

    fn identity_props(body: &str) -> Result<SandboxProperties> {
        let config = Config::parse(&format!("[sandbox.app]\nfolder = \"../app\"\n{body}"))?;
        Ok(config.resolve_sandbox("app")?.properties)
    }

    #[test]
    fn identity_parses_and_hint_applies() {
        let cases = [
            ("", Identity::Host),
            ("identity = \"host\"\n", Identity::Host),
            ("identity = \"image\"\n", Identity::Image),
            ("updateRemoteUserUID = true\n", Identity::Host),
            ("updateRemoteUserUID = false\n", Identity::Image),
            // An explicit `identity` wins over the hint.
            ("identity = \"host\"\nupdateRemoteUserUID = false\n", Identity::Host),
            ("identity = \"image\"\nupdateRemoteUserUID = true\n", Identity::Image),
        ];
        for (body, want) in cases {
            let props = identity_props(body).unwrap();
            assert_eq!(props.identity(), want, "{body:?}");
            assert!(props.ignored().is_empty(), "{body:?}: {:?}", props.ignored());
        }
    }

    #[test]
    fn identity_rejects_other_values() {
        let err = format!("{:#}", identity_props("identity = \"root\"\n").unwrap_err());
        assert!(err.contains("host") && err.contains("image"), "{err}");
        assert!(identity_props("updateRemoteUserUID = \"false\"\n").is_err());
    }

    #[test]
    fn identity_parses_from_yaml() {
        let props = |yaml: &str| {
            Config::parse_yaml(yaml).unwrap().resolve_sandbox("app").unwrap().properties.identity()
        };
        assert_eq!(props("sandbox:\n  app:\n    identity: image\n"), Identity::Image);
        assert_eq!(props("sandbox:\n  app:\n    updateRemoteUserUID: false\n"), Identity::Image);
        assert_eq!(props("sandbox:\n  app:\n    identity: host\n"), Identity::Host);
        let toml = Config::parse("[sandbox.app]\nidentity = \"image\"\n").unwrap();
        let yaml = Config::parse_yaml("sandbox:\n  app:\n    identity: image\n").unwrap();
        assert_eq!(toml.resolved_table("app").unwrap(), yaml.resolved_table("app").unwrap());
    }

    #[test]
    fn identity_and_hint_change_config_hash() {
        let hash = |body: &str| {
            Config::parse(&format!("[sandbox.app]\nfolder = \"../app\"\n{body}"))
                .unwrap()
                .resolve_sandbox("app")
                .unwrap()
                .config_hash
        };
        let plain = hash("");
        assert_eq!(plain, hash(""));
        assert_ne!(plain, hash("identity = \"image\"\n"));
        assert_ne!(hash("identity = \"host\"\n"), hash("identity = \"image\"\n"));
        assert_ne!(plain, hash("updateRemoteUserUID = false\n"));
        assert_ne!(hash("updateRemoteUserUID = true\n"), hash("updateRemoteUserUID = false\n"));
    }

    #[test]
    fn userns_defaults_on_and_changes_config_hash() {
        assert!(identity_props("").unwrap().userns());
        assert!(identity_props("userns = true\n").unwrap().userns());
        assert!(!identity_props("userns = false\n").unwrap().userns());
        assert!(identity_props("userns = \"no\"\n").is_err());
        let hash = |body: &str| {
            Config::parse(&format!("[sandbox.app]\nfolder = \"../app\"\n{body}"))
                .unwrap()
                .resolve_sandbox("app")
                .unwrap()
                .config_hash
        };
        assert_ne!(hash(""), hash("userns = false\n"));
        assert_ne!(hash("userns = true\n"), hash("userns = false\n"));
    }

    fn autostart_of(value: &str) -> Result<Option<Autostart>> {
        let config = Config::parse(&format!(
            "[sandbox.app]\nfolder = \"../app\"\nautostart = {value}\n"
        ))?;
        Ok(config.resolve_sandbox("app")?.properties.autostart)
    }

    #[test]
    fn autostart_parses_bool_and_runtime() {
        assert_eq!(autostart_of("true").unwrap(), Some(Autostart::Devsandbox));
        assert_eq!(autostart_of("false").unwrap(), Some(Autostart::Off));
        assert_eq!(autostart_of("\"runtime\"").unwrap(), Some(Autostart::Runtime));
        let unset = Config::parse(EXAMPLE).unwrap().resolve_sandbox("repository-1").unwrap();
        assert_eq!(unset.properties.autostart, None);
    }

    #[test]
    fn autostart_rejects_other_values() {
        for bad in ["\"bogus\"", "1"] {
            let err = format!("{:#}", autostart_of(bad).unwrap_err());
            assert!(err.contains("runtime") && err.contains("true"), "{bad}: {err}");
        }
    }

    #[test]
    fn autostart_excluded_from_config_hash() {
        let base = "[sandbox.app]\nfolder = \"../app\"\n";
        let plain = Config::parse(base).unwrap();
        let with = Config::parse(&format!("{base}autostart = true\n")).unwrap();
        let hash = plain.resolve_sandbox("app").unwrap().config_hash;
        assert_eq!(hash, with.resolve_sandbox("app").unwrap().config_hash);
        let (table, table_hash) = with.resolved_table("app").unwrap();
        assert_eq!(table_hash, hash);
        assert!(table.contains_key("autostart"));
    }

    #[test]
    fn dispatcher_parses_and_rejects_unknown_keys() {
        let config = Config::parse(
            "[sandbox.d]\nfolder = \".\"\ndispatcher = { spawn = [\"web\", \"*\"], max-instances = 3 }\n\
             [sandbox.web]\nfolder = \".\"\n",
        )
        .unwrap();
        let d = config.resolve_sandbox("d").unwrap().properties.dispatcher.unwrap();
        assert_eq!(d.spawn, vec!["web", "*"]);
        assert_eq!(d.max_instances, Some(3));
        assert_eq!(d.cap(), 3);
        assert_eq!(Dispatcher::default().cap(), Dispatcher::DEFAULT_MAX_INSTANCES);
        assert!(d.may_spawn("anything"));
        assert_eq!(config.resolve_sandbox("web").unwrap().properties.dispatcher, None);

        let bad = Config::parse("[sandbox.d]\ndispatcher = { spawn = [], max = 3 }\n").unwrap();
        let err = format!("{:#}", bad.resolve_sandbox("d").unwrap_err());
        assert!(err.contains("max"), "{err}");
        // snake_case spelling is rejected too: the key is `max-instances`.
        let bad = Config::parse("[sandbox.d]\ndispatcher = { max_instances = 3 }\n").unwrap();
        assert!(bad.resolve_sandbox("d").is_err());
    }

    #[test]
    fn dispatcher_spawn_list_is_checked_by_resolve_all() {
        let ok = Config::parse(
            "[sandbox.d]\ndispatcher = { spawn = [\"web\", \"*\", \"d\"] }\n[sandbox.web]\n",
        )
        .unwrap();
        assert!(ok.resolve_all().is_ok());
        let d = ok.resolve_sandbox("d").unwrap().properties.dispatcher.unwrap();
        assert!(d.may_spawn("web") && d.may_spawn("d"));

        let bad = Config::parse("[sandbox.d]\ndispatcher = { spawn = [\"nope\"] }\n").unwrap();
        let err = bad.resolve_all().unwrap_err().to_string();
        assert!(err.contains("unknown sandbox `nope`"), "{err}");
        let only = bad.resolve_sandbox("d").unwrap().properties.dispatcher.unwrap();
        assert!(!only.may_spawn("web"));
    }

    #[test]
    fn dispatcher_excluded_from_config_hash() {
        let base = "[sandbox.app]\nfolder = \"../app\"\n";
        let plain = Config::parse(base).unwrap();
        let with = Config::parse(&format!("{base}dispatcher = {{ spawn = [\"app\"] }}\n")).unwrap();
        let hash = plain.resolve_sandbox("app").unwrap().config_hash;
        assert_eq!(hash, with.resolve_sandbox("app").unwrap().config_hash);
        assert_eq!(with.resolved_table("app").unwrap().1, hash);
    }

    #[test]
    fn inbox_parses_merges_and_is_not_drift() {
        let config = Config::parse(
            "[template.owner]\ninbox = true\n\
             [sandbox.a]\nfolder = \".\"\nextends = [\"owner\"]\n\
             [sandbox.b]\nfolder = \".\"\nextends = [\"owner\"]\ninbox = false\n\
             [sandbox.c]\nfolder = \".\"\n",
        )
        .unwrap();
        assert_eq!(config.resolve_sandbox("a").unwrap().properties.inbox, Some(true));
        assert_eq!(config.resolve_sandbox("b").unwrap().properties.inbox, Some(false));
        assert_eq!(config.resolve_sandbox("c").unwrap().properties.inbox, None);
        // Toggling it is not drift.
        let hash = |s| config.resolve_sandbox(s).unwrap().config_hash;
        assert_eq!(hash("a"), hash("c"));
        assert_eq!(hash("b"), hash("c"));
        let bad = Config::parse("[sandbox.a]\ninbox = \"yes\"\n").unwrap();
        assert!(bad.resolve_sandbox("a").is_err());
    }

    #[test]
    fn placement_parses_merges_and_is_not_drift() {
        let config = Config::parse(
            "[template.pinned]\nplacement = \"home\"\n\
             [sandbox.a]\nfolder = \".\"\nextends = [\"pinned\"]\n\
             [sandbox.b]\nfolder = \".\"\nplacement = \"home\"\n\
             [sandbox.c]\nfolder = \".\"\n",
        )
        .unwrap();
        let placement = |s| config.resolve_sandbox(s).unwrap().properties.placement;
        assert_eq!(placement("a"), Some(Placement::Home));
        assert_eq!(placement("b"), Some(Placement::Home));
        assert_eq!(placement("c"), None);
        let hash = |s| config.resolve_sandbox(s).unwrap().config_hash;
        assert_eq!(hash("a"), hash("c"));
        assert_eq!(hash("b"), hash("c"));
        let bad = Config::parse("[sandbox.a]\nplacement = \"anywhere\"\n").unwrap();
        let err = format!("{:#}", bad.resolve_sandbox("a").unwrap_err());
        assert!(err.contains("anywhere") && err.contains("home"), "{err}");
    }

    #[test]
    fn forward_ports_excluded_from_config_hash() {
        let base = "[sandbox.app]\nfolder = \"../app\"\n";
        let plain = Config::parse(base).unwrap();
        let with = Config::parse(&format!("{base}forwardPorts = [3000]\n")).unwrap();
        let hash = plain.resolve_sandbox("app").unwrap().config_hash;
        assert_eq!(hash, with.resolve_sandbox("app").unwrap().config_hash);
        assert_eq!(with.resolved_table("app").unwrap().1, hash);
    }

    #[test]
    fn forward_port_entries_parse() {
        let fp = |host, service: Option<&str>, port| ForwardPort { host, service: service.map(str::to_string), port };
        assert_eq!(ForwardPort::parse("3000"), Ok(fp(None, None, 3000)));
        assert_eq!(ForwardPort::parse("8080:3000"), Ok(fp(Some(8080), None, 3000)));
        assert_eq!(ForwardPort::parse("db:5432"), Ok(fp(None, Some("db"), 5432)));
        assert_eq!(ForwardPort::parse("15432:db:5432"), Ok(fp(Some(15432), Some("db"), 5432)));
        for bad in ["", "0", "x", "70000", "8080:0", ":3000", "1:2:3", "db:", "a:b:c:d"] {
            assert!(ForwardPort::parse(bad).is_err(), "{bad}");
        }
        assert_eq!(fp(Some(15432), Some("db"), 5432).key(), "15432:db:5432");
        assert_eq!(fp(Some(15432), Some("db"), 5432).base(), 15432);
        assert_eq!(fp(None, Some("db"), 5432).base(), 5432);
    }

    #[test]
    fn forward_ports_accept_numbers_and_strings_dedupe_and_check_services() {
        let config = Config::parse(
            r#"
[services.db]
image = "postgres"

[template.t]
forwardPorts = [3000]

[sandbox.app]
extends = "t"
services = ["db"]
forwardPorts = ["3000", "8080:3000", "db:5432"]

[sandbox.bad]
forwardPorts = ["db:5432"]

[sandbox.worse]
forwardPorts = [true]
"#,
        )
        .unwrap();
        let app = config.resolve_sandbox("app").unwrap();
        let keys: Vec<String> = app.properties.forward_ports.as_ref().unwrap().iter().map(ForwardPort::key).collect();
        assert_eq!(keys, ["3000", "8080:3000", "db:5432"]);
        assert!(app.properties.ignored().is_empty());
        let err = config.resolve_sandbox("bad").unwrap_err().to_string();
        assert!(err.contains("isn't in its `services`"), "{err}");
        assert!(config.resolve_sandbox("worse").is_err());
    }

    #[test]
    fn profiles_excluded_from_config_hash() {
        let base = "[profiles.work]\n[sandbox.app]\nfolder = \"../app\"\n";
        let plain = Config::parse(base).unwrap();
        let with = Config::parse(&format!("{base}profiles = [\"work\"]\n")).unwrap();
        let hash = plain.resolve_sandbox("app").unwrap().config_hash;
        assert_eq!(hash, with.resolve_sandbox("app").unwrap().config_hash);
        assert_eq!(with.resolved_table("app").unwrap().1, hash);
    }

    #[test]
    fn updates_parse_in_toml_and_yaml_and_stay_out_of_config_hash() {
        use crate::updates::Interval;
        use std::time::Duration;
        let base = "[sandbox.app]\nfolder = \"../app\"\n";
        let toml = Config::parse(&format!("{base}[updates]\ngh = \"1d\"\nnode = \"never\"\n")).unwrap();
        let want = [
            ("gh".to_string(), Interval::Every(Duration::from_secs(86400))),
            ("node".to_string(), Interval::Never),
        ];
        assert_eq!(toml.updates, BTreeMap::from(want.clone()));
        let yaml = Config::parse_yaml("updates:\n  gh: 1d\n  node: never\n").unwrap();
        assert_eq!(yaml.updates, BTreeMap::from(want));
        let hash = Config::parse(base).unwrap().resolve_sandbox("app").unwrap().config_hash;
        assert_eq!(toml.resolve_sandbox("app").unwrap().config_hash, hash);

        for bad in ["[updates]\ngh = \"0d\"\n", "[updates]\ngh = 7\n", "[updates]\nGH = \"1d\"\n"] {
            assert!(Config::parse(bad).is_err(), "{bad}");
        }
        let e = format!("{:#}", Config::parse_yaml("updates:\n  gh: 1m\n").unwrap_err());
        assert!(e.contains("isn't a duration"), "{e}");
    }

    #[test]
    fn access_parses_merges_and_is_excluded_from_config_hash() {
        let config = Config::parse(
            r#"
[template.base.access.sentry]
scopes = ["issues.read"]

[sandbox.web]
extends = "base"
folder = "../web"

[sandbox.web.access.sentry]
scopes = ["releases.write", "issues.read"]
ask = ["uploads"]
credential = "sentry-work"
orgs = ["acme", "acme"]

[sandbox.web.access.github]
repos = ["acme/design-system"]
branches = ["release/*"]
as = "user"

[sandbox.plain]
extends = "base"
folder = "../web"
"#,
        )
        .unwrap();
        let web = config.resolve_sandbox("web").unwrap();
        let access = web.properties.access.as_ref().unwrap();
        assert_eq!(
            access["sentry"],
            Access {
                scopes: vec!["issues.read".into(), "releases.write".into()],
                ask: vec!["uploads".into()],
                credential: Some("sentry-work".into()),
                orgs: vec!["acme".into()],
                ..Access::default()
            }
        );
        assert_eq!(access["github"].as_.as_deref(), Some("user"));
        assert_eq!(access["github"].repos, ["acme/design-system"]);
        assert!(web.properties.ignored().is_empty());
        let plain = config.resolve_sandbox("plain").unwrap();
        assert_eq!(plain.properties.access.as_ref().unwrap()["sentry"].scopes, ["issues.read"]);

        let bare = Config::parse("[sandbox.web]\nfolder = \"../web\"\n").unwrap();
        assert_eq!(bare.resolve_sandbox("web").unwrap().config_hash, web.config_hash);
        assert_eq!(config.resolved_table("web").unwrap().1, web.config_hash);

        for (bad, wants) in [
            ("[sandbox.s.access.sentry]\nscope = [\"x\"]\n", "scope"),
            ("[sandbox.s.access.Sentry]\n", "the kind must be"),
            ("[sandbox.s.access.sentry]\ncredential = \"a.b\"\n", "credential name"),
            ("[sandbox.s.access.github]\nas = \"bot\"\n", "`user` or `app`"),
        ] {
            let err = match Config::parse(bad) {
                Err(e) => format!("{e:#}"),
                Ok(c) => format!("{:#}", c.resolve_sandbox("s").unwrap_err()),
            };
            assert!(err.contains(wants), "{bad}: {err}");
        }
    }

    #[test]
    fn ssh_keys_parse_concatenate_and_are_excluded_from_config_hash() {
        let mut blob = Vec::new();
        for part in [&b"ssh-ed25519"[..], &[7u8; 32][..]] {
            blob.extend_from_slice(&(part.len() as u32).to_be_bytes());
            blob.extend_from_slice(part);
        }
        let line = format!("ssh-ed25519 {} me@laptop", String::from_utf8(crate::broker::redact::base64(&blob)).unwrap());
        let fp = fingerprint_b64(&blob);
        let config = Config::parse(&format!(
            r#"
[template.base]
ssh-keys = [{{ key = "SHA256:{fp}", destinations = ["gitlab.example.com", "[git.corp]:2222"] }}]

[sandbox.web]
extends = "base"
folder = "../web"
ssh-keys = [{{ key = "{line}", signing-only = true }}]
"#
        ))
        .unwrap();
        let web = config.resolve_sandbox("web").unwrap();
        let keys = web.properties.ssh_keys.as_ref().unwrap();
        assert_eq!(keys.len(), 2);
        assert_eq!(keys[0].key, KeyRef::Fingerprint(fp.clone()));
        assert_eq!(keys[0].destinations.as_deref(), Some(&["gitlab.example.com".to_string(), "[git.corp]:2222".into()][..]));
        assert!(!keys[0].signing_only);
        assert_eq!(keys[1].key, KeyRef::Blob(blob.clone()));
        assert!(keys[1].signing_only && keys[1].destinations.is_none());
        assert!(keys.iter().all(|k| k.key.matches(&blob)));
        assert!(!keys[0].key.matches(b"other"));

        let bare = Config::parse("[sandbox.web]\nfolder = \"../web\"\n").unwrap();
        assert_eq!(bare.resolve_sandbox("web").unwrap().config_hash, web.config_hash);

        for (bad, wants) in [
            (format!("key = \"SHA256:{fp}\", signing-only = true, destinations = [\"x\"]"), "takes no `destinations`"),
            (format!("key = \"SHA256:{fp}\", destinations = []"), "is empty"),
            (format!("key = \"SHA256:{fp}\", destinations = [\"-oProxyCommand=x\"]"), "as `known_hosts` names it"),
            ("key = \"SHA256:short\"".into(), "isn't a SHA256 fingerprint"),
            ("key = \"me@laptop\"".into(), "neither"),
            (line.replace("ssh-ed25519 ", "ssh-rsa "), "isn't a `ssh-rsa` key"),
            (format!("key = \"SHA256:{fp}\", comment = \"x\""), "comment"),
        ] {
            let bad = if bad.starts_with("key") { bad } else { format!("key = \"{bad}\"") };
            let toml = format!("[sandbox.s]\nfolder = \".\"\nssh-keys = [{{ {bad} }}]\n");
            let err = match Config::parse(&toml) {
                Err(e) => format!("{e:#}"),
                Ok(c) => format!("{:#}", c.resolve_sandbox("s").unwrap_err()),
            };
            assert!(err.contains(wants), "{bad}: {err}");
        }
    }

    #[test]
    fn profiles_dedupe_and_must_be_declared() {
        let config = Config::parse(
            r#"
[profiles.work]
[profiles.personal]

[template.t]
profiles = ["work"]

[sandbox.app]
extends = "t"
profiles = ["work", "personal"]

[sandbox.bad]
profiles = ["work", "x"]
"#,
        )
        .unwrap();
        let app = config.resolve_sandbox("app").unwrap();
        assert_eq!(app.properties.profiles.as_deref().unwrap(), ["work", "personal"]);
        assert!(app.properties.ignored().is_empty());
        let err = config.resolve_sandbox("bad").unwrap_err().to_string();
        assert_eq!(err, "sandbox `bad`: profile `x` in `profiles` isn't declared (no [profiles.x])");

        let none = Config::parse("[sandbox.a]\nprofiles = [\"work\"]\n").unwrap();
        let err = none.resolve_sandbox("a").unwrap_err().to_string();
        assert!(err.contains("no [profiles.work]"), "{err}");
    }

    #[test]
    fn profile_tables_and_names_are_checked_at_parse() {
        let err = format!("{:#}", Config::parse("[profiles.work]\nbrowser = \"x\"\n").unwrap_err());
        assert!(err.contains("browser"), "{err}");
        for bad in ["Work", "-x", "_x", ".x", "a b", "a/b", "é"] {
            let toml = format!("[profiles.\"{bad}\"]\n");
            let err = format!("{:#}", Config::parse(&toml).unwrap_err());
            assert!(err.contains("profile name"), "{bad}: {err}");
            let yaml = format!("profiles: {{\"{bad}\": {{}}}}\n");
            assert!(Config::parse_yaml(&yaml).is_err(), "{bad}");
        }
        for good in ["work", "0", "a_b.c-d"] {
            Config::parse(&format!("[profiles.\"{good}\"]\n")).unwrap();
        }
        let yaml = Config::parse_yaml("profiles:\n  work: {}\n  personal: {}\n").unwrap();
        assert_eq!(yaml.profiles.keys().collect::<Vec<_>>(), ["personal", "work"]);
    }

    #[test]
    fn allowed_profiles_listed_or_every_declared() {
        let config = Config::parse(
            r#"
[profiles.work]
[profiles.personal]

[sandbox.listed]
profiles = ["work"]

[sandbox.all]
"#,
        )
        .unwrap();
        let allowed = |name| config.allowed_profiles(&config.resolve_sandbox(name).unwrap());
        assert_eq!(allowed("listed"), ["work"]);
        assert_eq!(allowed("all"), ["personal", "work"]);

        let bare = Config::parse("[sandbox.s]\n").unwrap();
        assert!(bare.allowed_profiles(&bare.resolve_sandbox("s").unwrap()).is_empty());
    }

    #[test]
    fn build_hash_none_and_missing_are_empty() {
        let dir = std::env::temp_dir();
        assert_eq!(build_hash(&dir, None), "");
        let no_dockerfile = Build::default();
        assert_eq!(build_hash(&dir, Some(&no_dockerfile)), "");
        let missing = Build {
            dockerfile: Some("does-not-exist-xyz.Dockerfile".into()),
            ..Build::default()
        };
        assert_eq!(build_hash(&dir, Some(&missing)), "");
    }

    #[test]
    fn build_hash_tracks_dockerfile_contents() {
        let dir = std::env::temp_dir().join(format!("devsandbox-bh-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("Dockerfile");
        let build = Build {
            dockerfile: Some("Dockerfile".into()),
            ..Build::default()
        };

        std::fs::write(&path, "FROM alpine\n").unwrap();
        let first = build_hash(&dir, Some(&build));
        assert!(!first.is_empty());
        assert_eq!(first, build_hash(&dir, Some(&build)));
        // A content change moves the hash even though the path is unchanged.
        std::fs::write(&path, "FROM alpine\nRUN echo hi\n").unwrap();
        assert_ne!(first, build_hash(&dir, Some(&build)));

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn sandbox_build_hash_tracks_local_features_only() {
        let dir = std::env::temp_dir().join(format!("devsandbox-sbh-{}", std::process::id()));
        let feature = dir.join("features/toolkit");
        std::fs::create_dir_all(&feature).unwrap();
        std::fs::write(feature.join("devcontainer-feature.json"), r#"{"id": "toolkit"}"#).unwrap();
        std::fs::write(feature.join("install.sh"), "#!/bin/sh\n").unwrap();
        let hash = |body: &str| {
            let sandbox = Config::parse(body).unwrap().resolve_sandbox("app").unwrap();
            sandbox_build_hash(&dir, &sandbox.properties)
        };
        let local = r#"
            [template.base.features."./features/toolkit"]
            ripgrep = true
            [sandbox.app]
            extends = "base"
            image = "alpine"
            folder = "app"
        "#;
        let first = hash(local);
        assert!(!first.is_empty());
        // Unrelated config edits (and option values) leave it alone.
        assert_eq!(first, hash(&local.replace("folder = \"app\"", "folder = \"other\"\nremoteUser = \"x\"")));
        assert_eq!(first, hash(&local.replace("ripgrep = true", "ripgrep = false")));
        // Editing the feature folder moves it.
        std::fs::write(feature.join("install.sh"), "#!/bin/sh\napk add ripgrep\n").unwrap();
        assert_ne!(first, hash(local));
        // OCI-only sandboxes keep the plain `build_hash` ("" for an image).
        let oci = r#"
            [sandbox.app]
            image = "alpine"
            [sandbox.app.features."ghcr.io/devcontainers/features/node:1"]
        "#;
        assert_eq!(hash(oci), "");

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn resolved_table_merges_and_drops_extends() {
        let config = Config::parse(EXAMPLE).unwrap();
        let (table, hash) = config.resolved_table("repository-2").unwrap();
        assert!(!table.contains_key("extends"));
        assert_eq!(table["folder"].as_str(), Some("../repository-2"));
        assert_eq!(table["caches"].as_array().unwrap().len(), 1); // from template
        // Nested build.args deep-merged: A from template, B overridden.
        let args = table["build"].as_table().unwrap()["args"].as_table().unwrap();
        assert_eq!(args["A"].as_str(), Some("1"));
        assert_eq!(args["B"].as_str(), Some("3"));
        assert_eq!(hash, config.resolve_sandbox("repository-2").unwrap().config_hash);
    }

    #[test]
    fn resolved_table_unknown_sandbox_errors() {
        let config = Config::parse(EXAMPLE).unwrap();
        assert!(config.resolved_table("nope").is_err());
    }

    #[test]
    fn extends_chain_is_merge_order() {
        let config = Config::parse(
            "[template.a]\n[template.b]\nextends = \"a\"\n[template.c]\nextends = [\"b\", \"a\"]\n\
             [template.x]\nextends = \"y\"\n[template.y]\nextends = \"x\"\n",
        )
        .unwrap();
        let chain = |name: &str| config.extends_chain(&config.templates[name]);
        assert_eq!(chain("a").unwrap(), Vec::<String>::new());
        assert_eq!(chain("c").unwrap(), ["a", "b", "a"]);
        assert!(format!("{:#}", chain("x").unwrap_err()).contains("cyclic"));
    }

    #[test]
    fn sandbox_without_extends() {
        let config = Config::parse("[sandbox.solo]\nimage = \"alpine\"").unwrap();
        let sandbox = config.resolve_sandbox("solo").unwrap();
        assert_eq!(sandbox.source(), "image alpine");
    }

    #[test]
    fn unknown_template_errors() {
        let config = Config::parse("[sandbox.bad]\nextends = \"nope\"").unwrap();
        let err = config.resolve_sandbox("bad").unwrap_err().to_string();
        assert!(err.contains("unknown template `nope`"), "{err}");
    }

    #[test]
    fn non_string_extends_errors() {
        let config = Config::parse("[sandbox.bad]\nextends = 3").unwrap();
        assert!(config.resolve_sandbox("bad").is_err());
    }

    #[test]
    fn unknown_property_errors() {
        let config = Config::parse("[sandbox.bad]\nimag = \"alpine\"").unwrap();
        let err = config.resolve_sandbox("bad").unwrap_err().to_string();
        assert!(err.contains("imag"), "{err}");
    }

    #[test]
    fn unknown_property_from_template_errors() {
        let config = Config::parse(
            "[template.t]\nfowardPorts = [3000]\n[sandbox.bad]\nextends = \"t\"",
        )
        .unwrap();
        let err = config.resolve_sandbox("bad").unwrap_err().to_string();
        assert!(err.contains("fowardPorts"), "{err}");
    }

    #[test]
    fn unimplemented_properties_are_flagged_ignored() {
        let config = Config::parse(
            r#"
[sandbox.s]
image = "alpine"
appPort = [3000]
runArgs = ["--gpus", "all"]
hostRequirements = { gpu = { cores = 2, memory = "8gb" }, cpus = 4, storage = "32gb" }
customizations.vscode.settings = { "editor.formatOnSave" = true }
customizations.jetbrains.plugins = ["x"]
"#,
        )
        .unwrap();
        let sandbox = config.resolve_sandbox("s").unwrap();
        assert_eq!(
            sandbox.properties.ignored(),
            vec![
                "appPort",
                "runArgs",
                "hostRequirements.gpu.cores",
                "hostRequirements.gpu.memory",
                "hostRequirements.cpus",
                "hostRequirements.storage",
                "customizations.vscode.settings",
                "customizations.jetbrains",
            ]
        );
    }

    fn host_requirements(body: &str) -> Result<HostRequirements> {
        let props = identity_props(&format!("[sandbox.app.hostRequirements]\n{body}"))?;
        Ok(props.host_requirements.unwrap_or_default())
    }

    #[test]
    fn host_requirements_gpu_forms() {
        let gpu = |body: &str| host_requirements(body).unwrap();
        assert_eq!(gpu("gpu = true").gpu, Some(GpuRequirement::Required));
        assert_eq!(gpu("gpu = true").gpu_need(), Some(GpuNeed::Required));
        assert_eq!(gpu("gpu = false").gpu, Some(GpuRequirement::No));
        assert_eq!(gpu("gpu = false").gpu_need(), None);
        for body in ["gpu = false", "gpu = true", "gpu = \"optional\"", "gpu = {}"] {
            assert!(gpu(body).set_keys().is_empty(), "{body}: `gpu` is acted on");
        }
        assert_eq!(gpu("gpu = \"optional\"").gpu_need(), Some(GpuNeed::Optional));
        let min = gpu("gpu = { cores = 2, memory = \"8gb\" }");
        assert_eq!(
            min.gpu,
            Some(GpuRequirement::Min { cores: Some(2), memory: Some("8gb".into()) })
        );
        assert_eq!(min.gpu_need(), Some(GpuNeed::Required));
        assert_eq!(gpu("gpu = {}").gpu_need(), Some(GpuNeed::Required));
        assert_eq!(gpu("cpus = 4").gpu_need(), None);
        assert_eq!(identity_props("").unwrap().host_requirements, None);
    }

    #[test]
    fn host_requirements_rejects_bad_values() {
        let err = |body: &str| format!("{:#}", host_requirements(body).unwrap_err());
        let bad = err("gpu = \"always\"");
        assert!(bad.contains("always") && bad.contains("optional"), "{bad}");
        assert!(err("gpus = true").contains("gpus"));
        assert!(err("gpu = { core = 2 }").contains("core"));
        assert!(err("gpu = 1").contains("optional"));
    }

    #[test]
    fn host_requirements_gpu_merges_through_extends() {
        let config = Config::parse(
            r#"
[template.t]
hostRequirements = { gpu = true, cpus = 2 }
[sandbox.s]
extends = "t"
image = "alpine"
hostRequirements.gpu = "optional"
"#,
        )
        .unwrap();
        let host = config.resolve_sandbox("s").unwrap().properties.host_requirements.unwrap();
        assert_eq!(host.gpu_need(), Some(GpuNeed::Optional));
        assert!(host.cpus.is_some(), "template's other keys stay");
    }

    #[test]
    fn host_requirements_gpu_is_drift() {
        let hash = sandbox_hash_of;
        assert_ne!(hash(""), hash("hostRequirements.gpu = true"));
        assert_ne!(hash("hostRequirements.gpu = true"), hash("hostRequirements.gpu = \"optional\""));
    }

    fn sandbox_hash_of(body: &str) -> String {
        let config = Config::parse(&format!("[sandbox.app]\nfolder = \"../app\"\n{body}")).unwrap();
        config.resolve_sandbox("app").unwrap().config_hash
    }

    #[test]
    fn implemented_properties_are_not_ignored() {
        let config = Config::parse(
            r#"
[sandbox.s]
image = "alpine"
containerEnv = { FOO = "bar" }
postCreateCommand = "npm install"
customizations.vscode.extensions = ["rust-lang.rust-analyzer"]
privileged = true
placement = "home"
hostRequirements.gpu = true
"#,
        )
        .unwrap();
        let sandbox = config.resolve_sandbox("s").unwrap();
        assert!(sandbox.properties.ignored().is_empty());
        assert_eq!(sandbox.properties.privileged, Some(true));
        assert_eq!(
            sandbox.properties.vscode_extensions(),
            Some(&["rust-lang.rust-analyzer".to_string()][..])
        );
    }

    #[test]
    fn feature_option_forms_parse() {
        let config = Config::parse(
            r#"
[sandbox.s]
image = "alpine"

[sandbox.s.features]
"ghcr.io/devcontainers/features/node:1" = { version = "lts" }
"ghcr.io/devcontainers/features/go:1" = "1.22"
"ghcr.io/devcontainers/features/git:1" = true
"#,
        )
        .unwrap();
        let features = config.resolve_sandbox("s").unwrap().properties.features.unwrap();
        match &features["ghcr.io/devcontainers/features/node:1"] {
            FeatureOptions::Options(opts) => {
                assert_eq!(opts["version"].as_str(), Some("lts"));
            }
            other => panic!("expected options table, got {other:?}"),
        }
        match &features["ghcr.io/devcontainers/features/go:1"] {
            FeatureOptions::Version(v) => assert_eq!(v, "1.22"),
            other => panic!("expected version string, got {other:?}"),
        }
        match &features["ghcr.io/devcontainers/features/git:1"] {
            FeatureOptions::Enabled(b) => assert!(b),
            other => panic!("expected bool, got {other:?}"),
        }
    }

    #[test]
    fn features_are_not_ignored() {
        let config = Config::parse(
            r#"
[sandbox.s]
image = "alpine"
features = { "ghcr.io/x/y:1" = true }
"#,
        )
        .unwrap();
        let sandbox = config.resolve_sandbox("s").unwrap();
        assert!(sandbox.properties.ignored().is_empty());
        assert!(!SandboxProperties::default().ignored().contains(&"features".to_string()));
    }

    #[test]
    fn features_deep_merge_across_template() {
        let config = Config::parse(
            r#"
[template.feat-base]
[template.feat-base.features]
"ghcr.io/devcontainers/features/common-utils:2" = true
"ghcr.io/devcontainers/features/node:1" = { version = "18" }

[sandbox.s]
extends = "feat-base"
image = "alpine"
[sandbox.s.features]
"ghcr.io/devcontainers/features/go:1" = "1.22"
"ghcr.io/devcontainers/features/node:1" = { version = "lts" }
"#,
        )
        .unwrap();
        let features = config.resolve_sandbox("s").unwrap().properties.features.unwrap();
        // common-utils comes from the template.
        assert!(matches!(
            features["ghcr.io/devcontainers/features/common-utils:2"],
            FeatureOptions::Enabled(true)
        ));
        // go is added by the sandbox.
        assert!(matches!(
            &features["ghcr.io/devcontainers/features/go:1"],
            FeatureOptions::Version(v) if v == "1.22"
        ));
        // node is overridden by the sandbox.
        match &features["ghcr.io/devcontainers/features/node:1"] {
            FeatureOptions::Options(opts) => assert_eq!(opts["version"].as_str(), Some("lts")),
            other => panic!("expected options table, got {other:?}"),
        }
    }

    #[test]
    fn lifecycle_command_forms() {
        let config = Config::parse(
            r#"
[sandbox.s]
image = "alpine"
postCreateCommand = "npm install"
postStartCommand = ["node", "server.js"]
onCreateCommand = { b = "make", a = ["cargo", "build"] }
"#,
        )
        .unwrap();
        let props = config.resolve_sandbox("s").unwrap().properties;
        assert_eq!(
            props.post_create_command.unwrap().commands(),
            vec![vec!["sh", "-c", "npm install"]]
        );
        assert_eq!(
            props.post_start_command.unwrap().commands(),
            vec![vec!["node", "server.js"]]
        );
        assert_eq!(
            props.on_create_command.unwrap().commands(),
            vec![vec!["cargo", "build"], vec!["sh", "-c", "make"]]
        );
    }

    fn ctx() -> MountContext<'static> {
        MountContext {
            config_dir: "/cfg",
            workspace_folder: "/home/u/repo",
            workspace_folder_basename: "repo",
            shared_volumes: "/cfg/shared-volumes",
            instance: "repo-2",
            container_env: None,
        }
    }

    fn image_env() -> Vec<(String, String)> {
        vec![("PATH".into(), "/usr/bin:/bin".into()), ("LANG".into(), "C".into()), ("LANG".into(), "C.UTF-8".into())]
    }

    #[test]
    fn container_env_order_and_home_fallback() {
        let sandbox = BTreeMap::from([("LANG".into(), "en_US.UTF-8".into())]);
        let env = ContainerEnv { sandbox, image: image_env(), home: "/home/node".into() };
        assert_eq!(env.get("LANG").as_deref(), Some("en_US.UTF-8"));
        assert_eq!(env.get("PATH").as_deref(), Some("/usr/bin:/bin"));
        assert_eq!(env.get("HOME").as_deref(), Some("/home/node"));
        assert_eq!(env.get("UNSET"), None);
        // The image's HOME beats the fallback; a later image entry wins.
        let mut image = image_env();
        image.push(("HOME".into(), "/srv".into()));
        let env = ContainerEnv { image, ..env };
        assert_eq!(env.get("HOME").as_deref(), Some("/srv"));
        assert_eq!(ContainerEnv { sandbox: BTreeMap::new(), ..env }.get("LANG").as_deref(), Some("C.UTF-8"));
    }

    #[test]
    fn container_env_in_mounts_only_with_a_context() {
        let m = Mount::Shorthand("type=volume,source=claude-${instance},target=${containerEnv:HOME}/.claude".into());
        // `ls`, the snapshot: verbatim, not an error.
        assert_eq!(m.resolve(&ctx()).unwrap().target, "${containerEnv:HOME}/.claude");
        let env = ContainerEnv { home: "/home/vscode".into(), ..Default::default() };
        let with = MountContext { container_env: Some(&env), ..ctx() };
        assert_eq!(m.resolve(&with).unwrap().target, "/home/vscode/.claude");
    }

    #[test]
    fn container_env_values_resolve_against_the_image_only() {
        let raw = BTreeMap::from([
            ("CLAUDE_CONFIG_DIR".into(), "${containerEnv:HOME}/.claude".into()),
            ("TOOLS_PATH".into(), "${containerEnv:PATH}:/opt/bin".into()),
            ("WHERE".into(), "${instance}@${configDir}".into()),
        ]);
        let env = ContainerEnv::resolve(Some(&raw), image_env(), "/home/node".into(), &ctx());
        assert_eq!(env.sandbox["CLAUDE_CONFIG_DIR"], "/home/node/.claude");
        assert_eq!(env.sandbox["TOOLS_PATH"], "/usr/bin:/bin:/opt/bin");
        assert_eq!(env.sandbox["WHERE"], "repo-2@/cfg");
        // Later lookups (mounts, remoteEnv) see the substituted values.
        assert_eq!(env.get("TOOLS_PATH").as_deref(), Some("/usr/bin:/bin:/opt/bin"));
        let none = ContainerEnv::resolve(None, Vec::new(), "/root".into(), &ctx());
        assert!(none.sandbox.is_empty());
    }

    #[test]
    fn container_env_values_read_the_image_not_each_other() {
        // Its own key: the image's value (devcontainer's PATH idiom), the home.
        let path = BTreeMap::from([
            ("PATH".into(), "${containerEnv:PATH}:/opt/bin".into()),
            ("HOME".into(), "${containerEnv:HOME}".into()),
        ]);
        let env = ContainerEnv::resolve(Some(&path), image_env(), "/root".into(), &ctx());
        assert_eq!(env.sandbox["PATH"], "/usr/bin:/bin:/opt/bin");
        assert_eq!(env.sandbox["HOME"], "/root");
        // Another containerEnv key isn't seen: no order between keys.
        let other = BTreeMap::from([("A".into(), "x".into()), ("B".into(), "pre-${containerEnv:A}".into())]);
        let env = ContainerEnv::resolve(Some(&other), Vec::new(), "/root".into(), &ctx());
        assert_eq!(env.sandbox["B"], "pre-");
    }

    #[test]
    fn substitutes_shared_volumes_and_instance() {
        let m = Mount::Shorthand(
            "source=${sharedVolumes}/agent/${instance},target=/root/.agent,type=bind".into(),
        );
        let resolved = m.resolve(&ctx()).unwrap();
        assert_eq!(resolved.source.as_deref(), Some("/cfg/shared-volumes/agent/repo-2"));
        assert_eq!(resolved.target, "/root/.agent");
        assert!(!resolved.per_instance, "binds are never per-instance volumes");
        assert!(resolved.instance_source);
        let shared = Mount::Shorthand("source=${sharedVolumes}/agent,target=/a,type=bind".into());
        assert!(!shared.resolve(&ctx()).unwrap().instance_source);
    }

    #[test]
    fn devcontainer_id_is_the_instance_and_marks_volume_per_instance() {
        // docker-in-docker's feature mount, object form.
        let m = Mount::Object(MountObject {
            kind: Some("volume".into()),
            source: Some("dind-var-lib-docker-${devcontainerId}".into()),
            target: "/var/lib/docker".into(),
            readonly: None,
        });
        let resolved = m.resolve(&ctx()).unwrap();
        assert_eq!(resolved.source.as_deref(), Some("dind-var-lib-docker-repo-2"));
        assert!(resolved.per_instance);
        let m = Mount::Shorthand("type=volume,source=cache-${instance},target=/c".into());
        assert!(m.resolve(&ctx()).unwrap().per_instance);
        // A shared named volume is not the instance's to delete.
        let m = Mount::Shorthand("type=volume,source=pnpm-store,target=/p".into());
        assert!(!m.resolve(&ctx()).unwrap().per_instance);
    }

    #[test]
    fn mount_shorthand_resolves_and_substitutes() {
        let config = Config::parse(
            r#"
[sandbox.s]
image = "alpine"
mounts = ["source=${configDir}/shared-volumes/cargo,target=/root/.cargo,type=bind"]
"#,
        )
        .unwrap();
        let props = config.resolve_sandbox("s").unwrap().properties;
        assert!(props.ignored().is_empty());
        let resolved = props.mounts.as_ref().unwrap()[0].resolve(&ctx()).unwrap();
        assert_eq!(resolved.source.as_deref(), Some("/cfg/shared-volumes/cargo"));
        assert_eq!(resolved.target, "/root/.cargo");
        assert_eq!(resolved.kind, "bind");
        assert_eq!(
            resolved.to_arg(),
            "type=bind,source=/cfg/shared-volumes/cargo,target=/root/.cargo"
        );
    }

    #[test]
    fn mount_object_form_with_readonly() {
        let config = Config::parse(
            r#"
[sandbox.s]
image = "alpine"
mounts = [{ source = "${localWorkspaceFolder}/x", target = "/x", readonly = true }]
"#,
        )
        .unwrap();
        let props = config.resolve_sandbox("s").unwrap().properties;
        let resolved = props.mounts.as_ref().unwrap()[0].resolve(&ctx()).unwrap();
        assert_eq!(resolved.source.as_deref(), Some("/home/u/repo/x"));
        assert!(resolved.readonly);
        assert_eq!(resolved.to_arg(), "type=bind,source=/home/u/repo/x,target=/x,readonly");
    }

    #[test]
    fn mount_localenv_expands_from_host() {
        // PATH is reliably set; verify substitution reads the host env.
        let expected = format!("type=bind,source={}/c,target=/c", std::env::var("PATH").unwrap());
        let config = Config::parse(
            "[sandbox.s]\nimage = \"alpine\"\nmounts = [\"source=${localEnv:PATH}/c,target=/c\"]",
        )
        .unwrap();
        let props = config.resolve_sandbox("s").unwrap().properties;
        let resolved = props.mounts.as_ref().unwrap()[0].resolve(&ctx()).unwrap();
        assert_eq!(resolved.to_arg(), expected);
    }

    #[test]
    fn local_env_default_applies_only_when_unset() {
        let env = |name: &str| match name {
            "SET" => Some("v".to_string()),
            "EMPTY" => Some(String::new()),
            _ => None,
        };
        let allow_all = |_: &str| true;
        let r = |expr: &str| resolve_var_with(expr, &ctx(), allow_all, env);
        assert_eq!(r("localEnv:SET").as_deref(), Some("v"));
        assert_eq!(r("localEnv:SET:d").as_deref(), Some("v"));
        // Set to empty is set: devcontainer's `typeof env === 'string'`.
        assert_eq!(r("localEnv:EMPTY:d").as_deref(), Some(""));
        assert_eq!(r("localEnv:UNSET:d").as_deref(), Some("d"));
        assert_eq!(r("localEnv:UNSET").as_deref(), Some(""));
        assert_eq!(r("localEnv:UNSET:").as_deref(), Some(""));
        assert_eq!(r("localEnv:UNSET:http://h:8080/x").as_deref(), Some("http://h:8080/x"));
        // Through `substitute`, against the real host env.
        assert_eq!(
            substitute("${localEnv:DEVSANDBOX_TEST_SURELY_UNSET:fall:back}/x", &ctx()),
            "fall:back/x"
        );
        assert_eq!(substitute("${localEnv:PATH:d}", &ctx()), std::env::var("PATH").unwrap());
    }

    #[test]
    fn local_env_gate_sees_the_name_and_refusal_stays_verbatim() {
        let env = |_: &str| Some("secret".to_string());
        let gate = |name: &str| {
            assert!(!name.contains(':'), "gate got `{name}`");
            name == "OK"
        };
        assert_eq!(resolve_var_with("localEnv:OK:d", &ctx(), gate, env).as_deref(), Some("secret"));
        assert_eq!(resolve_var_with("localEnv:GH:d", &ctx(), gate, env), None);
        assert_eq!(resolve_var_with("localEnv:GH", &ctx(), gate, env), None);
    }

    #[test]
    fn container_env_default_applies_only_when_unset() {
        let sandbox = BTreeMap::from([("EMPTY".into(), String::new())]);
        let env = ContainerEnv { sandbox, image: image_env(), home: "/home/node".into() };
        let with = MountContext { container_env: Some(&env), ..ctx() };
        assert_eq!(substitute("${containerEnv:LANG:d}", &with), "C.UTF-8");
        assert_eq!(substitute("${containerEnv:EMPTY:d}", &with), "");
        assert_eq!(substitute("${containerEnv:HOME:d}", &with), "/home/node");
        assert_eq!(substitute("${containerEnv:UNSET:a:b}", &with), "a:b");
        assert_eq!(substitute("${containerEnv:UNSET}", &with), "");
        // No context yet: verbatim, default and all.
        assert_eq!(substitute("${containerEnv:UNSET:d}", &ctx()), "${containerEnv:UNSET:d}");
    }

    #[test]
    fn mount_bind_without_source_errors() {
        let config =
            Config::parse("[sandbox.s]\nimage = \"alpine\"\nmounts = [\"target=/x,type=bind\"]")
                .unwrap();
        let props = config.resolve_sandbox("s").unwrap().properties;
        assert!(props.mounts.as_ref().unwrap()[0].resolve(&ctx()).is_err());
    }

    #[test]
    fn mount_unknown_variable_left_verbatim() {
        assert_eq!(substitute("${nope}/x", &ctx()), "${nope}/x");
        assert_eq!(substitute("a/${configDir}/b", &ctx()), "a//cfg/b");
    }

    #[test]
    fn arrays_concatenate_on_merge() {
        let config = Config::parse(
            r#"
[template.base]
mounts = ["source=/a,target=/a,type=bind"]
customizations.vscode.extensions = ["a.one"]

[sandbox.s]
extends = "base"
image = "alpine"
mounts = ["source=/b,target=/b,type=bind"]
customizations.vscode.extensions = ["b.two"]
"#,
        )
        .unwrap();
        let props = config.resolve_sandbox("s").unwrap().properties;
        assert_eq!(props.mounts.as_ref().unwrap().len(), 2);
        assert_eq!(
            props.vscode_extensions(),
            Some(&["a.one".to_string(), "b.two".to_string()][..])
        );
    }

    #[test]
    fn persist_shell_history_parses_and_merges() {
        let config = Config::parse(
            r#"
[template.base]
persist-shell-history = true

[sandbox.s]
extends = "base"
image = "alpine"
"#,
        )
        .unwrap();
        let props = config.resolve_sandbox("s").unwrap().properties;
        assert_eq!(props.persist_shell_history, Some(true));
        assert!(props.ignored().is_empty());
    }

    #[test]
    fn worktree_branch_parses_and_is_not_ignored() {
        let config = Config::parse(
            r#"
[sandbox.s]
image = "alpine"
worktree-branch = "feat/${instance}"
"#,
        )
        .unwrap();
        let props = config.resolve_sandbox("s").unwrap().properties;
        assert_eq!(props.worktree_branch.as_deref(), Some("feat/${instance}"));
        assert!(props.ignored().is_empty());
    }

    #[test]
    fn worktree_branch_merges_through_template() {
        let config = Config::parse(
            r#"
[template.base]
worktree-branch = "team/${instance}"

[sandbox.s]
extends = "base"
image = "alpine"
"#,
        )
        .unwrap();
        let props = config.resolve_sandbox("s").unwrap().properties;
        assert_eq!(props.worktree_branch.as_deref(), Some("team/${instance}"));
    }

    #[test]
    fn worktree_base_parses_and_is_not_ignored() {
        let config = Config::parse(
            r#"
[sandbox.s]
image = "alpine"
worktree-base = "origin/develop"
"#,
        )
        .unwrap();
        let props = config.resolve_sandbox("s").unwrap().properties;
        assert_eq!(props.worktree_base.as_deref(), Some("origin/develop"));
        assert!(props.ignored().is_empty());
    }

    #[test]
    fn worktree_include_and_link_concatenate_through_template() {
        let config = Config::parse(
            r#"
[template.base]
worktree-include = [".vscode/tasks.json"]
worktree-link = [".env"]

[sandbox.s]
extends = "base"
image = "alpine"
worktree-include = ["!.vscode/tasks.json"]
worktree-link = [".env.local"]
"#,
        )
        .unwrap();
        let props = config.resolve_sandbox("s").unwrap().properties;
        assert_eq!(
            props.worktree_include.as_deref(),
            Some(&[".vscode/tasks.json".to_string(), "!.vscode/tasks.json".to_string()][..])
        );
        assert_eq!(
            props.worktree_link.as_deref(),
            Some(&[".env".to_string(), ".env.local".to_string()][..])
        );
        assert!(props.ignored().is_empty());
    }

    #[test]
    fn shell_rc_concatenates_through_template() {
        let config = Config::parse(
            r#"
[template.base]
shell-rc = ["${configDir}/shell/aliases.sh"]

[sandbox.s]
extends = "base"
image = "alpine"
shell-rc = ["./env.sh"]
"#,
        )
        .unwrap();
        let props = config.resolve_sandbox("s").unwrap().properties;
        assert_eq!(
            props.shell_rc.as_deref(),
            Some(&["${configDir}/shell/aliases.sh".to_string(), "./env.sh".to_string()][..])
        );
        assert!(props.ignored().is_empty());
    }

    #[test]
    fn extends_list_merges_left_to_right() {
        let config = Config::parse(
            r#"
[template.node]
image = "node"
containerEnv = { A = "1" }
customizations.vscode.extensions = ["node.ext"]

[template.rust]
containerEnv = { B = "2" }
customizations.vscode.extensions = ["rust.ext"]

[sandbox.s]
extends = ["node", "rust"]
folder = "."
"#,
        )
        .unwrap();
        let props = config.resolve_sandbox("s").unwrap().properties;
        assert_eq!(props.image.as_deref(), Some("node"));
        let env = props.container_env.as_ref().unwrap();
        assert_eq!(env["A"], "1");
        assert_eq!(env["B"], "2");
        assert_eq!(
            props.vscode_extensions(),
            Some(&["node.ext".to_string(), "rust.ext".to_string()][..])
        );
    }

    #[test]
    fn extends_resolves_recursively() {
        let config = Config::parse(
            r#"
[template.base]
image = "alpine"
containerEnv = { BASE = "1" }

[template.mid]
extends = "base"
containerEnv = { MID = "2" }

[sandbox.s]
extends = "mid"
folder = "."
"#,
        )
        .unwrap();
        let props = config.resolve_sandbox("s").unwrap().properties;
        assert_eq!(props.image.as_deref(), Some("alpine"));
        let env = props.container_env.as_ref().unwrap();
        assert_eq!(env["BASE"], "1");
        assert_eq!(env["MID"], "2");
    }

    #[test]
    fn extends_cycle_errors() {
        let config = Config::parse(
            r#"
[template.a]
extends = "b"
[template.b]
extends = "a"
[sandbox.s]
extends = "a"
"#,
        )
        .unwrap();
        let err = config.resolve_sandbox("s").unwrap_err().to_string();
        assert!(err.contains("cyclic"), "{err}");
    }

    #[test]
    fn caches_expand_to_known_specs() {
        let (source, target, env) = known_cache("cargo").unwrap();
        assert_eq!(source, "cargo");
        assert_eq!(target, "/var/cache/devsandbox/cargo");
        assert_eq!(env, &["CARGO_HOME"]);
        assert!(known_cache("nope").is_none());
    }

    #[test]
    fn cache_targets_avoid_home_dirs() {
        // A non-root user can't traverse `/root`; every target must be
        // reachable whatever user the sandbox runs as.
        for name in SUPPORTED_CACHES {
            let (_, target, _) = known_cache(name).unwrap();
            assert!(target.starts_with("/var/cache/devsandbox/"), "{name}: {target}");
        }
    }

    #[test]
    fn service_scope_defaults_to_isolated() {
        let config = Config::parse("[services.db]\nimage = \"postgres:16\"").unwrap();
        let svc = config.resolve_service("db").unwrap();
        assert_eq!(svc.spec.scope, ServiceScope::Isolated);
    }

    #[test]
    fn service_scope_global_parses() {
        let config =
            Config::parse("[services.db]\nimage = \"postgres:16\"\nscope = \"global\"").unwrap();
        let svc = config.resolve_service("db").unwrap();
        assert_eq!(svc.spec.scope, ServiceScope::Global);
    }

    #[test]
    fn service_requires_image_xor_build() {
        let neither = Config::parse("[services.db]\nenv = { X = \"1\" }").unwrap();
        assert!(neither.resolve_service("db").unwrap_err().to_string().contains("image"));
        let both = Config::parse(
            "[services.db]\nimage = \"postgres:16\"\nbuild = { dockerfile = \"Dockerfile\" }",
        )
        .unwrap();
        assert!(both.resolve_service("db").unwrap_err().to_string().contains("only one"));
    }

    #[test]
    fn service_host_requirements_parse_and_hash() {
        let svc = |toml: &str| {
            Config::parse(&format!("[services.db]\nimage = \"postgres:16\"\n{toml}"))
                .unwrap()
                .resolve_service("db")
                .unwrap()
        };
        let plain = svc("");
        assert_eq!(plain.spec.host_requirements, None);
        let gpu = svc("hostRequirements.gpu = \"optional\"");
        assert_eq!(
            gpu.spec.host_requirements.as_ref().and_then(HostRequirements::gpu_need),
            Some(GpuNeed::Optional)
        );
        assert_ne!(plain.config_hash, gpu.config_hash);
        let yaml = Config::parse_yaml(
            "services:\n  db:\n    image: postgres:16\n    hostRequirements:\n      gpu: optional\n",
        )
        .unwrap()
        .resolve_service("db")
        .unwrap();
        assert_eq!(yaml.spec.host_requirements, gpu.spec.host_requirements);
        assert_eq!(yaml.config_hash, gpu.config_hash);
        let bad = Config::parse("[services.db]\nimage = \"x\"\nhostRequirements.gpu = \"yes\"")
            .unwrap()
            .resolve_service("db")
            .unwrap_err()
            .to_string();
        assert!(bad.contains("optional"), "{bad}");
    }
}