kranz-engine 0.2.2

Governed mission engine for auditable AI coding-agent work.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
//! OS sandbox profile/argv generation — Tier 2 filesystem/network containment.
//! See docs/scoping/worker-sandboxing.md tier 2.
//!
//! macOS uses Seatbelt (`sandbox-exec`) for filesystem isolation. Seatbelt
//! cannot express hostname egress allowlists (it accepts only `*`/`localhost`
//! network hosts), so `fs+net` on macOS restricts outbound TCP to loopback
//! and the run routes through the userspace filtering egress proxy
//! (`crate::egress_proxy`), which enforces the per-host allowlist at CONNECT
//! time. Linux uses bubblewrap for filesystem isolation; `fs+net` fails closed
//! with `--unshare-net` because bwrap alone cannot express a hostname egress
//! allowlist (and its netns cannot reach a host proxy — out of scope for v1).
//!
//! Write scope (P1, ticket sandbox-writable-scope): a session may write only
//! its working directory, its per-session private scratch root
//! (`SandboxInputs::tmpdir` — NOT the shared system temp root, which would
//! expose every sibling mission's worktrees and merge scratch), and
//! operator-declared `extraWrite` paths. The mission dir is never
//! worker-writable; its engine-owned metadata (audit log, state snapshot,
//! control inbox, transcripts) is additionally denied/masked so it stays
//! read-only even in checkout mode, where the writable `session_cwd` is an
//! ancestor of the mission dir.
//!
//! Mandatory validator containment (ticket `validator-mandatory-containment`):
//! VALIDATOR sessions are the one class wrapped regardless of
//! `sandbox.enforce` — the validator is the adversarial reader the whole
//! gate rests on, so its isolation cannot be operator-opt-in.
//! [`resolve_validator_containment`] resolves the posture: the role's own
//! enforced sandbox plus the real-checkout read-deny set when enforcement
//! is configured, the mandatory `fs`-tier wrap when it is not, and — where
//! the platform or the selected backend cannot contain — a FAIL-CLOSED
//! refusal by default (ticket `validator-containment-degrade-fail-closed`,
//! 14th-pass review: the loud degrade reopens the modify→use→restore path,
//! so it is now the explicit opt-in `validatorAllowUncontainedDegrade`, never
//! the default).
//! The read-deny set ([`validator_read_deny_entries`]) closes the broad
//! read allow over the real checkout's source tree — the snapshot
//! worktree is the sole writable root and the only tree the validator can
//! read — keeping the narrow `.git`/`.kranz` carve-outs the inspection
//! legitimately needs.

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

/// Default egress needed by Claude/Anthropic sessions under `fs+net`.
pub const DEFAULT_EGRESS: &[&str] = &["api.anthropic.com:443", "*.anthropic.com:443"];

/// Inputs used to build a session sandbox.
#[derive(Debug, Clone)]
pub struct SandboxInputs {
    pub enforce: crate::types::SandboxEnforce,
    pub session_cwd: PathBuf,
    pub mission_dir: PathBuf,
    /// The session-PRIVATE scratch root — the only TMPDIR-side path the
    /// session may write (the cleared child env points `HOME`/`TMPDIR`
    /// under it; see `crate::agent_env`). NOT the shared system temp root:
    /// allowing all of `TMPDIR` made every sibling mission's worktree and
    /// merge scratch worker-writable (P1, ticket sandbox-writable-scope).
    /// `build_inputs` defaults it to the mission's gitignored probe scratch;
    /// the runner overrides it per session with
    /// `crate::backend_claude::scratch_home_root(session_id)`.
    pub tmpdir: PathBuf,
    pub extra_write: Vec<PathBuf>,
    pub egress: Vec<String>,
    /// Mandatory validator containment (ticket
    /// `validator-mandatory-containment`): the REAL checkout roots a
    /// VALIDATOR session must not read — the checkout the snapshot was taken
    /// from, plus the primary checkout when worktree mode separates them.
    /// Empty for every non-validator session (workers, orchestrator turns)
    /// and for engine-run gates: those legitimately work in the real tree,
    /// and an empty set keeps the generated profile/argv byte-identical to
    /// the pre-containment shape. The validator's own snapshot worktree is
    /// never in this set — it lives under the mission dir, which the
    /// read-deny carve-outs (`<root>/.git`, `<root>/.kranz`) deliberately
    /// keep reachable; see [`validator_read_deny_entries`].
    pub validator_read_deny_roots: Vec<PathBuf>,
}

/// Concrete OS sandbox backend selected for this session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SandboxBackend {
    Seatbelt,
    Bubblewrap,
    /// Stable Win32 AppContainer profile + path-specific SID ACLs. The
    /// hostile child is created suspended and Job-owned before resume.
    AppContainer,
    /// Tier-3: run the session inside a container (see
    /// [`crate::sandbox_container`]); `ResolvedSandbox::container` is `Some`.
    Container,
}

/// How a role's `enforce` setting maps onto the current platform.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SandboxDecision {
    /// Enforcement is off; no sandbox is attached.
    Off,
    /// Enforcement is requested and the platform supports it.
    Enforce(SandboxBackend),
    /// Enforcement is requested but the platform can't honor it; run-level
    /// callers must refuse rather than proceed unsandboxed.
    UnsupportedWarn,
}

fn enforce_label(enforce: crate::types::SandboxEnforce) -> &'static str {
    match enforce {
        crate::types::SandboxEnforce::Off => "off",
        crate::types::SandboxEnforce::Fs => "fs",
        crate::types::SandboxEnforce::FsNet => "fs+net",
    }
}

/// Pure decision fn: given a role's `enforce` setting and the target OS
/// (`std::env::consts::OS`-shaped string), decide whether the session gets an
/// enforced sandbox. Parameterized on `target_os` so it is testable
/// cross-platform.
pub fn platform_support(enforce: crate::types::SandboxEnforce, target_os: &str) -> SandboxDecision {
    match enforce {
        crate::types::SandboxEnforce::Off => SandboxDecision::Off,
        crate::types::SandboxEnforce::Fs if target_os == "macos" => {
            SandboxDecision::Enforce(SandboxBackend::Seatbelt)
        }
        crate::types::SandboxEnforce::FsNet if target_os == "macos" => {
            // Seatbelt's loopback-only egress profile plus the egress proxy's
            // per-host allowlist (crate::egress_proxy): the hostname rules the
            // SBPL cannot express live in the proxy, not the profile.
            SandboxDecision::Enforce(SandboxBackend::Seatbelt)
        }
        crate::types::SandboxEnforce::Fs | crate::types::SandboxEnforce::FsNet
            if target_os == "linux" =>
        {
            SandboxDecision::Enforce(SandboxBackend::Bubblewrap)
        }
        crate::types::SandboxEnforce::Fs | crate::types::SandboxEnforce::FsNet
            if target_os == "windows" =>
        {
            SandboxDecision::Enforce(SandboxBackend::AppContainer)
        }
        crate::types::SandboxEnforce::Fs | crate::types::SandboxEnforce::FsNet => {
            SandboxDecision::UnsupportedWarn
        }
    }
}

/// A resolved, enforced sandbox for one session.
#[derive(Debug, Clone)]
pub struct ResolvedSandbox {
    pub backend: SandboxBackend,
    pub inputs: SandboxInputs,
    /// Container runtime + image; `Some` iff `backend == Container`.
    pub container: Option<crate::sandbox_container::ContainerSpec>,
}

/// Expand a leading `~/` (or `~\` on Windows) in `raw` using the platform home
/// variable; otherwise return `raw` unchanged as a `PathBuf`. `pub(crate)` so
/// the engine-run gate wrap (`crate::command_exec::resolve_gate_sandbox`)
/// builds `extra_write` inputs with the SAME expansion sessions get — never a
/// second hand-rolled rule.
///
/// Windows reads `USERPROFILE`, matching [`crate::paths::global_config`]. A
/// natively launched `kranz.exe` has no `HOME` (only shells like Git Bash
/// inject one), so keying solely off `HOME` silently left `~/...` literal and
/// the sandbox grant then pointed at a directory named `~`.
pub(crate) fn expand_tilde(raw: &str) -> PathBuf {
    let rest = raw.strip_prefix("~/").or_else(|| {
        if cfg!(windows) {
            raw.strip_prefix("~\\")
        } else {
            None
        }
    });
    if let Some(rest) = rest {
        if let Some(home) = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
            .filter(|value| !value.is_empty())
        {
            return PathBuf::from(home).join(rest);
        }
    }
    PathBuf::from(raw)
}

/// Resolve a role's sandbox config into an (optional) enforced sandbox for
/// one session, plus an optional one-time warning string.
///
/// Returns `(Some(ResolvedSandbox), None)` when enforcement is requested and
/// supported, `(None, None)` when enforcement is off, and
/// `(None, Some(warning))` when enforcement is requested but unsupported on
/// this platform.
pub fn resolve_for_session(
    role_sandbox: &crate::types::SandboxConfig,
    session_cwd: &Path,
    mission_dir: &Path,
) -> (Option<ResolvedSandbox>, Option<String>) {
    let runtime = crate::sandbox_container::detect();
    let resolved = resolve_for_session_target(
        role_sandbox,
        session_cwd,
        mission_dir,
        std::env::consts::OS,
        command_available("bwrap"),
        runtime,
        session_mount_proof(role_sandbox, session_cwd, mission_dir, runtime),
    );
    prewarm_xcrun_for_resolved_seatbelt(resolved.0.as_ref());
    resolved
}

/// Apple command-line-tool shims refresh a per-user `xcrun_db*` file even for
/// read-only Git commands. The profile correctly refuses that shared write,
/// so refresh the cache outside the sandbox once per resolved Seatbelt
/// session. Gate wrappers use the same bounded helper; command wrapping never
/// performs the prewarm itself.
#[cfg(target_os = "macos")]
fn prewarm_xcrun_for_resolved_seatbelt(sandbox: Option<&ResolvedSandbox>) {
    if sandbox.is_some_and(|sandbox| sandbox.backend == SandboxBackend::Seatbelt) {
        crate::command_exec::prewarm_xcrun_cache_outside_sandbox();
    }
}

#[cfg(not(target_os = "macos"))]
fn prewarm_xcrun_for_resolved_seatbelt(_sandbox: Option<&ResolvedSandbox>) {}

/// Take a bind-mount proof only where resolution needs one.
///
/// Linux is CI-proven and Windows is refused outright, so neither pays for a
/// probe. Everything else pays once per host, cached, and only when a
/// container was actually requested.
pub(crate) fn session_mount_proof(
    role_sandbox: &crate::types::SandboxConfig,
    session_cwd: &Path,
    mission_dir: &Path,
    runtime: Option<crate::sandbox_container::ContainerRuntime>,
) -> Option<crate::sandbox_container::MountProof> {
    if role_sandbox.provider != crate::types::SandboxProvider::Container
        || role_sandbox.enforce == crate::types::SandboxEnforce::Off
        || cfg!(target_os = "linux")
        || cfg!(target_os = "windows")
    {
        return None;
    }
    let runtime = runtime?;
    let extra_write: Vec<PathBuf> = role_sandbox
        .extra_write
        .iter()
        .map(|raw| expand_tilde(raw))
        .collect();
    Some(crate::sandbox_container::prove_mount_roots(
        runtime,
        &crate::sandbox_container::declared_mount_roots(session_cwd, mission_dir, &extra_write),
        crate::sandbox_container::DEFAULT_IMAGE,
    ))
}

fn resolve_for_session_target(
    role_sandbox: &crate::types::SandboxConfig,
    session_cwd: &Path,
    mission_dir: &Path,
    target_os: &str,
    bwrap_available: bool,
    container_runtime: Option<crate::sandbox_container::ContainerRuntime>,
    container_mount_proof: Option<crate::sandbox_container::MountProof>,
) -> (Option<ResolvedSandbox>, Option<String>) {
    if role_sandbox.provider == crate::types::SandboxProvider::Container {
        return resolve_container_target(
            role_sandbox,
            session_cwd,
            mission_dir,
            target_os,
            container_runtime,
            container_mount_proof,
        );
    }
    match platform_support(role_sandbox.enforce, target_os) {
        SandboxDecision::Off => (None, None),
        SandboxDecision::UnsupportedWarn => (
            None,
            Some(format!(
                "sandbox enforce:{} requested but unsupported on target_os={target_os}; refusing to run unsandboxed",
                enforce_label(role_sandbox.enforce)
            )),
        ),
        SandboxDecision::Enforce(SandboxBackend::Bubblewrap) if !bwrap_available => (
            None,
            Some(format!(
                "sandbox enforce:{} requested on linux but `bwrap` was not found; refusing to run unsandboxed",
                enforce_label(role_sandbox.enforce)
            )),
        ),
        SandboxDecision::Enforce(backend) => (
            Some(ResolvedSandbox {
                backend,
                inputs: build_inputs(role_sandbox, session_cwd, mission_dir),
                container: None,
            }),
            None,
        ),
    }
}

/// Resolve the tier-3 container provider: `enforce: off` stays unsandboxed;
/// `fs+net` with an empty egress list keeps the `--network none` hard egress
/// boundary. A non-empty list is supported only by Docker: the runner creates
/// a unique internal network and authenticated filtering relay before spawn.
/// Other runtimes refuse rather than silently falling back to their bridge.
/// A requested container with no runtime on PATH is refused.
fn resolve_container_target(
    role_sandbox: &crate::types::SandboxConfig,
    session_cwd: &Path,
    mission_dir: &Path,
    target_os: &str,
    runtime: Option<crate::sandbox_container::ContainerRuntime>,
    mount_proof: Option<crate::sandbox_container::MountProof>,
) -> (Option<ResolvedSandbox>, Option<String>) {
    if role_sandbox.enforce == crate::types::SandboxEnforce::Off {
        return (None, None);
    }
    // Linux carries a continuously enforced CI receipt for the shipped
    // bind-mount, authority-mask, and egress contracts, so it needs no
    // per-host evidence. macOS cannot renew that receipt in CI, because
    // hosted runners are already guests and cannot provision the VM the
    // runtime needs. Rather than claim macOS on a receipt that expires or
    // deny a host that demonstrably works, require the evidence AT RUN TIME:
    // a macOS host is supported exactly when this runtime proves it really
    // shares the mounted path. Windows stays refused whatever a probe says,
    // because its gap is the POSIX guest-path and `/dev/null` authority-mask
    // contract, which no mount proof addresses.
    if target_os == "windows" {
        return (
            None,
            Some(format!(
                "sandbox provider:container with enforce:{} is not supported on target_os=windows: the shipped contract uses POSIX guest paths, Linux images, and /dev/null authority masks that Windows containers do not honor; refusing to run under an unverified container mount contract",
                enforce_label(role_sandbox.enforce)
            )),
        );
    }
    if target_os != "linux" {
        match mount_proof {
            Some(crate::sandbox_container::MountProof::Proven) => {}
            Some(crate::sandbox_container::MountProof::Failed(reason)) => {
                return (
                    None,
                    Some(format!(
                        "sandbox provider:container with enforce:{} refused on target_os={target_os}: {reason}",
                        enforce_label(role_sandbox.enforce)
                    )),
                );
            }
            None => {
                return (
                    None,
                    Some(format!(
                        "sandbox provider:container with enforce:{} on target_os={target_os} requires a bind-mount proof on this host and none was taken; refusing to run under an unverified container mount contract; use sandbox.provider=\"process\" for native host containment",
                        enforce_label(role_sandbox.enforce)
                    )),
                );
            }
        }
    }
    let Some(runtime) = runtime else {
        return (
            None,
            Some(
                "sandbox provider:container requested but no container runtime (docker/podman/nerdctl/container) found on PATH; refusing to run unsandboxed"
                    .to_string(),
            ),
        );
    };
    if role_sandbox.enforce == crate::types::SandboxEnforce::FsNet
        && !role_sandbox.egress.is_empty()
        && runtime != crate::sandbox_container::ContainerRuntime::Docker
    {
        return (
            None,
            Some(format!(
                "sandbox provider:container with enforce:fs+net and a non-empty egress list requires Docker's internal-network boundary; runtime {} is not live-proven for that posture — refusing to run",
                runtime.binary()
            )),
        );
    }
    (
        Some(ResolvedSandbox {
            backend: SandboxBackend::Container,
            inputs: build_inputs(role_sandbox, session_cwd, mission_dir),
            container: Some(crate::sandbox_container::ContainerSpec {
                runtime,
                image: role_sandbox
                    .image
                    .clone()
                    .unwrap_or_else(|| crate::sandbox_container::DEFAULT_IMAGE.to_string()),
                network: None,
                name: None,
            }),
        }),
        None,
    )
}

fn build_inputs(
    role_sandbox: &crate::types::SandboxConfig,
    session_cwd: &Path,
    mission_dir: &Path,
) -> SandboxInputs {
    let extra_write = role_sandbox
        .extra_write
        .iter()
        .map(|s| expand_tilde(s))
        .collect();
    SandboxInputs {
        enforce: role_sandbox.enforce,
        session_cwd: session_cwd.to_path_buf(),
        mission_dir: mission_dir.to_path_buf(),
        // Default session-private scratch: the mission's gitignored
        // contract/sandbox scratch home — the shape the engine's own probes
        // (preflight contract commands, whose cleared env points HOME/TMPDIR
        // at `runs/contract-home`) execute under. The runner overrides this
        // per session with the session's private scratch root (see the
        // `SandboxInputs::tmpdir` doc); warn-only resolves never execute
        // under the profile, so the default is never their concern.
        tmpdir: mission_dir.join("runs").join("contract-home"),
        extra_write,
        egress: role_sandbox.egress.clone(),
        // Session sandboxes never read-deny the tree they work in — the
        // validator containment resolution sets this explicitly.
        validator_read_deny_roots: Vec::new(),
    }
}

// ---------------------------------------------------------------------------
// Mandatory validator containment (ticket validator-mandatory-containment)
// ---------------------------------------------------------------------------

/// The outcome of resolving one validator session's MANDATORY containment
/// (ticket `validator-mandatory-containment`). The validator is the
/// adversarial reader the whole gate rests on; its isolation must not depend
/// on the operator opting into enforcement, so `sandbox.enforce: off` (the
/// default) no longer means an unwrapped validator — where the platform has
/// a process-sandbox tier and the selected backend can apply it, the session
/// is wrapped regardless.
#[derive(Debug)]
pub struct ValidatorContainment {
    /// The sandbox to attach to the validator's [`crate::backend::SessionSpec`]
    /// — `Some` whenever a wrap applies (the role's own enforced sandbox
    /// plus the read-deny roots, or the mandatory `fs`-tier wrap under
    /// `enforce: off`), `None` only when containment degraded (see `note`).
    pub sandbox: Option<ResolvedSandbox>,
    /// The LOUD operator-facing posture note when containment could not be
    /// applied AND the operator opted into the degrade
    /// (`validatorAllowUncontainedDegrade`) — an unsupported platform, a
    /// linux without `bwrap`, or a backend that does not honor the resolved
    /// sandbox. The orchestrator surfaces it as a decision per validator
    /// spawn (so every validation round carries it); `None` when the session
    /// is contained. Without the opt-in the resolution FAILS CLOSED instead
    /// (ticket `validator-containment-degrade-fail-closed`, 14th-pass
    /// review): the degrade reopens the modify→use→restore path the
    /// mandatory-containment work was built to close, so snapshot
    /// separation plus the after-fingerprint tripwire alone are no longer
    /// the default posture.
    pub note: Option<String>,
}

/// Resolve the containment posture for one validator session (both roles —
/// scrutiny and functional run the same shape).
///
/// `session_cwd` is the throwaway snapshot worktree — the profile's sole
/// writable root alongside the session-private scratch. `read_deny_roots`
/// are the REAL checkout roots the snapshot was taken from (the active tree,
/// plus the primary checkout when worktree mode separates them); their
/// source trees become read-denied in the generated profile/argv
/// ([`validator_read_deny_entries`]). `backend` decides whether the wrap can
/// be honored at all: only the claude backend applies a resolved sandbox
/// ([`crate::types::BackendKind::supports_sandbox_enforcement`]).
///
/// `enforce != off` keeps today's fail-closed posture byte-for-byte: the
/// role's own resolution governs (an unsupported platform or missing `bwrap`
/// is an Err, mirroring the runner's `resolve_sandbox_or_refuse`), with the
/// read-deny roots ATTACHED on the process tier. The container provider
/// resolves untouched — its read-only rootfs and named mounts are already
/// the stronger containment, and the real tree is simply not mounted.
///
/// `enforce == off` is the case this ticket exists for: the mandatory
/// `fs`-tier wrap (write containment with the validator's API egress intact;
/// no operator `extraWrite` widening — the snapshot is the sole writable
/// root) wherever the platform supports it and the backend can apply it.
/// Everywhere else the resolution FAILS CLOSED (ticket
/// `validator-containment-degrade-fail-closed`, 14th-pass review — this
/// reverses the 224fa73 loud-degrade default) unless
/// `allow_uncontained_degrade` (the `validatorAllowUncontainedDegrade`
/// config flag) opts this repo back into the loud degradation note.
pub fn resolve_validator_containment(
    role_sandbox: &crate::types::SandboxConfig,
    backend: crate::types::BackendKind,
    session_cwd: &Path,
    mission_dir: &Path,
    read_deny_roots: &[PathBuf],
    allow_uncontained_degrade: bool,
) -> crate::error::Result<ValidatorContainment> {
    let runtime = crate::sandbox_container::detect();
    let resolved = resolve_validator_containment_target(
        role_sandbox,
        backend,
        session_cwd,
        mission_dir,
        read_deny_roots,
        allow_uncontained_degrade,
        std::env::consts::OS,
        command_available("bwrap"),
        runtime,
        session_mount_proof(role_sandbox, session_cwd, mission_dir, runtime),
    );
    if let Ok(containment) = &resolved {
        prewarm_xcrun_for_resolved_seatbelt(containment.sandbox.as_ref());
    }
    resolved
}

/// [`resolve_validator_containment`] parameterized on the target OS, `bwrap`
/// availability, and container runtime so the decision matrix is testable
/// cross-platform (mirrors [`resolve_for_session_target`] /
/// `crate::command_exec::resolve_gate_sandbox_target`).
#[allow(clippy::too_many_arguments)]
fn resolve_validator_containment_target(
    role_sandbox: &crate::types::SandboxConfig,
    backend: crate::types::BackendKind,
    session_cwd: &Path,
    mission_dir: &Path,
    read_deny_roots: &[PathBuf],
    allow_uncontained_degrade: bool,
    target_os: &str,
    bwrap_available: bool,
    container_runtime: Option<crate::sandbox_container::ContainerRuntime>,
    container_mount_proof: Option<crate::sandbox_container::MountProof>,
) -> crate::error::Result<ValidatorContainment> {
    if role_sandbox.enforce != crate::types::SandboxEnforce::Off {
        // The role's own resolution governs; an enforced pair with a
        // backend that cannot honor it is already refused by
        // `config::validate` (fail closed) before a mission reaches here.
        let (sandbox, warn) = resolve_for_session_target(
            role_sandbox,
            session_cwd,
            mission_dir,
            target_os,
            bwrap_available,
            container_runtime,
            container_mount_proof,
        );
        return match sandbox {
            Some(mut resolved) => {
                // Process-tier wraps (Seatbelt/bwrap) get the read-deny
                // roots; the container tier's mounts are the containment
                // and simply do not include the real tree.
                if resolved.backend != SandboxBackend::Container {
                    resolved.inputs.validator_read_deny_roots = read_deny_roots.to_vec();
                }
                Ok(ValidatorContainment {
                    sandbox: Some(resolved),
                    note: None,
                })
            }
            // Fail closed, mirroring resolve_sandbox_or_refuse: enforcement
            // was requested and cannot be honored on this platform.
            None => Err(crate::error::EngineError::Backend(warn.unwrap_or_else(|| {
                format!(
                    "sandbox enforce:{} requested but no sandbox could be resolved; refusing to run unsandboxed",
                    role_sandbox.enforce.as_str()
                )
            }))),
        };
    }

    // enforce: off — MANDATORY containment. The provider is ignored here:
    // `provider: container` with `enforce: off` documents "no sandboxing,
    // same as today", and the mandatory wrap is the process tier.
    //
    // Where the wrap cannot apply, the default is FAIL CLOSED (ticket
    // validator-containment-degrade-fail-closed, 14th-pass review — this
    // REVERSES the 224fa73 loud-degrade-by-default decision: a degraded
    // validator runs with snapshot separation and the tripwire only, which
    // reopens the modify→use→restore path the wrap exists to close).
    // `validatorAllowUncontainedDegrade` opts this repo back into the loud
    // per-round degradation note.
    let uncontained = |why: String, note: String| -> crate::error::Result<ValidatorContainment> {
        if !allow_uncontained_degrade {
            return Err(crate::error::EngineError::Config(format!(
                "mandatory validator containment cannot apply ({why}); refusing to run an \
                 uncontained validator — the degraded posture reopens the modify→use→restore \
                 path the wrap exists to close (ticket \
                 validator-containment-degrade-fail-closed). To run validators here anyway, \
                 set \"validatorAllowUncontainedDegrade\": true in .kranz/config.json (the \
                 loud per-round degrade returns); otherwise use a containable platform \
                 (macOS, or linux with `bwrap` on PATH) and the claude validator backend"
            )));
        }
        Ok(ValidatorContainment {
            sandbox: None,
            note: Some(note),
        })
    };
    if !backend.supports_sandbox_enforcement() {
        return uncontained(
            format!(
                "the {} backend does not apply the resolved sandbox profile",
                backend.as_str()
            ),
            format!(
                "validator sessions on the {} backend cannot be OS-sandbox-contained (only the \
                 claude backend applies the resolved sandbox profile); \
                 validatorAllowUncontainedDegrade is set, so this validator runs with \
                 snapshot isolation and the after-fingerprint tripwire only — the real checkout \
                 is reachable from the session. Select a claude validator backend for mandatory \
                 containment (ticket validator-mandatory-containment; the degrade is opt-in per \
                 validator-containment-degrade-fail-closed)",
                backend.as_str()
            ),
        );
    }
    let degraded = |why: String| {
        uncontained(
            why.clone(),
            format!(
                "validator sessions are NOT OS-sandbox-contained ({why}); \
                 validatorAllowUncontainedDegrade is set, so the validator still runs in its \
                 throwaway snapshot with the after-fingerprint tripwire on the real checkout, \
                 but hostile validator code could walk to the real checkout and restore bytes \
                 before the fingerprint — containment here is the snapshot's physical \
                 separation only (ticket validator-mandatory-containment; the degrade is \
                 opt-in per validator-containment-degrade-fail-closed)"
            ),
        )
    };
    match platform_support(crate::types::SandboxEnforce::Fs, target_os) {
        // Unreachable (Fs is not Off) — platform_support is the shared
        // vocabulary, so the match stays exhaustive anyway.
        SandboxDecision::Off => unreachable!("fs never decides Off"),
        SandboxDecision::UnsupportedWarn => {
            degraded(format!("target_os={target_os} has no process-sandbox tier"))
        }
        SandboxDecision::Enforce(SandboxBackend::Bubblewrap) if !bwrap_available => {
            degraded("linux without `bwrap` on PATH".to_string())
        }
        // platform_support never selects Container (that resolution is
        // resolve_container_target's, and the enforce!=off arm above owns
        // the provider) — the match stays exhaustive anyway.
        SandboxDecision::Enforce(SandboxBackend::Container) => {
            unreachable!("process tier only")
        }
        SandboxDecision::Enforce(backend_kind) => Ok(ValidatorContainment {
            sandbox: Some(ResolvedSandbox {
                backend: backend_kind,
                inputs: SandboxInputs {
                    // The fs tier: write containment with network intact
                    // (denying egress would brick the validator's API
                    // session — the same reason the session profile
                    // allows network under fs).
                    enforce: crate::types::SandboxEnforce::Fs,
                    session_cwd: session_cwd.to_path_buf(),
                    mission_dir: mission_dir.to_path_buf(),
                    // Pinned per session by the runner to the session's
                    // private scratch root (the same pin
                    // resolve_sandbox_or_refuse applies); the default
                    // here is the probe-shaped contract home.
                    tmpdir: mission_dir.join("runs").join("contract-home"),
                    // NO operator extraWrite widening under the mandatory
                    // wrap: the snapshot worktree is the sole writable
                    // root (plus the session-private scratch).
                    extra_write: Vec::new(),
                    egress: Vec::new(),
                    validator_read_deny_roots: read_deny_roots.to_vec(),
                },
                container: None,
            }),
            note: None,
        }),
    }
}

pub(crate) fn command_available(name: &str) -> bool {
    let Some(path) = std::env::var_os("PATH") else {
        return false;
    };
    // Windows PATH entries carry no extension; the executable suffixes live in
    // PATHEXT. Probing the bare name alone reports every Windows executable as
    // missing (`grep` vs `grep.exe`).
    let mut candidates = vec![name.to_string()];
    if cfg!(windows) {
        let pathext =
            std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string());
        candidates.extend(
            pathext
                .split(';')
                .filter(|ext| !ext.is_empty())
                .map(|ext| format!("{name}{ext}")),
        );
    }
    std::env::split_paths(&path).any(|dir| candidates.iter().any(|name| dir.join(name).is_file()))
}

/// Absolutize a path without requiring it to exist: canonicalize if possible,
/// otherwise join it onto the current directory when relative.
pub(crate) fn absolutize(path: &Path) -> PathBuf {
    if let Ok(canon) = path.canonicalize() {
        return canon;
    }
    // Future authority paths still need their existing ancestors resolved
    // (notably /var -> /private/var), even before their leaf is created.
    for ancestor in path.ancestors().skip(1) {
        if let Ok(canon) = ancestor.canonicalize() {
            if let Ok(suffix) = path.strip_prefix(ancestor) {
                return canon.join(suffix);
            }
        }
    }
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .map(|cwd| cwd.join(path))
            .unwrap_or_else(|_| path.to_path_buf())
    }
}

// Mount destinations name the inspected leaf without following its links.
fn lexical_absolute(path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .map(|cwd| cwd.join(path))
            .unwrap_or_else(|_| path.to_path_buf())
    }
}

pub(crate) fn global_authority_dir() -> Option<PathBuf> {
    crate::paths::global_config().and_then(|path| path.parent().map(absolutize))
}

/// Escape a path for embedding in an SBPL string literal.
pub(crate) fn escape_sbpl_literal(path: &Path) -> String {
    escape_sbpl_string(&path.to_string_lossy())
}

fn escape_sbpl_string(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

/// Escape a path for embedding in an SBPL `#"..."` regex literal: every
/// regex metacharacter is backslash-escaped so the path matches literally
/// (temp-dir names carry no metacharacters in practice, but a repo root
/// might — `.` in a directory name must not become an any-char match).
pub(crate) fn escape_sbpl_regex(path: &Path) -> String {
    let mut out = String::new();
    for ch in path.to_string_lossy().chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            c if "^.+$*?()[]{}|".contains(c) => {
                out.push('\\');
                out.push(c);
            }
            c => out.push(c),
        }
    }
    out
}

/// The session's writable roots: its working directory (worktree or, in
/// checkout mode, the repo root), its private scratch root, and each
/// operator-declared `extraWrite` entry. The mission dir and the shared
/// system temp root are deliberately NOT here (ticket
/// sandbox-writable-scope): the engine writes mission metadata from OUTSIDE
/// the sandbox, and whole-`TMPDIR` access made sibling missions' worktrees
/// writable. Mission metadata that would still be reachable through an
/// allowed ancestor (checkout mode: `session_cwd` is the repo root) is
/// carved back out by [`mission_write_denies`].
pub(crate) fn write_allowlist(inputs: &SandboxInputs) -> Vec<PathBuf> {
    let mut write_paths: Vec<PathBuf> =
        vec![absolutize(&inputs.session_cwd), absolutize(&inputs.tmpdir)];
    write_paths.extend(inputs.extra_write.iter().map(|p| absolutize(p)));
    write_paths.sort();
    write_paths.dedup();
    write_paths
}

/// The mission-metadata write-deny set: engine-owned files a sandboxed
/// session must never write even when an allowed ancestor (checkout mode's
/// `session_cwd` = repo root) would otherwise cover them. A worker that
/// could rewrite `events.jsonl` defeats the append-only audit log; one that
/// could drop files into `control/` injects control commands; one that
/// could rewrite `runs/*.jsonl` forges transcripts. Like
/// [`authority_read_deny_paths`], both the raw and canonical mission-dir
/// forms are expanded (Seatbelt matches canonical paths; the child may
/// address either form).
pub(crate) struct MissionWriteDenies {
    /// Engine-written files at the mission-dir root: literal write denies
    /// (Seatbelt) / read-only directory views (bwrap).
    pub files: Vec<PathBuf>,
    /// Current and sibling `control/` inboxes: subpath write deny / tmpfs shadow.
    pub control_dirs: Vec<PathBuf>,
    /// The `runs/` transcript dirs: `runs/*.jsonl` regex write deny
    /// (Seatbelt) / read-only directory binds (bwrap). Session scratch and
    /// the current worktree keep their explicit writable roots.
    pub runs_dirs: Vec<PathBuf>,
}

/// Engine-written files at the mission-dir root a sandboxed session must
/// never write (see [`MissionWriteDenies`]).
pub(crate) const MISSION_METADATA_FILES: &[&str] = &[
    "events.jsonl",
    "events.jsonl.lock",
    "state.json",
    "state.json.tmp",
    "estimate.json",
];

pub(crate) fn mission_write_denies(inputs: &SandboxInputs) -> MissionWriteDenies {
    let mut denies = MissionWriteDenies {
        files: Vec::new(),
        control_dirs: Vec::new(),
        runs_dirs: Vec::new(),
    };
    let mut mission_dirs = vec![inputs.mission_dir.clone(), absolutize(&inputs.mission_dir)];
    // Checkout mode makes the whole repository writable. Protect sibling
    // missions as well as the current one; their inboxes have equal authority.
    if let Some(missions) = inputs
        .mission_dir
        .parent()
        .filter(|path| path.ends_with("missions"))
    {
        if let Ok(entries) = std::fs::read_dir(missions) {
            for entry in entries.flatten() {
                if entry.file_type().is_ok_and(|kind| kind.is_dir()) {
                    mission_dirs.extend([entry.path(), absolutize(&entry.path())]);
                }
            }
        }
    }
    for mission_dir in mission_dirs {
        for name in MISSION_METADATA_FILES {
            denies.files.push(mission_dir.join(name));
        }
        denies.control_dirs.push(mission_dir.join("control"));
        denies.runs_dirs.push(mission_dir.join("runs"));
    }
    denies
}

/// The operator's real Cargo home: ambient `CARGO_HOME` when set, else
/// `~/.cargo` when HOME is set — the same resolution
/// `crate::agent_env::toolchain_var_value("CARGO_HOME", ".cargo")` applies
/// when it builds the isolated contract home. The two MUST stay in
/// lockstep: whatever the isolated home can LINK is what the profile must
/// be able to DENY writes to (see [`cargo_cache_write_deny_paths`]).
fn operator_cargo_home() -> Option<PathBuf> {
    std::env::var_os("CARGO_HOME")
        .map(PathBuf::from)
        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cargo")))
}

/// The operator's REAL shared Cargo cache directories —
/// `<cargo home>/registry` and `<cargo home>/git` — in both raw and
/// canonicalized forms (the `/var` ↔ `/private/var` idiom the write
/// allowlist already uses; Seatbelt matches canonical paths and a child
/// may address either form). Above the copy ceiling the isolated contract
/// home LINKS these in (`crate::agent_env::cache_only_cargo_home`'s
/// documented residual trade), so every sandbox profile must deny WRITES
/// to them explicitly (13th-pass review, P1): deny-default covers the
/// common case, but only an explicit deny survives EVERY allow — an
/// operator `extraWrite` of `$HOME`, or any future broadened writable
/// root, would otherwise silently re-widen the linked cache to writes
/// from worker-authored contract code, poisoning later builds. PRECISE
/// scope: the two cache dirs only, never the whole cargo home —
/// `~/.cargo/bin`'s rustup shims keep their ordinary posture. Reads stay
/// allowed: the linked cache is the session/gate's registry.
pub(crate) fn cargo_cache_write_deny_paths() -> Vec<PathBuf> {
    let Some(cargo_home) = operator_cargo_home() else {
        return Vec::new();
    };
    let mut paths = Vec::with_capacity(4);
    for base in [cargo_home.clone(), absolutize(&cargo_home)] {
        paths.push(base.join("registry"));
        paths.push(base.join("git"));
    }
    paths
}

/// Authority files a sandboxed session must never read, even under the broad
/// read allow: a read of `serve.token` IS mutation authority over `kranz
/// serve` (loopback is reachable from every sandbox tier), `serve.read.token`
/// is its GET-side sibling, `config.json` carries Slack tokens and
/// remote-workspace credentials, and `domain-terms.local` is the plaintext
/// clean-room lint vocabulary that must never be readable outside the
/// engine-side lint (14th-pass review: the mandatory validator wrap's
/// `.kranz` carve-out — kept for the snapshot — otherwise leaks it).
/// Derived from the mission dir's canonical `<repo>/.kranz/missions/<id>`
/// layout. Both the raw and the canonical mission-dir forms are expanded (the
/// dir exists at spawn time even when the token files do not yet), because
/// Seatbelt matches against canonical paths — the same `/var` ↔
/// `/private/var` split the write allowlist handles.
///
/// Also denied: `$CARGO_HOME/credentials.toml` AND the legacy extensionless
/// `$CARGO_HOME/credentials` (or `~/.cargo/...` when CARGO_HOME is unset) —
/// CARGO_HOME crosses into child envs for registry-cache locality
/// ([`crate::agent_env`]), but cargo reads BOTH filenames for registry auth
/// tokens (the legacy one is still supported and takes precedence where
/// present), so both are the same credential class as the serve token.
pub(crate) fn authority_read_deny_paths(inputs: &SandboxInputs) -> Vec<PathBuf> {
    let mut paths = Vec::new();
    for mission_dir in [inputs.mission_dir.clone(), absolutize(&inputs.mission_dir)] {
        if let Some(kranz_dir) = mission_dir
            .parent()
            .filter(|path| path.ends_with("missions"))
            .and_then(Path::parent)
        {
            for name in KRANZ_AUTHORITY_FILES {
                paths.push(kranz_dir.join(name));
            }
        }
    }
    for name in [
        "serve.token",
        "serve.read.token",
        "config.json",
        "domain-terms.local",
    ] {
        paths.push(absolutize(&inputs.session_cwd).join(".kranz").join(name));
    }
    if let Some(global) = crate::paths::global_config() {
        paths.extend([global.clone(), absolutize(&global)]);
    }
    if let Some(cargo_home) = operator_cargo_home() {
        for base in [cargo_home.clone(), absolutize(&cargo_home)] {
            paths.push(base.join("credentials.toml"));
            paths.push(base.join("credentials"));
        }
    }
    // Config layers can be symlinked. Deny the resolved file as well as its
    // configured name so a canonical read cannot bypass the authority rule.
    paths.extend(paths.clone().iter().map(|path| absolutize(path)));
    paths.sort();
    paths.dedup();
    paths
}

/// Authority DIRECTORIES a sandboxed session must never read (14th-pass
/// review — the directory half of [`authority_read_deny_paths`], denied as
/// Seatbelt subpaths / bwrap tmpfs shadows):
///
/// - `<repo>/.kranz/hook-status/` — the hook-signal projection
///   (registrations + per-run capability-token hashes). The in-sandbox
///   `kranz hook-status` relay reads only its session-private spec and POSTs
///   loopback; the server reads the projection from OUTSIDE the sandbox.
/// - `<mission_dir>/control/` — the operator→engine control inbox (approve /
///   pause / config-change commands). The orchestrator polls it from outside
///   the sandbox; no session ever legitimately reads it. The bwrap write
///   shadow already hid its contents — this aligns the Seatbelt read posture.
/// - `<global kranz dir>/keys/` — the operator-side authority keys the
///   consent substrate is authenticated with (2026-09-01 adversarial audit,
///   C1/H6: control files and the event log are MACed with a key that must
///   live OUTSIDE every sandboxed session's readable set, or the MAC proves
///   nothing against the agent it is meant to exclude). Denied for writes
///   too ([`authority_write_denies`]): a session that can replace the key
///   can re-sign whatever it likes.
pub(crate) fn authority_read_deny_dirs(inputs: &SandboxInputs) -> Vec<PathBuf> {
    let mut dirs = Vec::new();
    for mission_dir in [inputs.mission_dir.clone(), absolutize(&inputs.mission_dir)] {
        dirs.push(mission_dir.join("control"));
        if let Some(kranz_dir) = mission_dir
            .parent()
            .filter(|path| path.ends_with("missions"))
            .and_then(Path::parent)
        {
            dirs.push(kranz_dir.join("hook-status"));
        }
    }
    if let Some(global) = crate::paths::global_kranz_dir() {
        dirs.extend([global.clone(), absolutize(&global)]);
    }
    for keys_dir in global_key_dirs() {
        dirs.push(keys_dir);
    }
    dirs
}

/// Mount-backed sandboxes need a private directory namespace, not just
/// per-file masks: an absent token/config can be created while a worker is
/// running. Rebind only existing non-authority entries read-only beneath an
/// empty tmpfs. No placeholder files are created in the host checkout.
pub(crate) struct AuthorityDirectoryMask {
    pub path: PathBuf,
    pub visible_entries: Vec<PathBuf>,
}

pub(crate) fn authority_directory_masks(inputs: &SandboxInputs) -> Vec<AuthorityDirectoryMask> {
    let files: std::collections::BTreeSet<_> = authority_read_deny_paths(inputs)
        .into_iter()
        .filter_map(|path| Some(absolutize(path.parent()?).join(path.file_name()?)))
        .collect();
    let dirs: std::collections::BTreeSet<_> = authority_read_deny_dirs(inputs)
        .iter()
        .map(|path| absolutize(path))
        .collect();
    let mut roots: std::collections::BTreeSet<_> = files
        .iter()
        .filter_map(|path| path.parent().map(Path::to_path_buf))
        .collect();
    // Hide denied subdirectories through their parent's private namespace.
    // This also works when control/ or hook-status/ does not yet exist under
    // a read-only mission bind; setup need not mkdir in the host directory.
    for dir in &dirs {
        if !roots.contains(dir) {
            if let Some(parent) = dir.parent() {
                roots.insert(parent.to_path_buf());
            }
        }
    }
    let writable = write_allowlist(inputs);
    // A denied path may pass through a symlink beneath an allowed write root.
    // Mask the link's parent too: masking only its target would let the worker
    // replace the alias and redirect the engine's next config read. Ancestors
    // outside writable roots need no extra view (e.g. the system /var alias).
    for path in authority_read_deny_paths(inputs)
        .into_iter()
        .chain(authority_read_deny_dirs(inputs))
    {
        for ancestor in path.ancestors() {
            if std::fs::symlink_metadata(ancestor)
                .is_ok_and(|metadata| metadata.file_type().is_symlink())
            {
                if let Some(parent) = ancestor.parent().map(absolutize) {
                    if writable.iter().any(|root| parent.starts_with(root)) {
                        roots.insert(parent);
                    }
                }
            }
        }
    }
    let roots: std::collections::BTreeSet<_> = roots
        .into_iter()
        .map(|path| {
            if !path.exists() && !writable.iter().any(|root| path.starts_with(root)) {
                // bwrap cannot create a mountpoint inside its read-only / bind.
                // Mask the nearest existing ancestor instead; denied descendants
                // are never rebound, and private write roots are restored below.
                path.ancestors()
                    .skip(1)
                    .find(|parent| parent.is_dir())
                    .map(Path::to_path_buf)
                    .unwrap_or(path)
            } else {
                path
            }
        })
        .collect();
    roots
        .into_iter()
        .map(|path| {
            let mut visible_entries = Vec::new();
            if !dirs.iter().any(|dir| path.starts_with(dir)) {
                if let Ok(entries) = std::fs::read_dir(&path) {
                    for entry in entries.flatten() {
                        let entry_path = entry.path();
                        // Never follow a worker-authored link while constructing
                        // a privileged bind. Unknown/unreadable entries stay hidden.
                        if entry
                            .file_type()
                            .is_ok_and(|kind| kind.is_dir() || kind.is_file())
                            && !files.contains(&entry_path)
                            && !dirs.iter().any(|dir| entry_path.starts_with(dir))
                        {
                            visible_entries.push(entry_path);
                        }
                    }
                }
            }
            visible_entries.sort();
            AuthorityDirectoryMask {
                path,
                visible_entries,
            }
        })
        .collect()
}

/// The GLOBAL kranz authority stores (`<global kranz dir>/keys`, where the
/// per-repository authority key lives, and `<global kranz dir>/seals`, where
/// each mission's seal floor lives), each in raw and canonical form. The
/// global dir comes from [`crate::paths::global_kranz_dir`], the same
/// resolver the key writer and the seal recorder use, so the deny and the
/// writers cannot drift apart. Empty when no global dir resolves (no home,
/// no key dir, nothing to deny).
fn global_key_dirs() -> Vec<PathBuf> {
    let Some(global) = crate::paths::global_kranz_dir() else {
        return Vec::new();
    };
    let mut out = Vec::new();
    for name in ["keys", "seals"] {
        let dir = global.join(name);
        let canonical = absolutize(&dir);
        if canonical != dir {
            out.push(canonical);
        }
        out.push(dir);
    }
    out
}

/// Repo-level `<repo>/.kranz` stores the ENGINE owns end to end. Named
/// explicitly (not only enumerated from the live directory) so the deny
/// exists before the store does: a session that could CREATE
/// `.kranz/queue/` would own the autoWork drain outright.
const KRANZ_ENGINE_OWNED_DIRS: &[&str] = &["queue", "tickets", "lessons", "hook-status"];

/// Authority FILES that live directly under a `<repo>/.kranz` dir — the
/// same four [`authority_read_deny_paths`] names, factored out so the
/// container tier can apply them to the `.kranz` under its own session
/// mount without re-typing the list (2026-09-01 adversarial audit, MED-3:
/// the hand-copied three-name list had already drifted).
const KRANZ_AUTHORITY_FILES: &[&str] = &[
    "serve.token",
    "serve.read.token",
    "config.json",
    "domain-terms.local",
];

/// The authority set under ONE `<repo>/.kranz` dir: the engine-owned files
/// and the engine-owned stores. Shared by the process, container, and
/// Windows tiers so none of them can drift from the others.
pub(crate) fn kranz_authority_entries(kranz_dir: &Path) -> WriteDenySet {
    WriteDenySet {
        files: KRANZ_AUTHORITY_FILES
            .iter()
            .map(|name| kranz_dir.join(name))
            .collect(),
        dirs: KRANZ_ENGINE_OWNED_DIRS
            .iter()
            .map(|name| kranz_dir.join(name))
            .collect(),
    }
}

/// The `(<repo>/.kranz, <repo>/.kranz/missions, <mission dir>)` triples this
/// session's mission dir sits in — raw and canonical form — and ONLY when
/// the mission dir actually has the canonical `<repo>/.kranz/missions/<id>`
/// shape.
///
/// The shape check is load-bearing, not defensive tidiness: the deny
/// derivation below SWEEPS these directories, and a mission dir that is not
/// in the canonical layout (a bare temp dir in a fixture, a future layout
/// change) would otherwise make the sweep walk the system temp root, or
/// `/`, and deny writes across the whole host. A non-canonical layout
/// yields nothing here, which is the fail-quiet direction for a deny that is
/// additive to an already-narrow write allowlist.
fn repo_kranz_dirs(inputs: &SandboxInputs) -> Vec<(PathBuf, PathBuf, PathBuf)> {
    let mut out = Vec::new();
    for mission_dir in [inputs.mission_dir.clone(), absolutize(&inputs.mission_dir)] {
        let Some(missions_dir) = mission_dir.parent().map(Path::to_path_buf) else {
            continue;
        };
        let Some(kranz_dir) = missions_dir.parent().map(Path::to_path_buf) else {
            continue;
        };
        if missions_dir.file_name() != Some(std::ffi::OsStr::new("missions"))
            || kranz_dir.file_name() != Some(std::ffi::OsStr::new(".kranz"))
        {
            continue;
        }
        out.push((kranz_dir, missions_dir, mission_dir));
    }
    out
}

/// A write-deny set split by what each tier can express: `files` deny as
/// Seatbelt literals / bwrap self ro-binds / Windows non-inheriting ACL
/// denies, `dirs` as Seatbelt subpaths / bwrap self ro-binds / inheriting
/// ACL denies.
pub(crate) struct WriteDenySet {
    pub files: Vec<PathBuf>,
    pub dirs: Vec<PathBuf>,
}

fn sorted_dedup(mut paths: Vec<PathBuf>) -> Vec<PathBuf> {
    paths.sort();
    paths.dedup();
    paths
}

/// Authority material a sandboxed session must never WRITE (2026-09-01
/// adversarial audit H2 + H11).
///
/// The pre-audit posture denied READS of `<repo>/.kranz/config.json`,
/// `serve.token`, `serve.read.token`, `domain-terms.local`, `hook-status/`
/// and the mission `control/` inbox while leaving them WRITABLE: under
/// `workerIsolation: "checkout"` the session cwd IS the repo root, so a
/// contained worker could overwrite the trust root it could not read. The
/// running mission is immune (its config is pinned into `MissionCreated`);
/// the next mission picks up `claudeBinary`, `dangerouslyAllowAll`, or
/// `enforce: off` from the file the worker wrote. Every path the read deny
/// names is therefore denied for writes as well.
///
/// H11 is the same asymmetry one level up: every mission-metadata deny was
/// derived from THIS session's `mission_dir`, so a mission-A worker could
/// forge approvals into mission B's `control/` inbox, or drop entries into
/// `.kranz/queue/`, `.kranz/tickets/`, `.kranz/lessons/`. The deny is now
/// derived from `<repo>/.kranz` as a whole:
///
/// - every ENGINE-owned repo-level store ([`KRANZ_ENGINE_OWNED_DIRS`]),
///   named unconditionally so a store that does not exist yet cannot be
///   created by a session either,
/// - every top-level entry of `<repo>/.kranz` present at profile-build time
///   EXCEPT `missions/`, which is carved out because the session's own
///   mission dir lives under it,
/// - every SIBLING mission dir under `<repo>/.kranz/missions/` — the
///   session's own mission dir is carved back in, and inside it the
///   narrower [`mission_write_denies`] keeps the audit log, state snapshot,
///   control inbox and transcripts read-only while leaving the session's
///   own worktree/scratch under `runs/` writable,
/// - the global key dir, via [`authority_read_deny_dirs`].
///
/// Enumeration is spawn-time, so an entry created under `<repo>/.kranz`
/// AFTER the profile is built is not individually named. Seatbelt closes
/// that residue with [`sealed_kranz_dir_roots`]; bwrap and Windows cannot
/// express it (their masks likewise require the target to exist at spawn),
/// which is the documented remainder on those tiers.
pub(crate) fn authority_write_denies(inputs: &SandboxInputs) -> WriteDenySet {
    let mut files = authority_read_deny_paths(inputs);
    let mut dirs = authority_read_deny_dirs(inputs);
    for (kranz_dir, missions_dir, mission_dir) in repo_kranz_dirs(inputs) {
        let entries = kranz_authority_entries(&kranz_dir);
        files.extend(entries.files);
        dirs.extend(entries.dirs);
        if let Ok(entries) = std::fs::read_dir(&kranz_dir) {
            for entry in entries.flatten() {
                // `missions/` is the one carve-out: the session's own
                // mission dir is under it (see the sibling sweep below).
                if entry.file_name().as_os_str() == std::ffi::OsStr::new("missions") {
                    continue;
                }
                let path = entry.path();
                match std::fs::symlink_metadata(&path) {
                    Ok(metadata) if metadata.file_type().is_dir() => dirs.push(path),
                    // A symlink is denied as a file: denying the LINK is
                    // what stops a session replacing it, and following it
                    // would deny some unrelated target instead.
                    Ok(_) => files.push(path),
                    Err(_) => {}
                }
            }
        }
        if let Ok(entries) = std::fs::read_dir(&missions_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path == mission_dir {
                    continue;
                }
                dirs.push(path);
            }
        }
    }
    WriteDenySet {
        files: sorted_dedup(files),
        dirs: sorted_dedup(dirs),
    }
}

/// Seatbelt-only companion to [`authority_write_denies`]: directory roots
/// whose DIRECT children may not be created or replaced, emitted as a
/// `^<root>/[^/]*$` write-deny regex. Sealing `<repo>/.kranz` stops a
/// session creating `.kranz/queue/` (or any future engine store) after the
/// profile was built; sealing `<repo>/.kranz/missions` stops it fabricating
/// a sibling mission dir to forge approvals into. Neither seal reaches
/// GRANDchildren, so the session's own `<mission>/runs/<scratch>` stays
/// writable.
pub(crate) fn sealed_kranz_dir_roots(inputs: &SandboxInputs) -> Vec<PathBuf> {
    let mut roots = Vec::new();
    for (kranz_dir, missions_dir, _) in repo_kranz_dirs(inputs) {
        roots.push(kranz_dir);
        roots.push(missions_dir);
    }
    sorted_dedup(roots)
}

/// The operator's OWN controlling terminal, in raw and canonical form
/// (2026-09-01 adversarial audit, H7).
///
/// The gate profile grants read/write/`file-ioctl` on the pty device class
/// `^/dev/tty[p-t][0-9a-f]+$` so the validator harness's `openpty` chain
/// works. On macOS that pool IS the terminal pool: a Terminal.app session is
/// `/dev/ttys003`, matched by the same regex. A contained gate command could
/// therefore open the operator's own terminal, write raw escape sequences to
/// it, or issue `TIOCSTI` to push characters into the operator's shell —
/// arbitrary execution as the operator, outside the sandbox. Naming the
/// parent's terminal explicitly lets both profiles DENY exactly that one
/// device while keeping the pty pair the harness allocates for itself; SBPL
/// denies beat allows regardless of clause order, which this file already
/// relies on throughout.
///
/// Resolved from the ENGINE's own fds 0/1/2 at profile-build time. Every
/// child the engine spawns gets piped or null stdio, so no sandboxed process
/// legitimately holds this device. An empty result (no tty at all: a daemon,
/// CI, `kranz serve`) emits nothing extra.
#[cfg(unix)]
pub(crate) fn operator_tty_paths() -> Vec<PathBuf> {
    let mut paths = Vec::new();
    for fd in [0, 1, 2] {
        // SAFETY: `isatty` and `ttyname_r` take a plain fd and, for the
        // latter, a caller-owned buffer with its length; no ownership
        // crosses. `ttyname_r` is the thread-safe form (`ttyname` returns a
        // shared static buffer).
        let name = unsafe {
            if libc::isatty(fd) != 1 {
                continue;
            }
            let mut buffer = [0 as libc::c_char; 1024];
            if libc::ttyname_r(fd, buffer.as_mut_ptr(), buffer.len()) != 0 {
                continue;
            }
            std::ffi::CStr::from_ptr(buffer.as_ptr())
                .to_string_lossy()
                .into_owned()
        };
        if name.is_empty() {
            continue;
        }
        let path = PathBuf::from(name);
        paths.push(absolutize(&path));
        paths.push(path);
    }
    sorted_dedup(paths)
}

#[cfg(not(unix))]
pub(crate) fn operator_tty_paths() -> Vec<PathBuf> {
    Vec::new()
}

/// Render the operator-terminal deny block for `paths` (2026-09-01
/// adversarial audit, H7). Empty in, empty out: a host with no controlling
/// terminal has nothing to protect, and an empty `(deny …)` block would be
/// noise in every CI profile. Shared by [`generate_profile`] and the gate
/// extras (`crate::command_exec::gate_profile_extras`) so the two cannot
/// render the same guard differently. Parameterized on the paths rather
/// than calling [`operator_tty_paths`] itself, so the rendering is testable
/// on a host whose test runner has no tty.
pub(crate) fn tty_deny_block(paths: &[PathBuf]) -> String {
    let literals: std::collections::BTreeSet<String> =
        paths.iter().map(|path| escape_sbpl_literal(path)).collect();
    if literals.is_empty() {
        return String::new();
    }
    let mut block = String::from("(deny file-read* file-write* file-ioctl\n");
    for literal in &literals {
        block.push_str(&format!("  (literal \"{literal}\")\n"));
    }
    block.push_str(")\n");
    block
}

/// Refuse Git configurations whose complete input set this sandbox cannot
/// protect. The enforcement protects against contained children; a separate
/// unsandboxed host process can still change the repository concurrently.
pub(crate) fn validate_git_config_protection(
    inputs: &SandboxInputs,
    mount_based: bool,
) -> crate::error::Result<()> {
    let writable = write_allowlist(inputs);
    let neutral_config = absolutize(crate::git_ops::empty_global_config_path()?);
    if writable.iter().any(|root| neutral_config.starts_with(root)) {
        return Err(crate::error::EngineError::Backend(
            "cannot grant sandbox writes over the engine's neutral Git configuration; narrow the overlapping session, scratch, or extraWrite root".into(),
        ));
    }
    let Some(marker) = git_marker(&inputs.session_cwd) else {
        return Ok(());
    };
    let root = marker.parent().expect("git marker has a parent");
    let repo = crate::git_ops::GitRepo::open(root)?;
    let (git_dir, common, worktree_enabled) = repo.config_protection_paths()?;
    let described = git_metadata_dirs(&inputs.session_cwd);
    if [&git_dir, &common].iter().any(|dir| {
        !described
            .iter()
            .any(|path| absolutize(path) == absolutize(dir))
    }) {
        return Err(crate::error::EngineError::Backend(
            "cannot protect Git metadata redirected outside the session's Git layout; remove repository environment overrides before running an enforced session".into(),
        ));
    }
    let masks = authority_directory_masks(inputs);
    let mut graph_dirs = vec![git_dir.clone(), common.clone()];
    graph_dirs.extend(git_metadata_mount_nodes(inputs));
    if graph_dirs.iter().any(|dir| {
        let dir = absolutize(dir);
        // A shared Git directory outside writable roots remains read-only;
        // its existing read-only authority view needs no writable node bind.
        if !writable.iter().any(|root| dir.starts_with(root)) {
            return false;
        }
        masks.iter().any(|mask| {
            dir.starts_with(&mask.path)
                && ![&inputs.session_cwd, &inputs.tmpdir].iter().any(|private| {
                    let private = absolutize(private);
                    private != mask.path
                        && private.starts_with(&mask.path)
                        && dir.starts_with(private)
                })
        })
    }) {
        return Err(crate::error::EngineError::Backend(
            "cannot protect Git metadata through an authority directory; keep the Git directory outside .kranz and credential stores".into(),
        ));
    }
    let mut sources = vec![common.join("config")];
    if marker.is_file() {
        sources.push(marker.clone());
        sources.push(git_dir.join("commondir"));
    }
    if worktree_enabled {
        sources.push(git_dir.join("config.worktree"));
    }
    for source in sources {
        let writable_source = writable
            .iter()
            .any(|root| absolutize(&source).starts_with(root));
        // A symlink input (or replaceable symlink ancestor) defeats a path-only
        // deny. System aliases outside writable roots, such as /var, are fine.
        for ancestor in source.ancestors() {
            if std::fs::symlink_metadata(ancestor).is_ok_and(|meta| meta.file_type().is_symlink())
                && (ancestor == source
                    || writable.iter().any(|root| {
                        ancestor
                            .parent()
                            .map(absolutize)
                            .map(|parent| parent.join(ancestor.file_name().unwrap_or_default()))
                            .is_some_and(|path| path.starts_with(root))
                    }))
            {
                return Err(crate::error::EngineError::Backend(format!(
                    "cannot protect Git configuration through symlink {}; use regular Git metadata paths", ancestor.display()
                )));
            }
        }
        match std::fs::symlink_metadata(&source) {
            Ok(meta) if meta.is_file() => {
                #[cfg(unix)]
                {
                    use std::os::unix::fs::MetadataExt;
                    if meta.nlink() != 1 {
                        return Err(crate::error::EngineError::Backend(format!(
                            "cannot protect multiply linked Git configuration {}; replace it with a private regular file", source.display()
                        )));
                    }
                }
            }
            Err(error)
                if error.kind() == std::io::ErrorKind::NotFound
                    && (!mount_based || !writable_source) => {}
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                return Err(crate::error::EngineError::Backend(format!(
                    "cannot protect absent active Git configuration {} with a mount sandbox; create the intended regular config file before running, or disable extensions.worktreeConfig", source.display()
                )));
            }
            _ => {
                return Err(crate::error::EngineError::Backend(format!(
                    "cannot protect Git configuration {}; expected a regular file",
                    source.display()
                )))
            }
        }
    }
    Ok(())
}

fn git_marker(cwd: &Path) -> Option<PathBuf> {
    cwd.ancestors()
        .map(|path| path.join(".git"))
        .find(|path| std::fs::symlink_metadata(path).is_ok())
}

/// Follow only the two bounded Git indirection files to describe denies. The
/// execution boundary validates the layout using Git itself before spawning.
fn git_metadata_dirs(cwd: &Path) -> Vec<PathBuf> {
    let Some(marker) = git_marker(cwd) else {
        return vec![cwd.join(".git")];
    };
    let read = |path: &Path| {
        std::fs::File::open(path)
            .ok()
            .and_then(|file| crate::paths::read_regular_file_bounded(file, 16384).ok())
    };
    if marker.is_dir() {
        return vec![marker];
    }
    let Some(link) = read(&marker) else {
        return Vec::new();
    };
    let Some(path) = link.trim().strip_prefix("gitdir: ") else {
        return Vec::new();
    };
    let dir = absolutize(&marker.parent().unwrap().join(path));
    let mut dirs = vec![dir.clone()];
    if let Some(common) = read(&dir.join("commondir")) {
        dirs.push(absolutize(&dir.join(common.trim())));
    }
    dirs
}

/// Pin writable metadata directory nodes as mountpoints, so renaming a parent
/// cannot replace a protected config path. The directories stay writable for
/// Git's index/ref lock files; named configuration inputs are mounted read-only.
pub(crate) fn git_metadata_mount_nodes(inputs: &SandboxInputs) -> Vec<PathBuf> {
    let writable = write_allowlist(inputs);
    let mut nodes = std::collections::BTreeSet::new();
    let mut dirs = git_metadata_dirs(&inputs.session_cwd);
    if let Some(marker) = git_marker(&inputs.session_cwd).filter(|path| path.is_file()) {
        dirs.push(
            marker
                .parent()
                .expect("git marker has a parent")
                .to_path_buf(),
        );
    }
    for dir in dirs {
        for path in absolutize(&dir).ancestors() {
            if writable
                .iter()
                .any(|root| path.starts_with(root) && path != root)
                && path.is_dir()
            {
                nodes.insert(path.to_path_buf());
            }
        }
    }
    nodes.into_iter().collect()
}

/// The `.git` metadata a sandboxed session must never write (2026-09-01
/// adversarial audit H3 support).
///
/// The engine runs git IN the tree the worker controls: `commit_dirty_paths`
/// checkpoints after every feature on a hardened handle
/// (`orchestrator.rs`), and `push_mission_branch` pushes from the CLI. A
/// worker that plants `.git/hooks/pre-commit`, sets `core.fsmonitor` /
/// `core.sshCommand` in `.git/config`, or rewrites the WORKTREE GITLINK to
/// point at a `.git` dir of its own making gets host execution with the
/// engine's full environment, outside every sandbox.
///
/// The deny is NARROW on purpose: the worker's own role is to commit (see
/// `prompts/worker.md` step 6), so `.git/index`, `.git/objects`,
/// `.git/refs`, and `.git/logs` must stay writable. What is denied is the
/// config-and-hook surface that turns a later engine-side git invocation
/// into code execution, plus the gitlink FILE form:
///
/// - `<cwd>/.git/hooks/` and `<cwd>/.git/info/` (subtrees),
/// - `<cwd>/.git/modules/` (subtree) — a submodule keeps its own `config`
///   and `hooks/` under `.git/modules/<name>/`, the SAME host-execution
///   surface one level down, and in checkout mode it sits inside the rw
///   session bind (follow-up review, M-9). Denied as a whole subtree so a
///   submodule added after the profile was built is covered too; git never
///   needs to write it from inside the sandbox.
/// - `<cwd>/.git/config` and `<cwd>/.git/config.worktree` (files),
/// - `<cwd>/.git` itself as a LITERAL — in worktree mode that path is the
///   gitlink file, and denying the literal stops a rewrite of it; in
///   checkout mode it is the directory node, where the literal deny stops a
///   replace of the directory without touching anything beneath it.
///
/// Reads stay allowed throughout: git cannot operate without reading its
/// own config, and secrecy was never this tier's promise.
pub(crate) fn git_metadata_write_denies(inputs: &SandboxInputs) -> WriteDenySet {
    let mut files = git_metadata_mount_nodes(inputs);
    let mut dirs = Vec::new();
    for cwd in [inputs.session_cwd.clone(), absolutize(&inputs.session_cwd)] {
        files.push(cwd.join(".git"));
        if let Some(marker) = git_marker(&cwd) {
            files.push(marker);
        }
        for git in git_metadata_dirs(&cwd) {
            files.push(git.join("config"));
            files.push(git.join("config.worktree"));
            files.push(git.join("commondir"));
            dirs.push(git.join("hooks"));
            dirs.push(git.join("info"));
            dirs.push(git.join("modules"));
        }
    }
    WriteDenySet {
        files: sorted_dedup(files),
        dirs: sorted_dedup(dirs),
    }
}

/// One entry of the validator read-deny set: a top-level path of a real
/// checkout root the validator must not read, classified so the Seatbelt
/// profile can pick `subpath` vs `literal` and the bwrap argv can pick a
/// tmpfs shadow vs a `/dev/null` mask.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct ValidatorReadDenyEntry {
    pub path: PathBuf,
    pub is_dir: bool,
}

/// Top-level names a validator read-deny root ALWAYS keeps readable, because
/// the validator's own machinery cannot work without them:
///
/// - `.git` — the shared git directory. The snapshot is a WORKTREE: its
///   `.git` file points into `<root>/.git/worktrees/<n>`, and every
///   `git log`/`diff`/`show` the scrutiny/inspection flow runs resolves
///   objects and refs through the common dir. This is the narrow
///   `.git` surface the ticket keeps: READABLE (the fold needs it), never
///   writable (deny-default; a ref move is the tripwire's `for-each-ref`
///   half). `.git/config` stays readable for the same reason git itself
///   reads it — the same posture today's broad-read sandbox has.
/// - `.kranz` — the mission dir lives here, and the validator's snapshot
///   worktree sits under it (`<root>/.kranz/missions/<id>/runs/`). The
///   engine-owned metadata inside stays write-denied
///   ([`mission_write_denies`]) and the authority files read-denied
///   ([`authority_read_deny_paths`]) exactly as for any session; the rest
///   (tracked `workspace.json`, tickets) is content the snapshot already
///   carries.
const VALIDATOR_READ_DENY_CARVEOUTS: &[&str] = &[".git", ".kranz"];

/// The validator read-deny set (ticket `validator-mandatory-containment`):
/// every TOP-LEVEL entry of each [`SandboxInputs::validator_read_deny_roots`]
/// root EXCEPT the [`VALIDATOR_READ_DENY_CARVEOUTS`]. Denying whole top-level
/// entries covers the source tree without naming the root itself as a
/// subpath (which would swallow the carved-out `.git`/`.kranz` beneath it —
/// SBPL denies take precedence over every allow, so no allow could carve
/// them back out).
///
/// Entries are classified by `std::fs::metadata` — which FOLLOWS symlinks —
/// so a symlinked top-level dir is denied as a dir (and the canonical form
/// emitted alongside covers the link TARGET, the same raw+canonical idiom
/// [`authority_read_deny_paths`] uses; Seatbelt matches canonical paths).
/// Entries whose metadata fails (a broken symlink, a racer's unlink) are
/// skipped: a dangling link leaks nothing, and a vanished entry is gone.
///
/// The root ITSELF is not in this set: a literal deny on the root dir would
/// block stat/readdir of it, and coreutils `mkdir -p` stats every ancestor
/// of an absolute path — denying the root broke `mkdir -p` under the
/// snapshot (probed 2026-08-04). The root's directory LISTING therefore
/// stays readable on both tiers (names, never contents — the bwrap side
/// cannot express a listing deny without masking the carve-outs anyway).
///
/// One documented residual gap, outside the threat model (validator code can
/// create NOTHING at a deny root — writes there are deny-default): an entry
/// created at a root AFTER profile generation is not in the set — the same
/// spawn-time shape the bwrap authority masks already accept.
pub(crate) fn validator_read_deny_entries(inputs: &SandboxInputs) -> Vec<ValidatorReadDenyEntry> {
    let mut entries = std::collections::BTreeSet::new();
    for root in &inputs.validator_read_deny_roots {
        let Ok(read_dir) = std::fs::read_dir(root) else {
            continue;
        };
        for entry in read_dir.flatten() {
            let name = entry.file_name();
            if VALIDATOR_READ_DENY_CARVEOUTS.contains(&name.to_string_lossy().as_ref()) {
                continue;
            }
            let path = entry.path();
            let Ok(metadata) = std::fs::metadata(&path) else {
                continue;
            };
            let is_dir = metadata.is_dir();
            entries.insert(ValidatorReadDenyEntry {
                path: path.clone(),
                is_dir,
            });
            let canonical = absolutize(&path);
            if canonical != path {
                entries.insert(ValidatorReadDenyEntry {
                    path: canonical,
                    is_dir,
                });
            }
        }
    }
    entries.into_iter().collect()
}

/// Default Anthropic egress plus mission-configured additions, trimmed and
/// de-duplicated in stable order.
pub fn effective_egress(configured: &[String]) -> Vec<String> {
    let mut out: Vec<String> = DEFAULT_EGRESS.iter().map(|s| (*s).to_string()).collect();
    for item in configured {
        let item = item.trim();
        if !item.is_empty() && !out.iter().any(|existing| existing == item) {
            out.push(item.to_string());
        }
    }
    out
}

/// Generate an SBPL profile: deny-by-default, broad read (Seatbelt cannot
/// usefully scope toolchain/dyld reads without breaking `/bin/sh`) with the
/// [`authority_read_deny_paths`]/[`authority_read_deny_dirs`] carve-out,
/// write limited to subpaths of
/// `session_cwd`, the session-private scratch `tmpdir`, and each
/// `extra_write` entry — with the mission metadata of
/// [`mission_write_denies`] carved back OUT by explicit write denies, so the
/// audit log / state snapshot / control inbox / transcripts stay read-only
/// to the session even in checkout mode (where `session_cwd` is the repo
/// root and the mission dir sits under it). `fs` allows network — the profile wraps the agent
/// binary itself, so denying egress bricks Anthropic/API sessions; write
/// containment is the fs-tier promise. `fs+net` restricts outbound TCP to
/// loopback: Seatbelt rejects hostname egress rules (`host must be * or
/// localhost`), so the per-host allowlist is enforced by the run's egress
/// proxy (`crate::egress_proxy`) — the only reachable way out. The
/// operator's real Cargo registry/git caches carry an explicit write deny
/// of their own (13th-pass review, P1 — [`cargo_cache_write_deny_paths`]):
/// the isolated contract home may LINK them in above the copy ceiling, and
/// the linked target must stay read-only under every allow.
///
/// Mandatory validator containment (ticket `validator-mandatory-containment`):
/// when [`SandboxInputs::validator_read_deny_roots`] is non-empty (validator
/// sessions only), a second read-deny block closes the broad read allow over
/// the REAL checkout's source tree — every top-level entry of each root
/// except the `.git`/`.kranz` carve-outs ([`validator_read_deny_entries`]) —
/// plus the `/dev/null` write allow every shell/git needs under deny-default
/// (the gate wrap's documented finding). The root's own listing stays
/// readable (names, never contents — a literal deny on the root breaks
/// `mkdir -p` under the snapshot, which stats every ancestor; the bwrap
/// side cannot express the listing deny at all). The snapshot worktree
/// (under `<root>/.kranz/...`) and the shared git dir stay readable; the
/// validator provably reads only its snapshot's contents. Denies take
/// precedence over the broad allow regardless of clause order (the same
/// guarantee the authority deny above relies on). Every Seatbelt session
/// also keeps `/dev/null` writable: shells, Git, and agent tool runners use
/// it for ordinary redirects even outside validator sessions.
pub fn generate_profile(inputs: &SandboxInputs) -> String {
    let write_paths = write_allowlist(inputs);

    let mut profile = String::new();
    profile.push_str("(version 1)\n");
    profile.push_str("(deny default)\n");
    profile.push('\n');
    profile.push_str("(allow process*)\n");
    profile.push_str("(allow signal (target self))\n");
    profile.push_str("(allow sysctl-read)\n");
    profile.push_str("(allow mach-lookup)\n");
    profile.push_str("(allow mach-register)\n");
    profile.push_str("(allow iokit-open)\n");
    profile.push('\n');
    // Reads stay broad: Seatbelt cannot usefully express "toolchain + dyld +
    // locale" without a long allowlist that still breaks `/bin/sh` redirects.
    // Secrecy is not the fs-tier promise — write containment is — with ONE
    // carve-out: the authority material below.
    profile.push_str("(allow file-read*)\n");
    profile.push('\n');
    // Serve tokens, the repo config, the plaintext lint vocabulary, the
    // hook-status projection, and the control inbox must stay unreadable even
    // under the broad read allow (see authority_read_deny_paths /
    // authority_read_deny_dirs). SBPL denies take precedence over allows
    // regardless of clause order (verified with sandbox-exec), so placing
    // the deny after the allow is documentary.
    let mut deny_literals = std::collections::BTreeSet::new();
    for path in authority_read_deny_paths(inputs) {
        deny_literals.insert(escape_sbpl_literal(&path));
    }
    let mut deny_subpaths = std::collections::BTreeSet::new();
    for dir in authority_read_deny_dirs(inputs) {
        deny_subpaths.insert(escape_sbpl_literal(&dir));
    }
    if !deny_literals.is_empty() || !deny_subpaths.is_empty() {
        profile.push_str("(deny file-read*\n");
        for lit in &deny_subpaths {
            profile.push_str(&format!("  (subpath \"{lit}\")\n"));
        }
        for lit in &deny_literals {
            profile.push_str(&format!("  (literal \"{lit}\")\n"));
        }
        profile.push_str(")\n");
        profile.push('\n');
    }
    // Mandatory validator containment (see the fn doc): read-deny the real
    // checkout's source tree. Directories deny as subpaths (the whole
    // subtree), files as literals. Deny wins over the broad read allow
    // regardless of clause order — placement after it is documentary. The
    // root ITSELF is deliberately NOT denied: a literal deny on the root
    // dir blocks stat/readdir of it, and coreutils `mkdir -p` stats every
    // ancestor of an absolute path — denying the root broke `mkdir -p`
    // under the snapshot (probed 2026-08-04). The root's directory LISTING
    // stays visible (names, never contents) — the same posture the bwrap
    // side is limited to anyway.
    let validator_denies = validator_read_deny_entries(inputs);
    if !validator_denies.is_empty() {
        let mut subpaths = std::collections::BTreeSet::new();
        let mut literals = std::collections::BTreeSet::new();
        for entry in &validator_denies {
            if entry.is_dir {
                subpaths.insert(escape_sbpl_literal(&entry.path));
            } else {
                literals.insert(escape_sbpl_literal(&entry.path));
            }
        }
        profile.push_str("(deny file-read*\n");
        for lit in &subpaths {
            profile.push_str(&format!("  (subpath \"{lit}\")\n"));
        }
        for lit in &literals {
            profile.push_str(&format!("  (literal \"{lit}\")\n"));
        }
        profile.push_str(")\n");
        profile.push('\n');
    }
    // `/dev/null` must stay writable even under deny-default (the gate
    // wrap's documented finding, `gate_profile_extras` — probed
    // 2026-08-03): Git, shells, and agent tool runners open it O_RDWR in
    // ordinary operation. This applies to every session, not only the
    // validator shape above.
    profile.push_str("(allow file-write* (literal \"/dev/null\"))\n");
    profile.push('\n');
    match inputs.enforce {
        crate::types::SandboxEnforce::FsNet => {
            // Loopback-only egress: the session's proxy hops (CONNECT to
            // 127.0.0.1) are legal, and every non-localhost destination is
            // denied here at the kernel boundary — the egress proxy is the
            // only way out and applies the hostname allowlist.
            profile.push_str("(allow network-outbound (remote tcp \"localhost:*\"))\n");
        }
        // `fs` (and Off) must allow network: this profile wraps the agent
        // binary, so `deny network*` bricks API egress. Egress restriction
        // is an `fs+net` concern.
        crate::types::SandboxEnforce::Fs | crate::types::SandboxEnforce::Off => {
            profile.push_str("(allow network*)\n");
        }
    }
    profile.push('\n');
    // Write allowlist: include both the canonical path and the path as given
    // (macOS `/var` ↔ `/private/var`) so shell redirects using either form match.
    profile.push_str("(allow file-write*\n");
    let mut write_literals = std::collections::BTreeSet::new();
    for p in &write_paths {
        write_literals.insert(escape_sbpl_literal(p));
    }
    for raw in [&inputs.session_cwd, &inputs.tmpdir]
        .into_iter()
        .chain(inputs.extra_write.iter())
    {
        write_literals.insert(escape_sbpl_literal(raw));
        write_literals.insert(escape_sbpl_literal(&absolutize(raw)));
    }
    for lit in &write_literals {
        profile.push_str(&format!("  (subpath \"{lit}\")\n"));
    }
    profile.push_str(")\n");
    profile.push('\n');
    // Mission metadata write deny: the allowlist no longer names the mission
    // dir, but in checkout mode `session_cwd` IS the repo root and the
    // mission dir sits under it — without these denies the audit log, state
    // snapshot, control inbox, and transcripts would be writable through the
    // session-cwd subpath allow. SBPL denies take precedence over allows
    // regardless of clause order (the same guarantee the read deny above
    // relies on), so placement after the allow is documentary.
    let write_denies = mission_write_denies(inputs);
    profile.push_str("(deny file-write*\n");
    let mut deny_literals = std::collections::BTreeSet::new();
    for p in &write_denies.files {
        deny_literals.insert(escape_sbpl_literal(p));
    }
    for lit in &deny_literals {
        profile.push_str(&format!("  (literal \"{lit}\")\n"));
    }
    let mut deny_subpaths = std::collections::BTreeSet::new();
    for p in &write_denies.control_dirs {
        deny_subpaths.insert(escape_sbpl_literal(p));
    }
    for lit in &deny_subpaths {
        profile.push_str(&format!("  (subpath \"{lit}\")\n"));
    }
    // Transcripts are `runs/*.jsonl` files directly under the runs dir; the
    // `[^/]*` keeps `runs/` SUBDIRECTORIES (session scratch, preflight
    // worktree) writable.
    let mut deny_regexes = std::collections::BTreeSet::new();
    for p in &write_denies.runs_dirs {
        deny_regexes.insert(escape_sbpl_regex(p));
    }
    for lit in &deny_regexes {
        profile.push_str(&format!("  (regex #\"^{lit}/[^/]*\\.jsonl$\")\n"));
    }
    profile.push_str(")\n");
    profile.push('\n');

    // Authority write deny (2026-09-01 adversarial audit, H2 + H11 — see
    // authority_write_denies for the full why): every path the read deny
    // above names, plus the repo-level `.kranz` stores and every SIBLING
    // mission dir. Under checkout mode `session_cwd` is the repo root, so
    // without this block a contained worker could overwrite the trust root
    // it cannot read, or forge approvals into another mission's inbox.
    // Denies take precedence over allows regardless of clause order, so
    // placement after the write allow is documentary.
    let authority_writes = authority_write_denies(inputs);
    let mut authority_write_literals = std::collections::BTreeSet::new();
    for path in &authority_writes.files {
        authority_write_literals.insert(escape_sbpl_literal(path));
    }
    let mut authority_write_subpaths = std::collections::BTreeSet::new();
    for path in &authority_writes.dirs {
        authority_write_subpaths.insert(escape_sbpl_literal(path));
    }
    // The spawn-time residue the enumeration cannot cover: sealing the
    // DIRECT children of `<repo>/.kranz` and `<repo>/.kranz/missions` stops
    // a session creating a store or a sibling mission dir after the profile
    // was built. `[^/]*` never crosses a separator, so the session's own
    // `<mission>/runs/<scratch>` stays writable.
    let mut sealed_regexes = std::collections::BTreeSet::new();
    for root in sealed_kranz_dir_roots(inputs) {
        sealed_regexes.insert(escape_sbpl_regex(&root));
    }
    if !authority_write_literals.is_empty()
        || !authority_write_subpaths.is_empty()
        || !sealed_regexes.is_empty()
    {
        profile.push_str("(deny file-write*\n");
        for lit in &authority_write_subpaths {
            profile.push_str(&format!("  (subpath \"{lit}\")\n"));
        }
        for lit in &authority_write_literals {
            profile.push_str(&format!("  (literal \"{lit}\")\n"));
        }
        for root in &sealed_regexes {
            profile.push_str(&format!("  (regex #\"^{root}/[^/]*$\")\n"));
        }
        profile.push_str(")\n");
        profile.push('\n');
    }

    // `.git` metadata write deny (2026-09-01 adversarial audit, H3 support —
    // see git_metadata_write_denies): the engine checkpoints with a
    // hardened git handle in the tree the worker controls, so the hook and
    // config surface that turns the next engine-side `git commit` into host
    // execution is denied. Narrow by design — the worker's own role is to
    // commit, so the index, objects, refs and logs stay writable.
    let git_writes = git_metadata_write_denies(inputs);
    let mut git_write_literals = std::collections::BTreeSet::new();
    for path in &git_writes.files {
        git_write_literals.insert(escape_sbpl_literal(path));
    }
    let mut git_write_subpaths = std::collections::BTreeSet::new();
    for path in &git_writes.dirs {
        git_write_subpaths.insert(escape_sbpl_literal(path));
    }
    if !git_write_literals.is_empty() || !git_write_subpaths.is_empty() {
        profile.push_str("(deny file-write*\n");
        for lit in &git_write_subpaths {
            profile.push_str(&format!("  (subpath \"{lit}\")\n"));
        }
        for lit in &git_write_literals {
            profile.push_str(&format!("  (literal \"{lit}\")\n"));
        }
        profile.push_str(")\n");
        profile.push('\n');
    }

    // Operator terminal deny (2026-09-01 adversarial audit, H7 — see
    // operator_tty_paths): the engine's own controlling terminal is denied
    // read, write, AND ioctl. Every child the engine spawns has piped or
    // null stdio, so nothing inside the sandbox needs this device, and the
    // deny is what stops escape-sequence writes and TIOCSTI-class input
    // injection into the operator's shell. Nothing is emitted when the
    // engine has no terminal (a daemon, CI, `kranz serve`).
    let tty_block = tty_deny_block(&operator_tty_paths());
    if !tty_block.is_empty() {
        profile.push_str(&tty_block);
        profile.push('\n');
    }

    profile.push_str("(deny file-write*\n");
    // Match future sibling missions too: enumeration alone would leave an
    // inbox created after this session starts writable under checkout mode.
    if let Some(missions) = inputs
        .mission_dir
        .parent()
        .filter(|path| path.ends_with("missions"))
    {
        for root in [missions.to_path_buf(), absolutize(missions)] {
            let root = escape_sbpl_regex(&root);
            profile.push_str(&format!(
                "  (regex #\"^{root}/[^/]+/(events\\.jsonl(\\.lock)?|state\\.json(\\.tmp)?|estimate\\.json)$\")\n"
            ));
            profile.push_str(&format!("  (regex #\"^{root}/[^/]+/control(/|$)\")\n"));
            profile.push_str(&format!(
                "  (regex #\"^{root}/[^/]+/runs/[^/]*\\.jsonl$\")\n"
            ));
        }
    }
    profile.push_str(")\n");

    // Denying a file alone does not stop renaming its parent directory,
    // which would move authority outside path-based read/write rules.
    // Pin ancestor names without denying ordinary writes to their children.
    let mut pinned_dirs = std::collections::BTreeSet::new();
    for path in authority_read_deny_paths(inputs)
        .into_iter()
        .chain(authority_read_deny_dirs(inputs))
        .chain(mission_write_denies(inputs).control_dirs)
    {
        for parent in path.ancestors().skip(1) {
            pinned_dirs.insert(escape_sbpl_literal(parent));
        }
    }
    profile.push_str("(deny file-write-unlink\n");
    for path in pinned_dirs {
        profile.push_str(&format!("  (literal \"{path}\")\n"));
    }
    if let Some(missions) = inputs
        .mission_dir
        .parent()
        .filter(|p| p.ends_with("missions"))
    {
        for path in [missions.to_path_buf(), absolutize(missions)] {
            profile.push_str(&format!(
                "  (regex #\"^{}/[^/]+(/(control|runs))?$\")\n",
                escape_sbpl_regex(&path)
            ));
        }
    }
    profile.push_str(")\n");

    // Shared-Cargo-cache write deny (13th-pass review, P1 — see
    // cargo_cache_write_deny_paths for the full why): when the shared
    // registry/git cache exceeds the copy ceiling, the isolated contract
    // home LINKS it in, and only an EXPLICIT deny keeps the link target
    // read-only under every allow (an operator extraWrite of $HOME would
    // otherwise re-widen it to worker-authored contract code). Precise
    // scope: registry/ and git/ only. Denies take precedence over allows
    // regardless of clause order (the same guarantee the blocks above
    // rely on), so placement after the allow is documentary.
    let mut cache_denies = std::collections::BTreeSet::new();
    for path in cargo_cache_write_deny_paths() {
        cache_denies.insert(escape_sbpl_literal(&path));
    }
    if !cache_denies.is_empty() {
        profile.push_str("(deny file-write*\n");
        for lit in &cache_denies {
            profile.push_str(&format!("  (subpath \"{lit}\")\n"));
        }
        profile.push_str(")\n");
    }

    profile
}

/// Build the bubblewrap argv tail for running `binary args` under the resolved
/// sandbox. The caller uses program `bwrap` and passes this vector as args.
///
/// Write scope mirrors the Seatbelt profile: the whole filesystem is bound
/// read-only, then `session_cwd`, the session-private scratch `tmpdir`, and
/// each `extra_write` entry are bound writable — the mission dir and the
/// shared system temp root are NOT writable (ticket sandbox-writable-scope).
/// Mission metadata that an rw ancestor bind would otherwise cover (checkout
/// mode) is masked back out, the bwrap analogue of the profile's write deny;
/// the operator's real Cargo registry/git caches get explicit stacked
/// ro-binds for the same reason (13th-pass review — they stay readable, a
/// linked cache is the session's registry, but never writable).
///
/// Mandatory validator containment (ticket `validator-mandatory-containment`
/// — the bwrap analogue of the profile's validator read-deny block): when
/// [`SandboxInputs::validator_read_deny_roots`] is non-empty, each top-level
/// source-tree entry of those roots ([`validator_read_deny_entries`]) is
/// masked — directories shadowed by an empty tmpfs, files by a `/dev/null`
/// ro-bind — so the whole-fs ro-bind no longer exposes the real checkout's
/// contents. The `.git`/`.kranz` carve-outs stay (git needs the shared
/// object store; the snapshot lives under `.kranz`). The root's own
/// directory LISTING stays visible on both tiers (names, never contents):
/// bwrap cannot close it without masking the carve-outs, and the Seatbelt
/// side declines to (a literal deny on the root breaks `mkdir -p` under
/// the snapshot). `/dev/null` needs no allow here — the bwrap argv mounts
/// a real `/dev` (`--dev /dev`).
pub fn bubblewrap_args(
    inputs: &SandboxInputs,
    binary: &Path,
    args: &[String],
) -> crate::error::Result<Vec<String>> {
    let mut out = vec![
        "--die-with-parent".to_string(),
        "--ro-bind".to_string(),
        "/".to_string(),
        "/".to_string(),
        "--dev".to_string(),
        "/dev".to_string(),
        "--proc".to_string(),
        "/proc".to_string(),
        // Namespace set (2026-09-01 adversarial audit, H8). Before it the
        // argv unshared ONLY the network namespace, and only under `fs+net`:
        //
        // - `--unshare-pid` is what makes `--proc /proc` mean what the mount
        //   above assumes. Without it the contained agent sees HOST procfs
        //   and can read `/proc/<engine pid>/environ` — precisely the set
        //   `agent_env`'s env_clear exists to keep away from a
        //   prompt-injectable child — on any host with
        //   `kernel.yama.ptrace_scope = 0`. It also stops the agent
        //   signalling the engine or any same-uid host process.
        // - `--unshare-ipc` closes the System V / POSIX IPC channel to host
        //   processes.
        // - `--unshare-uts` and `--unshare-cgroup-try` keep hostname and
        //   cgroup views from being host-identifying or host-mutable. The
        //   `-try` suffix is load-bearing (follow-up review, M-8): cgroup
        //   namespaces need Linux >= 4.6 and are unavailable in some nested
        //   container and hardened-kernel environments, where the plain
        //   `--unshare-cgroup` makes bwrap EXIT non-zero — and every resolver
        //   in this file fails closed, so the whole session would die rather
        //   than degrade by one namespace. `--unshare-pid`/`ipc`/`uts` are
        //   long-supported and stay unconditional.
        // - `--new-session` drops the controlling terminal, which is the
        //   Linux half of the TIOCSTI escape H7 names on macOS (still live
        //   on kernels built with CONFIG_LEGACY_TIOCSTI). Safe here: every
        //   child the engine spawns gets piped or null stdio, and the pty
        //   harness passes its OWN slave fd rather than relying on an
        //   inherited ctty.
        //
        // Unconditional, unlike `--unshare-net` below: none of these is an
        // egress decision, and `fs` is a containment tier too.
        "--unshare-pid".to_string(),
        "--unshare-ipc".to_string(),
        "--unshare-uts".to_string(),
        "--unshare-cgroup-try".to_string(),
        "--new-session".to_string(),
    ];
    if inputs.enforce == crate::types::SandboxEnforce::FsNet {
        out.push("--unshare-net".to_string());
    }
    for path in write_allowlist(inputs) {
        let path = path.display().to_string();
        out.push("--bind".to_string());
        out.push(path.clone());
        out.push(path);
    }
    // Keep the mission namespace read-only, including siblings created
    // after spawn. A validator snapshot or private scratch nested here
    // gets its own writable bind back before the metadata masks below.
    if let Some(missions) = inputs
        .mission_dir
        .parent()
        .filter(|path| path.ends_with("missions") && path.is_dir())
    {
        let missions = absolutize(missions);
        let display = missions.display().to_string();
        out.extend(["--ro-bind".to_string(), display.clone(), display]);
        for private in [&inputs.session_cwd, &inputs.tmpdir] {
            let private = absolutize(private);
            if private.starts_with(&missions) && private != missions {
                let display = private.display().to_string();
                out.extend(["--bind".to_string(), display.clone(), display]);
            }
        }
    }
    // The bwrap analogue of the profile's shared-Cargo-cache write deny
    // (13th-pass review, P1 — cargo_cache_write_deny_paths): the `/`
    // ro-bind already mounts the real caches read-only, but an rw bind
    // covering an ancestor (an extraWrite of $HOME) would silently
    // re-widen them — stack an explicit ro-bind OVER each cache dir
    // present at spawn (later binds win; the destination must exist,
    // hence the is_dir filter). The dir stays READABLE — a linked cache
    // is the session/gate's registry — only writes close. This
    // behavior is also enforced by the private Cargo-home namespace below,
    // which keeps later credential/cache creation out of the session.
    let cache_ro_binds: std::collections::BTreeSet<String> = cargo_cache_write_deny_paths()
        .iter()
        .filter(|path| path.is_dir())
        .map(|path| path.display().to_string())
        .collect();
    for bind in &cache_ro_binds {
        out.push("--ro-bind".to_string());
        out.push(bind.clone());
        out.push(bind.clone());
    }
    // The bwrap analogue of the profile's authority and `.git` write denies
    // (2026-09-01 adversarial audit, H2 + H11 + H3 support): bwrap has no
    // per-path write deny to stack over an rw bind, so each denied path is
    // ro-bound OVER ITSELF — the contents stay READABLE (git cannot run
    // without its own config, and the Seatbelt side denies writes only) while
    // every write closes. Later binds win: install these after the initial
    // writable roots, and restore them after any private-root rebind below.
    //
    // Private authority directory views below close both reads and writes,
    // including authority files created after launch. These extra ro-binds
    // cover readable policy and Git metadata outside those views. For that
    // Git configuration surface, active absent inputs are refused before
    // spawn. Inactive config.worktree cannot become active while the main
    // config is immutable. Writable self-binds pin metadata directory nodes
    // against rename without closing the index/object/ref lockfile paths.
    // Do not directly bind READ-denied paths: their private directory view
    // owns the destination. A host bind stacked over a mask would restore
    // the credential the mask is meant to hide.
    // The write-deny set is a superset of the read-deny set by
    // construction, so subtract the masked paths and everything beneath a
    // masked directory before binding.
    let masked_files: Vec<PathBuf> = authority_read_deny_paths(inputs)
        .iter()
        .map(|p| lexical_absolute(p))
        .collect();
    let masked_dirs: Vec<PathBuf> = authority_read_deny_dirs(inputs)
        .iter()
        .map(|p| lexical_absolute(p))
        .collect();
    let is_masked = |path: &Path| -> bool {
        let abs = lexical_absolute(path);
        masked_files.contains(&abs) || masked_dirs.iter().any(|d| abs.starts_with(d))
    };
    let git_mount_nodes = git_metadata_mount_nodes(inputs);
    for node in &git_mount_nodes {
        let node = node.display().to_string();
        out.extend(["--bind".to_string(), node.clone(), node]);
    }
    let authority_writes = authority_write_denies(inputs);
    let git_writes = git_metadata_write_denies(inputs);
    let write_ro_binds: std::collections::BTreeSet<String> = authority_writes
        .files
        .iter()
        .chain(authority_writes.dirs.iter())
        .filter(|path| path.exists())
        .chain(
            git_writes
                .files
                .iter()
                .filter(|path| path.is_file() && !path.is_symlink()),
        )
        .chain(git_writes.dirs.iter().filter(|path| path.is_dir()))
        .filter(|path| !is_masked(path))
        .map(|path| lexical_absolute(path).display().to_string())
        .collect();
    for bind in &write_ro_binds {
        out.push("--ro-bind".to_string());
        out.push(bind.clone());
        out.push(bind.clone());
    }
    // Reject hostile metadata leaves before constructing read-only views.
    // Missing state/transcript files stay absent in the private namespace;
    // no host-side state.json.tmp placeholder is needed.
    let write_denies = mission_write_denies(inputs);
    for path in &write_denies.files {
        match std::fs::symlink_metadata(path) {
            Ok(metadata) if metadata.file_type().is_file() => {}
            Ok(_) => {
                return Err(crate::error::EngineError::InvalidState(format!(
                    "bwrap mask prep: {} exists and is not a regular file",
                    path.display()
                )))
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error.into()),
        }
    }
    let authority_dirs: Vec<_> = authority_read_deny_dirs(inputs)
        .iter()
        .map(|path| absolutize(path))
        .collect();
    let authority_masks = authority_directory_masks(inputs);
    for mask in &authority_masks {
        let display = mask.path.display().to_string();
        out.extend(["--tmpfs".to_string(), display.clone()]);
        for path in &mask.visible_entries {
            let path = path.display().to_string();
            // Ordinary entries can disappear after enumeration (for example,
            // another gate's temporary cache). Leaving a missing entry hidden
            // is safe; the enclosing mask and read-only remount remain required.
            out.extend(["--ro-bind-try".to_string(), path.clone(), path]);
        }
        // A deeper mask may replace an entry hidden by this one (e.g.
        // HOME/.kranz below a HOME mask for a missing Cargo home). Reserve
        // its empty mountpoint in the private tmpfs before sealing it.
        for nested in &authority_masks {
            if nested.path != mask.path
                && nested.path.starts_with(&mask.path)
                && !mask
                    .visible_entries
                    .iter()
                    .any(|entry| nested.path.starts_with(entry))
            {
                out.extend(["--dir".to_string(), nested.path.display().to_string()]);
            }
        }
        out.extend(["--remount-ro".to_string(), display]);
        // A snapshot or session-private scratch under .kranz remains writable.
        // Later (deeper) masks still hide its own authority directories.
        for private in [&inputs.session_cwd, &inputs.tmpdir] {
            let private = absolutize(private);
            if private != mask.path
                && private.starts_with(&mask.path)
                && !authority_dirs
                    .iter()
                    .any(|denied| private.starts_with(denied))
            {
                let path = private.display().to_string();
                out.extend(["--bind".to_string(), path.clone(), path.clone()]);
                for node in git_mount_nodes
                    .iter()
                    .filter(|node| node.starts_with(&private))
                {
                    let node = node.display().to_string();
                    out.extend(["--bind".to_string(), node.clone(), node]);
                }
                // Host-source binds replace every nested mount. Restore the
                // write denies this private root just covered, before deeper
                // authority masks hide their secrets. Rebinding denied host
                // directories after those masks would expose them again.
                let restored_denies: std::collections::BTreeSet<_> = cache_ro_binds
                    .iter()
                    .chain(&write_ro_binds)
                    .filter_map(|denied| {
                        let denied_path = Path::new(denied);
                        if denied_path.starts_with(&private) {
                            Some(denied)
                        } else if private.starts_with(denied_path) {
                            Some(&path)
                        } else {
                            None
                        }
                    })
                    .collect();
                for denied in restored_denies {
                    out.extend(["--ro-bind".to_string(), denied.clone(), denied.clone()]);
                }
            }
        }
    }
    // The bwrap analogue of the profile's validator read-deny block (ticket
    // validator-mandatory-containment — see the fn doc): shadow each real
    // source-tree entry so the whole-fs ro-bind stops exposing it. Dirs get
    // an empty tmpfs (the existing control/-shadow idiom), files a
    // /dev/null ro-bind (the authority-mask idiom). Entries were enumerated
    // from the live fs and exist at spawn; later binds win, and this block
    // lands after every bind and authority view, so neither can re-expose a
    // denied entry — the carve-outs (`.git`, `.kranz`) were never in the
    // set, so the snapshot and the shared git dir stay as their binds left
    // them.
    for entry in validator_read_deny_entries(inputs) {
        let display = entry.path.display().to_string();
        if entry.is_dir {
            out.push("--tmpfs".to_string());
            out.push(display);
        } else {
            out.push("--ro-bind".to_string());
            out.push("/dev/null".to_string());
            out.push(display);
        }
    }
    out.push("--chdir".to_string());
    out.push(absolutize(&inputs.session_cwd).display().to_string());
    out.push("--".to_string());
    out.push(binary.display().to_string());
    out.extend(args.iter().cloned());
    Ok(out)
}

/// Write the profile to a uniquely-named file under `dir`, returning its path.
pub fn write_profile_file(dir: &Path, profile: &str) -> std::io::Result<PathBuf> {
    std::fs::create_dir_all(dir)?;
    let path = dir.join(format!("kranz-sandbox-{}.sb", uuid::Uuid::new_v4()));
    std::fs::write(&path, profile)?;
    Ok(path)
}

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

    #[cfg(target_os = "macos")]
    use std::sync::Mutex;

    /// `extra_write: ["~/cache"]` must resolve against the platform home.
    /// Regression: this read `HOME` only, which a natively launched
    /// `kranz.exe` does not have (Git Bash injects one; cmd/PowerShell/
    /// Explorer do not), so the entry stayed the literal `~/cache` and the
    /// sandbox grant silently targeted a directory named `~`.
    #[test]
    fn expand_tilde_uses_the_platform_home_variable() {
        assert_eq!(
            expand_tilde("relative/path"),
            PathBuf::from("relative/path")
        );
        assert_eq!(expand_tilde("~notatilde"), PathBuf::from("~notatilde"));

        let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
            .expect("the platform home variable is always set on a real host");
        let expanded = expand_tilde("~/cache");
        assert_eq!(expanded, PathBuf::from(&home).join("cache"));
        assert!(
            expanded.is_absolute(),
            "an expanded home path must be absolute: {expanded:?}"
        );

        #[cfg(windows)]
        assert_eq!(expand_tilde(r"~\cache"), PathBuf::from(&home).join("cache"));
    }

    #[cfg(target_os = "macos")]
    static SANDBOX_EXEC_TEST_LOCK: Mutex<()> = Mutex::new(());

    #[cfg(target_os = "macos")]
    fn sandbox_exec_can_apply() -> bool {
        let found = std::process::Command::new("which")
            .arg("sandbox-exec")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);
        if !found {
            crate::test_capability::skip(
                crate::test_capability::capability::SANDBOX_EXEC,
                "sandbox-exec not found on this host",
            );
            return false;
        }

        let smoke = std::process::Command::new("sandbox-exec")
            .arg("-p")
            .arg("(version 1)\n(allow default)\n")
            .arg("/usr/bin/true")
            .output();
        match smoke {
            Ok(output) if output.status.success() => true,
            Ok(output) => {
                eprintln!(
                    "sandbox-exec cannot apply a smoke profile on this host; skipping: {}",
                    String::from_utf8_lossy(&output.stderr)
                );
                false
            }
            Err(e) => {
                eprintln!("sandbox-exec smoke probe failed; skipping: {e}");
                false
            }
        }
    }

    #[cfg(target_os = "linux")]
    fn bwrap_can_apply() -> bool {
        if !command_available("bwrap") {
            crate::test_capability::skip(
                crate::test_capability::capability::BWRAP,
                "bwrap not found on this host",
            );
            return false;
        }

        let smoke = std::process::Command::new("bwrap")
            .args([
                "--die-with-parent",
                "--ro-bind",
                "/",
                "/",
                "--dev",
                "/dev",
                "--proc",
                "/proc",
                "--",
                "/bin/true",
            ])
            .output();
        match smoke {
            Ok(output) if output.status.success() => true,
            Ok(output) => {
                eprintln!(
                    "bwrap cannot apply a smoke sandbox on this host; skipping: {}",
                    String::from_utf8_lossy(&output.stderr)
                );
                false
            }
            Err(e) => {
                eprintln!("bwrap smoke probe failed; skipping: {e}");
                false
            }
        }
    }

    fn inputs(
        session_cwd: &Path,
        mission_dir: &Path,
        tmpdir: &Path,
        extra: Vec<PathBuf>,
    ) -> SandboxInputs {
        SandboxInputs {
            enforce: crate::types::SandboxEnforce::Fs,
            session_cwd: session_cwd.to_path_buf(),
            mission_dir: mission_dir.to_path_buf(),
            tmpdir: tmpdir.to_path_buf(),
            extra_write: extra,
            egress: Vec::new(),
            validator_read_deny_roots: Vec::new(),
        }
    }

    #[test]
    fn sandbox_profile_contains_required_clauses() {
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let extra = tempfile::tempdir().unwrap();

        let profile = generate_profile(&inputs(
            session.path(),
            mission.path(),
            tmp.path(),
            vec![extra.path().to_path_buf()],
        ));

        assert!(profile.contains("(version 1)"));
        assert!(profile.contains("(deny default)"));
        assert!(profile.contains("(allow file-read*)"));
        assert!(profile.contains("(allow file-write* (literal \"/dev/null\"))"));
        // `fs` must allow network so the sandboxed agent can reach its API.
        assert!(profile.contains("(allow network*)"));
        assert!(!profile.contains("(deny network*)"));

        let session_abs = absolutize(session.path());
        let tmp_abs = absolutize(tmp.path());
        let extra_abs = absolutize(extra.path());

        // The writable set: session cwd, the session-private scratch, and
        // each extraWrite entry.
        for p in [&session_abs, &tmp_abs, &extra_abs] {
            let expected = format!("(subpath \"{}\")", escape_sbpl_literal(p));
            assert!(
                profile.contains(&expected),
                "profile missing subpath rule for {:?}:\n{}",
                p,
                profile
            );
        }

        // The mission dir is NOT writable (its engine-owned metadata carries
        // explicit write denies instead — see
        // sandbox_profile_denies_mission_metadata_writes).
        let mission_abs = absolutize(mission.path());
        let mission_rule = format!("(subpath \"{}\")", escape_sbpl_literal(&mission_abs));
        assert!(
            !profile.contains(&mission_rule),
            "profile must not allow writes to the whole mission dir:\n{profile}"
        );
    }

    #[test]
    fn sandbox_profile_denies_authority_material_reads() {
        let _env = crate::agent_env::EnvTestGuard::engage(&[]);
        let repo = tempfile::tempdir().unwrap();
        let mission = repo.path().join(".kranz").join("missions").join("m-x");
        std::fs::create_dir_all(&mission).unwrap();
        let tmp = tempfile::tempdir().unwrap();

        let profile = generate_profile(&inputs(repo.path(), &mission, tmp.path(), vec![]));

        // Broad reads stay, with the authority material carved out by explicit
        // denies (SBPL denies take precedence over the allow).
        assert!(profile.contains("(allow file-read*)"));
        assert!(profile.contains("(deny file-read*"));
        let kranz_dir = repo.path().join(".kranz");
        for name in [
            "serve.token",
            "serve.read.token",
            "config.json",
            // The plaintext clean-room lint vocabulary (14th-pass review).
            "domain-terms.local",
        ] {
            for base in [kranz_dir.clone(), absolutize(&kranz_dir)] {
                let expected = format!("(literal \"{}\")", escape_sbpl_literal(&base.join(name)));
                assert!(
                    profile.contains(&expected),
                    "profile missing read deny for {}:\n{profile}",
                    base.join(name).display()
                );
            }
        }
        // The cargo registry token file is denied too (CARGO_HOME crosses
        // into child envs for cache locality; its credentials must not
        // ride along).
        assert!(
            profile.contains("credentials.toml"),
            "profile missing read deny for cargo credentials:\n{profile}"
        );
        if let Some(global) = crate::paths::global_config() {
            let global_dir = global.parent().unwrap();
            for operation in ["(deny file-read*", "(deny file-write*"] {
                for protected in [&global, global_dir] {
                    assert!(
                        profile.split(operation).skip(1).any(|block| {
                            block
                                .split("\n)\n")
                                .next()
                                .unwrap()
                                .contains(&escape_sbpl_literal(protected))
                        }),
                        "missing {operation} rule for {}",
                        protected.display()
                    );
                }
            }
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn sandbox_checkout_denies_authority_writes_and_future_sibling_inboxes() {
        use std::process::Command;
        let root = tempfile::tempdir().unwrap();
        let root = root.path().canonicalize().unwrap();
        let mission = root.join(".kranz/missions/m-current");
        std::fs::create_dir_all(&mission).unwrap();
        let config = root.join(".kranz/config.json");
        let config_target = root.join("operator-config.json");
        std::fs::write(&config_target, "original").unwrap();
        std::os::unix::fs::symlink(&config_target, &config).unwrap();
        let scratch = root.join("scratch");
        std::fs::create_dir(&scratch).unwrap();
        let profile = generate_profile(&inputs(&root, &mission, &scratch, vec![]));
        // Create a sibling after generating the profile to cover future
        // missions rather than relying on a spawn-time directory listing.
        let sibling = root.join(".kranz/missions/m-later/control");
        std::fs::create_dir_all(&sibling).unwrap();
        let run = |script: &str, path: &Path| {
            Command::new("sandbox-exec")
                .args(["-p", &profile, "/bin/sh", "-c", script, "audit"])
                .arg(path)
                .output()
                .unwrap()
        };
        let probe = run("exit 0", &root);
        if !probe.status.success()
            && String::from_utf8_lossy(&probe.stderr).contains("sandbox_apply")
        {
            eprintln!("SKIP-UNDER-WRAP: nested sandbox unavailable");
            return;
        }
        assert!(probe.status.success(), "{probe:?}");
        for protected in [
            config.clone(),
            config_target.clone(),
            sibling.join("forged.json"),
            sibling.parent().unwrap().join("events.jsonl"),
        ] {
            assert!(
                !run("printf forged > \"$1\"", &protected).status.success(),
                "wrote {}",
                protected.display()
            );
        }
        assert_eq!(std::fs::read_to_string(config).unwrap(), "original");
        assert!(
            !run("cat \"$1\"", &config_target).status.success(),
            "the symlink's target must carry the same authority read denial"
        );
        assert!(!sibling.join("forged.json").exists());
        assert!(
            !run(
                "ln \"$1/.kranz/config.json\" \"$1/authority-hardlink\"",
                &root
            )
            .status
            .success(),
            "a hard link must not move authority outside the read deny"
        );
        assert!(
            !run("mv \"$1/.kranz\" \"$1/moved-authority\"", &root)
                .status
                .success(),
            "renaming the authority parent must not move it outside its deny rules"
        );
        assert!(run("printf feature > \"$1\"", &root.join("feature.txt"))
            .status
            .success());
        assert!(run("printf scratch > \"$1\"", &scratch.join("work.txt"))
            .status
            .success());
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn sandbox_global_authority_is_denied_when_created_after_profile() {
        if crate::agent_env::isolated_global_home_test(
            "sandbox::tests::sandbox_global_authority_is_denied_when_created_after_profile",
        ) {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let home = root.join("operator");
        let alias = root.join("operator-alias");
        std::fs::create_dir(&home).unwrap();
        std::os::unix::fs::symlink(&home, &alias).unwrap();
        let session = root.join("session");
        let mission = session.join(".kranz/missions/m-test");
        let scratch = root.join("scratch");
        std::fs::create_dir_all(&mission).unwrap();
        std::fs::create_dir(&scratch).unwrap();
        let profile = {
            let _env = crate::agent_env::EnvTestGuard::engage(&[("HOME", alias.to_str().unwrap())]);
            generate_profile(&inputs(&session, &mission, &scratch, vec![home.clone()]))
        };
        let authority = home.join(".kranz/serve/later.token");
        std::fs::create_dir_all(authority.parent().unwrap()).unwrap();
        std::fs::write(&authority, "fake-authority").unwrap();
        let output = std::process::Command::new("sandbox-exec")
            .args(["-p", &profile, "/bin/sh", "-c",
                "printf witness > \"$1/witness\" || exit 2; if cat \"$2\"; then exit 3; fi; if printf forged > \"$2\"; then exit 4; fi",
                "test"])
            .arg(&session).arg(&authority).output().unwrap();
        if String::from_utf8_lossy(&output.stderr).contains("sandbox_apply") {
            eprintln!("SKIP-UNDER-WRAP: nested sandbox unavailable");
            return;
        }
        assert!(output.status.success(), "{output:?}");
        assert!(session.join("witness").exists());
        assert_eq!(
            std::fs::read_to_string(authority).unwrap(),
            "fake-authority"
        );
    }

    /// Composition audit (ticket `config-fail-open-audit`): the effective
    /// egress list EXTENDS the compiled-in Anthropic floor — a mission's
    /// configured `egress[]` (and, downstream, its operator-approved egress
    /// grants) can only add destinations, never drop or narrow the defaults.
    /// A replace-shaped regression here strands the sandboxed session's own
    /// API access, or worse, goes unnoticed while the operator believes the
    /// floor is still composed in.
    #[test]
    fn composition_audit_effective_egress_extends_never_replaces_the_default_floor() {
        let configured = vec![
            " crates.io:443 ".to_string(),       // trimmed on the way in
            "api.anthropic.com:443".to_string(), // a duplicate of the floor
            "registry.npmjs.org:443".to_string(),
        ];
        let out = effective_egress(&configured);
        assert_eq!(
            out,
            vec![
                "api.anthropic.com:443".to_string(),
                "*.anthropic.com:443".to_string(),
                "crates.io:443".to_string(),
                "registry.npmjs.org:443".to_string(),
            ]
        );
        // An empty configured list still yields the full default floor.
        assert_eq!(effective_egress(&[]).len(), DEFAULT_EGRESS.len());
    }

    /// Composition audit: `extraWrite` EXTENDS the writable floor (session
    /// cwd + session-private scratch) — the floor itself is not configurable
    /// away, so no config shape can un-write the session's own worktree or
    /// its private scratch.
    #[test]
    fn composition_audit_extra_write_extends_never_replaces_the_writable_floor() {
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let extra = tempfile::tempdir().unwrap();
        let inputs = inputs(
            session.path(),
            mission.path(),
            tmp.path(),
            vec![extra.path().to_path_buf()],
        );
        let writable = write_allowlist(&inputs);
        for floor in [absolutize(session.path()), absolutize(tmp.path())] {
            assert!(
                writable.contains(&floor),
                "the writable floor {floor:?} must survive any extraWrite list"
            );
        }
        assert!(writable.contains(&absolutize(extra.path())));
    }

    /// Composition audit: the explicit deny sets (mission metadata writes,
    /// authority reads) survive an `extraWrite` broad enough to COVER them.
    /// SBPL denies take precedence over every allow regardless of clause
    /// order, so the deny clauses must still be emitted when the allow side
    /// is at its widest — this is the deny-wins pin for the sandbox surface.
    #[test]
    fn composition_audit_explicit_denies_survive_a_covering_extra_write_allow() {
        let repo = tempfile::tempdir().unwrap();
        let mission = repo.path().join(".kranz").join("missions").join("m-x");
        std::fs::create_dir_all(&mission).unwrap();
        let tmp = tempfile::tempdir().unwrap();
        // extraWrite = the repo root: every mission file now sits under an
        // allowed subpath — the widest realistic allow shape.
        let profile = generate_profile(&inputs(
            repo.path(),
            &mission,
            tmp.path(),
            vec![repo.path().to_path_buf()],
        ));
        // The covering allow IS emitted...
        assert!(
            profile.contains(&format!(
                "(subpath \"{}\")",
                escape_sbpl_literal(&absolutize(repo.path()))
            )),
            "the covering extraWrite allow must be present:\n{profile}"
        );
        // ...and the metadata write denies still are too: the audit log,
        // state snapshot, and control inbox stay unwritable through the
        // allow because SBPL denies win over it.
        assert!(profile.contains("(deny file-write*"));
        for name in ["events.jsonl", "state.json"] {
            assert!(
                profile.contains(&escape_sbpl_literal(&mission.join(name))),
                "the write deny for {name} must survive the covering allow:\n{profile}"
            );
        }
        // Authority reads (serve.token) stay denied under the broad read
        // allow for the same reason.
        assert!(
            profile.contains(&escape_sbpl_literal(
                &repo.path().join(".kranz").join("serve.token")
            )),
            "the read deny for serve.token must survive the covering allow:\n{profile}"
        );
    }

    #[test]
    fn bubblewrap_args_mask_authority_material_with_dev_null() {
        let repo = tempfile::tempdir().unwrap();
        let mission = repo.path().join(".kranz").join("missions").join("m-x");
        std::fs::create_dir_all(&mission).unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let serve_token = repo.path().join(".kranz").join("serve.token");
        std::fs::write(&serve_token, "secret").unwrap();

        let args = bubblewrap_args(
            &inputs(repo.path(), &mission, tmp.path(), vec![]),
            Path::new("/usr/bin/claude"),
            &[],
        )
        .unwrap();
        let joined = args.join(" ");

        let expected = format!(
            "--tmpfs {}",
            absolutize(serve_token.parent().unwrap()).display()
        );
        assert!(
            joined.contains(&expected),
            "missing private authority directory: {args:?}"
        );
        // Neither existing nor future credentials get a bind back into it.
        assert!(!joined.contains("serve.token"));
        assert!(
            !joined.contains("serve.read.token"),
            "future authority files must not get a host bind: {args:?}"
        );
    }

    #[test]
    fn sandbox_profile_denies_mission_metadata_writes() {
        let repo = tempfile::tempdir().unwrap();
        let mission = repo.path().join(".kranz").join("missions").join("m-x");
        std::fs::create_dir_all(&mission).unwrap();
        let scratch = tempfile::tempdir().unwrap();

        // Checkout-mode shape: the session cwd is the repo root, an ANCESTOR
        // of the mission dir — without explicit write denies the audit log,
        // state snapshot, control inbox, and transcripts would be writable
        // through the session-cwd subpath allow.
        let profile = generate_profile(&inputs(repo.path(), &mission, scratch.path(), vec![]));

        assert!(
            profile.contains("(deny file-write*"),
            "missing write deny block:\n{profile}"
        );
        for name in MISSION_METADATA_FILES {
            for base in [mission.clone(), absolutize(&mission)] {
                let expected = format!("(literal \"{}\")", escape_sbpl_literal(&base.join(name)));
                assert!(
                    profile.contains(&expected),
                    "profile missing write deny for {}:\n{profile}",
                    base.join(name).display()
                );
            }
        }
        for base in [mission.clone(), absolutize(&mission)] {
            let control = format!(
                "(subpath \"{}\")",
                escape_sbpl_literal(&base.join("control"))
            );
            assert!(
                profile.contains(&control),
                "profile missing control/ write deny:\n{profile}"
            );
            let runs = format!(
                "(regex #\"^{}/[^/]*\\.jsonl$\")",
                escape_sbpl_regex(&base.join("runs"))
            );
            assert!(
                profile.contains(&runs),
                "profile missing transcript write deny:\n{profile}"
            );
        }
        // The mission dir root itself is not in the allow set.
        let mission_rule = format!(
            "(subpath \"{}\")",
            escape_sbpl_literal(&absolutize(&mission))
        );
        assert!(
            !profile.contains(&mission_rule),
            "the whole mission dir must not be writable:\n{profile}"
        );
    }

    /// 13th-pass review (P1): above the copy ceiling the isolated contract
    /// Cargo home LINKS the operator's registry/git caches in — the profile
    /// must deny writes to those REAL cache dirs (raw AND canonical forms)
    /// so the linked target stays read-only under every allow. The deny is
    /// PRECISE: the two cache dirs, never the whole cargo home (rustup/cargo
    /// binaries keep their ordinary posture).
    #[test]
    fn cache_write_deny_profile_denies_real_cache_dirs_precisely() {
        let cargo = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(cargo.path().join("registry")).unwrap();
        std::fs::create_dir_all(cargo.path().join("git")).unwrap();
        let _guard = crate::agent_env::EnvTestGuard::engage(&[(
            "CARGO_HOME",
            cargo.path().to_str().expect("utf-8 temp path"),
        )]);
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();
        let scratch = tempfile::tempdir().unwrap();

        let profile = generate_profile(&inputs(
            session.path(),
            mission.path(),
            scratch.path(),
            vec![],
        ));
        for base in [cargo.path().to_path_buf(), absolutize(cargo.path())] {
            for name in ["registry", "git"] {
                let expected = format!("(subpath \"{}\")", escape_sbpl_literal(&base.join(name)));
                assert!(
                    profile.contains(&expected),
                    "profile missing cache write deny for {}:\n{profile}",
                    base.join(name).display()
                );
            }
        }
        // Precision: the cargo home ITSELF is not in the deny set — the
        // closing `"` after the home path makes this an exact-line check
        // (the registry/git lines carry a longer path and cannot match).
        for base in [cargo.path().to_path_buf(), absolutize(cargo.path())] {
            let whole_home = format!("(subpath \"{}\")", escape_sbpl_literal(&base));
            assert!(
                !profile.contains(&whole_home),
                "the deny must be precise to the cache dirs, not the whole cargo home:\n{profile}"
            );
        }
    }

    /// The bwrap analogue: the real cache dirs present at spawn get explicit
    /// ro-binds stacked AFTER the rw binds (later binds win — an rw
    /// extraWrite covering an ancestor must not re-widen them), and absent
    /// dirs are skipped (bwrap requires the destination to exist).
    #[test]
    fn cache_write_deny_bwrap_stacks_ro_binds_over_real_cache() {
        let cargo = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(cargo.path().join("registry")).unwrap();
        // git/ deliberately absent → not bound (the is_dir filter).
        let _guard = crate::agent_env::EnvTestGuard::engage(&[(
            "CARGO_HOME",
            cargo.path().to_str().expect("utf-8 temp path"),
        )]);
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();
        let scratch = tempfile::tempdir().unwrap();

        let args = bubblewrap_args(
            &inputs(session.path(), mission.path(), scratch.path(), vec![]),
            Path::new("/usr/bin/claude"),
            &[],
        )
        .unwrap();
        let joined = args.join(" ");

        let registry = absolutize(&cargo.path().join("registry"));
        let expected = format!("--ro-bind {0} {0}", registry.display());
        assert!(
            joined.contains(&expected),
            "missing stacked ro-bind for the real registry cache: {args:?}"
        );
        let git_cache = cargo.path().join("git");
        assert!(
            !joined.contains(&git_cache.display().to_string()),
            "an absent cache dir must not be bound: {args:?}"
        );
        // Ordering is load-bearing: the cache ro-bind must land AFTER every
        // rw `--bind`, or a wide writable root would re-cover it.
        let last_rw = args
            .iter()
            .rposition(|arg| arg == "--bind")
            .expect("the writable roots are rw-bound");
        let registry_arg = registry.display().to_string();
        let cache_pos = args
            .windows(3)
            .position(|w| w[0] == "--ro-bind" && w[1] == registry_arg && w[2] == registry_arg)
            .expect("the cache ro-bind pair exists");
        assert!(
            cache_pos > last_rw,
            "the cache ro-bind must stack after the rw binds: {args:?}"
        );
    }

    #[test]
    fn sandbox_profile_keeps_sibling_temp_neighbors_unwritable() {
        // The worktree-mode layout the finding named: integration/feature
        // worktrees for ALL missions sit side by side under the shared temp
        // root. The session's own worktree + private scratch must be
        // writable; the sibling mission's worktree, the sibling's scratch,
        // and the shared temp root itself must not.
        let root = tempfile::tempdir().unwrap();
        let session = root.path().join("kranz-wt-aaa-m1-f-1-1");
        let scratch = root.path().join("kranz-worker-home-sess-1");
        let sibling = root.path().join("kranz-wt-bbb-m2-_integration");
        let sibling_scratch = root.path().join("kranz-worker-home-sess-2");
        for d in [&session, &scratch, &sibling, &sibling_scratch] {
            std::fs::create_dir_all(d).unwrap();
        }
        let mission = tempfile::tempdir().unwrap();

        let profile = generate_profile(&inputs(&session, mission.path(), &scratch, vec![]));

        for allowed in [&session, &scratch] {
            let expected = format!(
                "(subpath \"{}\")",
                escape_sbpl_literal(&absolutize(allowed))
            );
            assert!(
                profile.contains(&expected),
                "profile missing allow for {}:\n{profile}",
                allowed.display()
            );
        }
        for denied in [&sibling, &sibling_scratch, &root.path().to_path_buf()] {
            let rule = format!("(subpath \"{}\")", escape_sbpl_literal(&absolutize(denied)));
            assert!(
                !profile.contains(&rule),
                "{} must not be writable:\n{profile}",
                denied.display()
            );
        }
    }

    #[test]
    fn bubblewrap_args_mask_mission_metadata() {
        let repo = tempfile::tempdir().unwrap();
        let mission = repo.path().join(".kranz").join("missions").join("m-x");
        let runs = mission.join("runs");
        std::fs::create_dir_all(&runs).unwrap();
        let scratch = tempfile::tempdir().unwrap();
        // Engine-owned metadata present at spawn.
        let events = mission.join("events.jsonl");
        let state = mission.join("state.json");
        let transcript = runs.join("run-1.jsonl");
        let denials = runs.join("egress-denials.jsonl");
        for f in [&events, &state, &transcript, &denials] {
            std::fs::write(f, "engine").unwrap();
        }
        let control = mission.join("control");
        std::fs::create_dir_all(&control).unwrap();
        // A runs/ SUBDIRECTORY of session scratch: its jsonl files are not
        // transcripts and must NOT be masked.
        let contract_home = runs.join("contract-home");
        std::fs::create_dir_all(&contract_home).unwrap();
        let scratch_jsonl = contract_home.join("notes.jsonl");
        std::fs::write(&scratch_jsonl, "session").unwrap();

        let args = bubblewrap_args(
            &inputs(repo.path(), &mission, scratch.path(), vec![]),
            Path::new("/usr/bin/claude"),
            &[],
        )
        .unwrap();
        let joined = args.join(" ");

        for path in [&events, &state, &mission.join("runs")] {
            let path = absolutize(path).display().to_string();
            assert!(
                joined.contains(&format!("--ro-bind-try {path} {path}")),
                "metadata must remain read-only: {args:?}"
            );
        }
        let mission_abs = absolutize(&mission).display().to_string();
        assert!(args
            .windows(2)
            .any(|pair| pair[0] == "--tmpfs" && pair[1] == mission_abs));
        assert!(
            !args.windows(3).any(|part| {
                matches!(part[0].as_str(), "--ro-bind" | "--ro-bind-try")
                    && part[1] == absolutize(&control).display().to_string()
                    && part[1] == part[2]
            }),
            "the control inbox must not be rebound into the private mission directory"
        );
        assert!(
            !mission.join("state.json.tmp").exists(),
            "argv construction must not create metadata"
        );
        // Absent metadata files are not masked (bwrap needs the destination
        // to exist).
        assert!(
            !joined.contains("estimate.json"),
            "absent metadata files must not be masked: {args:?}"
        );
        // No rw bind of the mission dir, and runs/-subdir scratch files stay
        // unmasked.
        let mission_abs = absolutize(&mission);
        assert!(
            !joined.contains(&format!("--bind {0} {0}", mission_abs.display())),
            "mission dir must not be rw-bound: {args:?}"
        );
        assert!(
            !joined.contains(&scratch_jsonl.display().to_string()),
            "runs/ subdir scratch files must not be masked: {args:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn bubblewrap_mask_prep_rejects_preexisting_state_tmp_symlink() {
        use std::os::unix::fs::symlink;
        let repo = tempfile::tempdir().unwrap();
        let mission = repo.path().join(".kranz").join("missions").join("m-x");
        std::fs::create_dir_all(mission.join("runs")).unwrap();
        let target_dir = tempfile::tempdir().unwrap();
        let target = target_dir.path().join("outside");
        std::fs::write(&target, "unchanged").unwrap();
        symlink(&target, mission.join("state.json.tmp")).unwrap();
        let scratch = tempfile::tempdir().unwrap();

        let error = bubblewrap_args(
            &inputs(repo.path(), &mission, scratch.path(), vec![]),
            Path::new("/usr/bin/claude"),
            &[],
        )
        .expect_err("a symlink cannot become a bwrap mask mount point");

        assert!(error.to_string().contains("not a regular file"), "{error}");
        assert_eq!(std::fs::read_to_string(target).unwrap(), "unchanged");
        assert!(
            std::fs::symlink_metadata(mission.join("state.json.tmp"))
                .unwrap()
                .file_type()
                .is_symlink(),
            "mask preparation must not replace or follow the hostile leaf"
        );
    }

    #[test]
    fn sandbox_profile_excludes_paths_outside_allowlist() {
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let outsider = tempfile::tempdir().unwrap();

        let profile = generate_profile(&inputs(session.path(), mission.path(), tmp.path(), vec![]));

        let outsider_abs = absolutize(outsider.path());
        let forbidden = format!("(subpath \"{}\")", escape_sbpl_literal(&outsider_abs));
        assert!(
            !profile.contains(&forbidden),
            "profile unexpectedly allows write to path outside the allowlist"
        );
    }

    #[test]
    fn sandbox_profile_fs_net_restricts_egress_to_loopback() {
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let mut inputs = inputs(session.path(), mission.path(), tmp.path(), vec![]);
        inputs.enforce = crate::types::SandboxEnforce::FsNet;
        inputs.egress = vec!["crates.io:443".into(), "api.anthropic.com:443".into()];

        let profile = generate_profile(&inputs);

        // Seatbelt rejects hostname egress rules, so the profile cuts outbound
        // TCP to loopback only; the per-host allowlist (including the
        // configured entries above) is the egress proxy's job, not the SBPL's.
        assert!(!profile.contains("(allow network*)"));
        assert!(profile.contains("(allow network-outbound (remote tcp \"localhost:*\"))"));
        assert!(
            !profile.contains("crates.io") && !profile.contains("anthropic.com"),
            "no per-host egress rules in the profile:\n{profile}"
        );
    }

    #[test]
    fn bubblewrap_args_bind_write_roots_and_unshare_network_for_fs_net() {
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let extra = tempfile::tempdir().unwrap();
        let mut inputs = inputs(
            session.path(),
            mission.path(),
            tmp.path(),
            vec![extra.path().to_path_buf()],
        );
        inputs.enforce = crate::types::SandboxEnforce::FsNet;

        let args =
            bubblewrap_args(&inputs, Path::new("/usr/bin/claude"), &["--print".into()]).unwrap();
        let joined = args.join(" ");

        assert!(args.contains(&"--unshare-net".to_string()));
        for path in [
            absolutize(session.path()),
            absolutize(tmp.path()),
            absolutize(extra.path()),
        ] {
            assert!(
                joined.contains(&format!("--bind {0} {0}", path.display())),
                "bubblewrap args missing bind for {}: {args:?}",
                path.display()
            );
        }
        // The mission dir is bound read-only via the whole-fs ro-bind only —
        // never re-bound writable.
        let mission_abs = absolutize(mission.path());
        assert!(
            !joined.contains(&format!("--bind {0} {0}", mission_abs.display())),
            "bubblewrap args must not rw-bind the mission dir: {args:?}"
        );
        assert!(joined.contains("--ro-bind / /"));
        assert!(joined.ends_with("/usr/bin/claude --print"));
    }

    /// H8 (2026-09-01 adversarial audit): the argv unshared ONLY the network
    /// namespace, and only under `fs+net`. Host `/proc` was therefore the
    /// engine's own `/proc`, so a contained agent could read
    /// `/proc/<engine>/environ` (the very set `agent_env` exists to withhold)
    /// on a `ptrace_scope = 0` host, keep the controlling terminal, and
    /// signal the engine. Every namespace flag is unconditional; only
    /// `--unshare-net` stays tier-gated, because it is an egress decision.
    #[test]
    fn bubblewrap_args_unshare_every_namespace_on_both_tiers() {
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();
        let tmp = tempfile::tempdir().unwrap();

        for enforce in [
            crate::types::SandboxEnforce::Fs,
            crate::types::SandboxEnforce::FsNet,
        ] {
            let mut inputs = inputs(session.path(), mission.path(), tmp.path(), vec![]);
            inputs.enforce = enforce;
            let args = bubblewrap_args(&inputs, Path::new("/usr/bin/claude"), &[]).unwrap();

            for flag in [
                "--unshare-pid",
                "--unshare-ipc",
                "--unshare-uts",
                "--unshare-cgroup-try",
                "--new-session",
                "--die-with-parent",
            ] {
                assert!(
                    args.contains(&flag.to_string()),
                    "{enforce:?} argv missing {flag}: {args:?}"
                );
            }
            // M-8 (follow-up review): the non-try form makes bwrap EXIT
            // non-zero where cgroup namespaces are unavailable (kernels
            // before 4.6, nested containers, hardened kernels), and every
            // resolver here fails closed — so the whole session dies rather
            // than degrading by one namespace.
            assert!(
                !args.contains(&"--unshare-cgroup".to_string()),
                "the non-try cgroup unshare must never be emitted: {args:?}"
            );
            assert_eq!(
                args.contains(&"--unshare-net".to_string()),
                enforce == crate::types::SandboxEnforce::FsNet,
                "--unshare-net is the one tier-gated namespace: {args:?}"
            );
        }
    }

    /// The canonical `<repo>/.kranz/missions/<id>` fixture the authority
    /// write denies need: a repo root with the mission's own dir, a SIBLING
    /// mission, the repo-level engine stores, and a `.git`.
    fn authority_write_fixture() -> (tempfile::TempDir, PathBuf) {
        let repo = tempfile::tempdir().unwrap();
        let kranz = repo.path().join(".kranz");
        let mission = kranz.join("missions").join("m-x");
        std::fs::create_dir_all(mission.join("runs").join("scratch")).unwrap();
        std::fs::create_dir_all(kranz.join("missions").join("m-other")).unwrap();
        for name in ["queue", "tickets", "lessons", "hook-status"] {
            std::fs::create_dir_all(kranz.join(name)).unwrap();
        }
        for name in ["config.json", "serve.token", "serve.read.token"] {
            std::fs::write(kranz.join(name), "secret").unwrap();
        }
        std::fs::create_dir_all(repo.path().join(".git").join("hooks")).unwrap();
        std::fs::create_dir_all(repo.path().join(".git").join("info")).unwrap();
        std::fs::write(repo.path().join(".git").join("config"), "[core]\n").unwrap();
        (repo, mission)
    }

    /// H2 + H11 (2026-09-01 adversarial audit): `.kranz/config.json` was
    /// read-denied but WRITE-allowed, and every metadata deny was derived
    /// from the session's OWN mission dir. Under checkout mode `session_cwd`
    /// is the repo root, so a contained worker could overwrite the trust
    /// root it could not read, and forge approvals into a sibling mission.
    #[test]
    fn sandbox_profile_denies_authority_material_writes() {
        let (repo, mission) = authority_write_fixture();
        let tmp = tempfile::tempdir().unwrap();
        let kranz = repo.path().join(".kranz");

        // Checkout mode: session_cwd IS the repo root, the hostile shape.
        let profile = generate_profile(&inputs(repo.path(), &mission, tmp.path(), vec![]));

        for name in ["config.json", "serve.token", "serve.read.token"] {
            let expected = format!(
                "(literal \"{}\")",
                escape_sbpl_literal(&absolutize(&kranz.join(name)))
            );
            assert!(
                profile.contains(&expected),
                "profile missing write deny for .kranz/{name}:\n{profile}"
            );
        }
        for name in ["queue", "tickets", "lessons", "hook-status"] {
            let expected = format!(
                "(subpath \"{}\")",
                escape_sbpl_literal(&absolutize(&kranz.join(name)))
            );
            assert!(
                profile.contains(&expected),
                "profile missing write deny for .kranz/{name}/:\n{profile}"
            );
        }
        // The SIBLING mission is denied; the session's OWN mission dir is
        // not denied wholesale (mission_write_denies keeps the narrow set,
        // and runs/<scratch> must stay writable).
        let other = absolutize(&kranz.join("missions").join("m-other"));
        assert!(
            profile.contains(&format!("(subpath \"{}\")", escape_sbpl_literal(&other))),
            "profile missing write deny for the sibling mission dir:\n{profile}"
        );
        let own = absolutize(&mission);
        assert!(
            !profile.contains(&format!("(subpath \"{}\")\n", escape_sbpl_literal(&own))),
            "the session's own mission dir must not be denied wholesale:\n{profile}"
        );
        // The sealing regexes: no NEW store under `.kranz`, no NEW sibling
        // mission dir, after the profile was built.
        for root in [absolutize(&kranz), absolutize(&kranz.join("missions"))] {
            let expected = format!("(regex #\"^{}/[^/]*$\")", escape_sbpl_regex(&root));
            assert!(
                profile.contains(&expected),
                "profile missing the sealing regex for {}:\n{profile}",
                root.display()
            );
        }
    }

    /// The global kranz key dir (`~/.kranz/keys`) is denied for BOTH reads
    /// and writes on every tier (2026-09-01 adversarial audit, C1/H6): the
    /// consent substrate's MAC key has to live outside a sandboxed session's
    /// readable set, or the MAC proves nothing against the agent it excludes;
    /// and a session that could replace the key could re-sign anything.
    #[test]
    fn global_key_dir_is_read_and_write_denied() {
        // The global dir is resolved once per process (`paths::global_kranz_dir`),
        // so the test reads the resolved value instead of rebinding HOME: the
        // property under test is that the deny follows the SAME resolver the
        // key writer and the seal recorder use.
        let global = crate::paths::global_kranz_dir().expect("a global kranz dir resolves");
        let (repo, mission) = authority_write_fixture();
        let tmp = tempfile::tempdir().unwrap();
        let inputs = inputs(repo.path(), &mission, tmp.path(), vec![]);

        for store in ["keys", "seals"] {
            let dir = global.join(store);
            assert!(
                authority_read_deny_dirs(&inputs).contains(&dir),
                "the global {store} dir must be read-denied"
            );
            assert!(
                authority_write_denies(&inputs).dirs.contains(&dir),
                "the global {store} dir must be write-denied"
            );
            let profile = generate_profile(&inputs);
            let expected = format!("(subpath \"{}\")", escape_sbpl_literal(&dir));
            assert!(
                profile.matches(&expected).count() >= 2,
                "the {store} dir belongs in BOTH the read-deny and the write-deny block:\n{profile}"
            );
        }
    }

    /// A mission dir that is NOT in the canonical
    /// `<repo>/.kranz/missions/<id>` layout must yield no sweep at all — the
    /// derivation walks parents, and a bare temp-dir mission would otherwise
    /// seal the system temp root (or `/`) against every write.
    #[test]
    fn authority_write_denies_refuse_a_noncanonical_mission_layout() {
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let inputs = inputs(session.path(), mission.path(), tmp.path(), vec![]);

        assert!(
            sealed_kranz_dir_roots(&inputs).is_empty(),
            "a non-canonical mission dir must seal nothing"
        );
        let denies = authority_write_denies(&inputs);
        let temp_root = absolutize(&std::env::temp_dir());
        assert!(
            !denies.dirs.iter().any(|d| d == &temp_root),
            "the sweep must never reach the system temp root: {:?}",
            denies.dirs
        );
    }

    /// H3 support (2026-09-01 adversarial audit): the engine checkpoints with
    /// an UNHARDENED git handle in the tree the worker controls, so a planted
    /// `.git/hooks/pre-commit` or a `core.sshCommand` in `.git/config`
    /// executes on the host with the engine's full environment. The deny is
    /// narrow because the worker's own role is to commit.
    #[test]
    fn sandbox_profile_denies_git_config_and_hook_writes_but_not_the_index() {
        let (repo, mission) = authority_write_fixture();
        let tmp = tempfile::tempdir().unwrap();

        let profile = generate_profile(&inputs(repo.path(), &mission, tmp.path(), vec![]));

        let git = absolutize(&repo.path().join(".git"));
        for dir in ["hooks", "info"] {
            let expected = format!("(subpath \"{}\")", escape_sbpl_literal(&git.join(dir)));
            assert!(
                profile.contains(&expected),
                "profile missing write deny for .git/{dir}/:\n{profile}"
            );
        }
        for file in ["config", "config.worktree"] {
            let expected = format!("(literal \"{}\")", escape_sbpl_literal(&git.join(file)));
            assert!(
                profile.contains(&expected),
                "profile missing write deny for .git/{file}:\n{profile}"
            );
        }
        // The gitlink FILE form (worktree mode) is denied as a literal, which
        // in checkout mode denies a replace of the `.git` directory node.
        assert!(
            profile.contains(&format!("(literal \"{}\")", escape_sbpl_literal(&git))),
            "profile missing write deny for the .git node itself:\n{profile}"
        );
        // The commit path stays open: nothing denies the index or objects.
        for open in ["index", "objects", "refs"] {
            let denied = format!("(subpath \"{}\")", escape_sbpl_literal(&git.join(open)));
            assert!(
                !profile.contains(&denied),
                ".git/{open} must stay writable — the worker commits:\n{profile}"
            );
        }
    }

    /// M-9 (follow-up review): a submodule keeps its own `config` and
    /// `hooks/` under `.git/modules/<name>/`, which is the SAME host-execution
    /// surface `.git/config` and `.git/hooks/` are — and in checkout mode it
    /// sits inside the rw session bind. The subtree deny covers every
    /// submodule, present and future; git never needs to write it from
    /// inside the sandbox.
    #[test]
    fn git_metadata_write_denies_cover_the_submodule_config_and_hook_surface() {
        let (repo, mission) = authority_write_fixture();
        let tmp = tempfile::tempdir().unwrap();
        let inputs = inputs(repo.path(), &mission, tmp.path(), vec![]);

        let modules = absolutize(&repo.path().join(".git").join("modules"));
        assert!(
            git_metadata_write_denies(&inputs).dirs.contains(&modules),
            "the .git/modules subtree must be write-denied: {:?}",
            git_metadata_write_denies(&inputs).dirs
        );
        let profile = generate_profile(&inputs);
        assert!(
            profile.contains(&format!("(subpath \"{}\")", escape_sbpl_literal(&modules))),
            "profile missing write deny for .git/modules/:\n{profile}"
        );
    }

    /// The bwrap analogue of the two blocks above: each denied path is
    /// ro-bound over itself (readable, unwritable), and the `.git` DIRECTORY
    /// node is deliberately excluded — binding it whole would close the index
    /// the worker's own `git commit` writes.
    /// Later binds win in bwrap. A read-denied file is closed by its
    /// /dev/null mask; a self ro-bind of the same path emitted afterwards
    /// would put the real content back. Every masked path must therefore be
    /// absent from the self-bind set (Linux CI receipt, 2026-09-03).
    #[test]
    fn bubblewrap_args_never_self_bind_a_masked_authority_path() {
        let (repo, mission) = authority_write_fixture();
        let tmp = tempfile::tempdir().unwrap();
        let inputs = inputs(repo.path(), &mission, tmp.path(), vec![]);
        let args = bubblewrap_args(&inputs, Path::new("/bin/true"), &[]).unwrap();
        let masked: Vec<String> = authority_read_deny_paths(&inputs)
            .iter()
            .map(|path| absolutize(path).display().to_string())
            .collect();
        let kranz = absolutize(&repo.path().join(".kranz"))
            .display()
            .to_string();
        assert!(args
            .windows(2)
            .any(|pair| pair[0] == "--tmpfs" && pair[1] == kranz));
        let mut i = 0;
        while i + 2 < args.len() {
            if matches!(args[i].as_str(), "--ro-bind" | "--ro-bind-try")
                && args[i + 1] == args[i + 2]
            {
                assert!(
                    !masked.contains(&args[i + 2]),
                    "{} is masked and must not be re-bound over itself",
                    args[i + 2]
                );
            }
            i += 1;
        }
    }

    #[test]
    fn bubblewrap_args_ro_bind_authority_and_git_write_denies() {
        let (repo, mission) = authority_write_fixture();
        let tmp = tempfile::tempdir().unwrap();
        let kranz = repo.path().join(".kranz");

        let args = bubblewrap_args(
            &inputs(repo.path(), &mission, tmp.path(), vec![]),
            Path::new("/usr/bin/claude"),
            &[],
        )
        .unwrap();
        let joined = args.join(" ");

        for path in [
            kranz.join("queue"),
            kranz.join("tickets"),
            kranz.join("lessons"),
            kranz.join("missions").join("m-other"),
            repo.path().join(".git").join("hooks"),
            repo.path().join(".git").join("info"),
            repo.path().join(".git").join("config"),
        ] {
            let expected = format!("--ro-bind {0} {0}", lexical_absolute(&path).display());
            assert!(
                joined.contains(&expected),
                "bwrap argv missing the write-closing ro-bind for {}: {args:?}",
                path.display()
            );
        }
        let git = lexical_absolute(&repo.path().join(".git"));
        assert!(
            !joined.contains(&format!("--ro-bind {0} {0}", git.display())),
            "the .git DIRECTORY must never be ro-bound whole — the worker commits: {args:?}"
        );
    }

    /// H7 (2026-09-01 adversarial audit): the operator's own terminal must
    /// be denied read, write AND ioctl — the last is what closes TIOCSTI —
    /// even though the gate extras still ALLOW the pty device class the
    /// harness's `openpty` needs, and even though `/dev/ttys003` is matched
    /// by that class. Rendered from an explicit path list so the assertion
    /// holds on a test runner with no controlling terminal of its own.
    #[test]
    fn tty_deny_block_denies_ioctl_on_the_named_terminal_and_nothing_when_absent() {
        let block = tty_deny_block(&[
            PathBuf::from("/dev/ttys003"),
            PathBuf::from("/dev/ttys003"),
            PathBuf::from("/dev/ttys001"),
        ]);
        assert!(block.starts_with("(deny file-read* file-write* file-ioctl\n"));
        assert!(block.contains("(literal \"/dev/ttys003\")"), "{block}");
        assert!(block.contains("(literal \"/dev/ttys001\")"), "{block}");
        assert_eq!(
            block.matches("/dev/ttys003").count(),
            1,
            "duplicate fds must collapse to one literal:\n{block}"
        );
        assert!(
            tty_deny_block(&[]).is_empty(),
            "no controlling terminal means no deny block"
        );
    }

    #[test]
    fn sandbox_profile_write_profile_file_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let profile = "(version 1)\n(deny default)\n";
        let path = write_profile_file(dir.path(), profile).unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), profile);
        assert!(path.starts_with(dir.path()));
    }

    #[test]
    fn sandbox_platform_support_matrix() {
        use crate::types::SandboxEnforce;

        assert_eq!(
            platform_support(SandboxEnforce::Off, "macos"),
            SandboxDecision::Off
        );
        assert_eq!(
            platform_support(SandboxEnforce::Fs, "macos"),
            SandboxDecision::Enforce(SandboxBackend::Seatbelt)
        );
        assert_eq!(
            platform_support(SandboxEnforce::Fs, "linux"),
            SandboxDecision::Enforce(SandboxBackend::Bubblewrap)
        );
        assert_eq!(
            platform_support(SandboxEnforce::FsNet, "macos"),
            SandboxDecision::Enforce(SandboxBackend::Seatbelt)
        );
        assert_eq!(
            platform_support(SandboxEnforce::FsNet, "linux"),
            SandboxDecision::Enforce(SandboxBackend::Bubblewrap)
        );
        assert_eq!(
            platform_support(SandboxEnforce::Fs, "windows"),
            SandboxDecision::Enforce(SandboxBackend::AppContainer)
        );
        assert_eq!(
            platform_support(SandboxEnforce::FsNet, "windows"),
            SandboxDecision::Enforce(SandboxBackend::AppContainer)
        );
        assert_eq!(
            platform_support(SandboxEnforce::Off, "linux"),
            SandboxDecision::Off
        );
    }

    #[test]
    fn sandbox_resolve_off_yields_none() {
        let cfg = crate::types::SandboxConfig {
            enforce: crate::types::SandboxEnforce::Off,
            provider: crate::types::SandboxProvider::Process,
            image: None,
            extra_write: vec![],
            egress: vec![],
        };
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();

        let (resolved, warn) = resolve_for_session(&cfg, session.path(), mission.path());
        assert!(resolved.is_none());
        assert!(warn.is_none());
    }

    #[test]
    fn sandbox_resolve_linux_requires_bwrap() {
        let cfg = crate::types::SandboxConfig {
            enforce: crate::types::SandboxEnforce::Fs,
            provider: crate::types::SandboxProvider::Process,
            image: None,
            extra_write: vec![],
            egress: vec![],
        };
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();

        let (resolved, warn) = resolve_for_session_target(
            &cfg,
            session.path(),
            mission.path(),
            "linux",
            false,
            None,
            None,
        );
        assert!(resolved.is_none());
        assert!(
            warn.unwrap().contains("bwrap"),
            "missing-bwrap warning should name bwrap"
        );

        let (resolved, warn) = resolve_for_session_target(
            &cfg,
            session.path(),
            mission.path(),
            "linux",
            true,
            None,
            None,
        );
        assert!(warn.is_none());
        assert_eq!(
            resolved.expect("bwrap present").backend,
            SandboxBackend::Bubblewrap
        );
    }

    fn container_cfg(
        enforce: crate::types::SandboxEnforce,
        egress: Vec<String>,
    ) -> crate::types::SandboxConfig {
        crate::types::SandboxConfig {
            enforce,
            provider: crate::types::SandboxProvider::Container,
            image: None,
            extra_write: vec![],
            egress,
        }
    }

    #[test]
    fn container_provider_off_stays_unsandboxed() {
        let cfg = container_cfg(crate::types::SandboxEnforce::Off, vec![]);
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();

        let (resolved, warn) = resolve_for_session_target(
            &cfg,
            session.path(),
            mission.path(),
            "macos",
            false,
            None,
            None,
        );
        assert!(resolved.is_none());
        assert!(warn.is_none());
    }

    #[test]
    fn container_provider_on_macos_resolves_only_against_a_mount_proof() {
        use crate::sandbox_container::{ContainerRuntime, MountProof};
        let cfg = container_cfg(crate::types::SandboxEnforce::Fs, vec![]);
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();
        let resolve = |proof: Option<MountProof>| {
            resolve_for_session_target(
                &cfg,
                session.path(),
                mission.path(),
                "macos",
                false,
                Some(ContainerRuntime::Docker),
                proof,
            )
        };

        // A host that proved the round trip is supported, receipt or no receipt.
        let (resolved, warn) = resolve(Some(MountProof::Proven));
        assert!(resolved.is_some(), "a proven mount must resolve: {warn:?}");

        // A host whose mount shares nothing is refused, and the operator is
        // told which path failed rather than that the platform is unsupported.
        let (resolved, warn) = resolve(Some(MountProof::Failed(
            "docker accepted a bind mount of /var/folders/x and shared nothing".to_string(),
        )));
        assert!(resolved.is_none());
        let warn = warn.expect("a failed proof must refuse loudly");
        assert!(warn.contains("/var/folders/x"), "{warn}");
        assert!(warn.contains("shared nothing"), "{warn}");

        // No proof is not the same as a passing proof.
        let (resolved, warn) = resolve(None);
        assert!(resolved.is_none());
        let warn = warn.expect("an unproven host must refuse");
        assert!(warn.contains("requires a bind-mount proof"), "{warn}");
    }

    #[test]
    fn container_provider_on_windows_refuses_even_a_proven_mount() {
        use crate::sandbox_container::{ContainerRuntime, MountProof};
        let cfg = container_cfg(crate::types::SandboxEnforce::Fs, vec![]);
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();

        // Windows fails the POSIX guest-path and /dev/null authority-mask
        // contract, which a mount proof says nothing about.
        let (resolved, warn) = resolve_for_session_target(
            &cfg,
            session.path(),
            mission.path(),
            "windows",
            false,
            Some(ContainerRuntime::Docker),
            Some(MountProof::Proven),
        );
        assert!(resolved.is_none());
        let warn = warn.expect("windows must refuse");
        assert!(
            warn.contains("not supported on target_os=windows"),
            "{warn}"
        );
        assert!(warn.contains("POSIX guest paths"), "{warn}");
    }

    #[test]
    fn container_provider_without_runtime_fails_closed() {
        let cfg = container_cfg(crate::types::SandboxEnforce::Fs, vec![]);
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();

        let (resolved, warn) = resolve_for_session_target(
            &cfg,
            session.path(),
            mission.path(),
            "linux",
            false,
            None,
            None,
        );
        assert!(resolved.is_none());
        let warn = warn.expect("missing runtime must produce a warning");
        assert!(warn.contains("provider:container"), "{warn}");
        assert!(warn.contains("docker/podman/nerdctl/container"), "{warn}");
        assert!(warn.contains("refusing to run unsandboxed"), "{warn}");
    }

    #[test]
    fn macos_enforced_container_provider_fails_closed_to_native_process_guidance() {
        let cfg = container_cfg(crate::types::SandboxEnforce::Fs, vec![]);
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();

        let (resolved, warning) = resolve_for_session_target(
            &cfg,
            session.path(),
            mission.path(),
            "macos",
            false,
            Some(crate::sandbox_container::ContainerRuntime::Docker),
            None,
        );
        assert!(resolved.is_none());
        let warning = warning.expect("an unproved macOS container must refuse");
        // The refusal is now about THIS host's evidence, not about the
        // platform: an unproved macOS host is refused, and a proved one
        // resolves (container_provider_on_macos_resolves_only_against_a_mount_proof).
        assert!(warning.contains("requires a bind-mount proof"), "{warning}");
        assert!(
            warning.contains("sandbox.provider=\"process\""),
            "{warning}"
        );
        assert!(warning.contains("native host containment"), "{warning}");
    }

    /// M7 Windows parity, phase 4: the process provider resolves the stable
    /// AppContainer backend. Merely finding `docker.exe` still does not prove
    /// the Windows container mount contract, so that provider stays refused;
    /// `off` remains the operator's explicit unsandboxed posture.
    #[test]
    fn windows_enforced_session_process_resolves_appcontainer_while_container_fails_closed() {
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();

        for enforce in [
            crate::types::SandboxEnforce::Fs,
            crate::types::SandboxEnforce::FsNet,
        ] {
            let process = crate::types::SandboxConfig {
                enforce,
                provider: crate::types::SandboxProvider::Process,
                image: None,
                extra_write: vec![],
                egress: vec![],
            };
            let (resolved, warning) = resolve_for_session_target(
                &process,
                session.path(),
                mission.path(),
                "windows",
                false,
                Some(crate::sandbox_container::ContainerRuntime::Docker),
                None,
            );
            assert!(warning.is_none(), "{warning:?}");
            let resolved = resolved.expect("Windows process enforcement resolves");
            assert_eq!(resolved.backend, SandboxBackend::AppContainer);
            assert_eq!(resolved.inputs.enforce, enforce);
            assert_eq!(resolved.inputs.session_cwd, session.path());
            assert_eq!(resolved.inputs.mission_dir, mission.path());

            let container = container_cfg(enforce, vec![]);
            let (resolved, warning) = resolve_for_session_target(
                &container,
                session.path(),
                mission.path(),
                "windows",
                false,
                Some(crate::sandbox_container::ContainerRuntime::Docker),
                None,
            );
            assert!(resolved.is_none());
            let warning = warning.expect("an unproved Windows container must refuse");
            // Windows is refused on its own contract gap, not for want of a
            // mount proof: guest paths and /dev/null masks are what fail
            // there, so no probe result could change this answer.
            assert!(
                warning.contains("not supported on target_os=windows"),
                "{warning}"
            );
            assert!(
                warning.contains("unverified container mount contract"),
                "{warning}"
            );
        }

        let off = container_cfg(crate::types::SandboxEnforce::Off, vec![]);
        let (resolved, warning) = resolve_for_session_target(
            &off,
            session.path(),
            mission.path(),
            "windows",
            false,
            Some(crate::sandbox_container::ContainerRuntime::Docker),
            None,
        );
        assert!(resolved.is_none());
        assert!(warning.is_none());
    }

    #[test]
    fn container_provider_fs_net_with_egress_list_resolves_for_the_proxy() {
        let cfg = container_cfg(
            crate::types::SandboxEnforce::FsNet,
            vec!["crates.io:443".to_string()],
        );
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();

        // Docker resolves the posture; the runner provisions the unique
        // internal network + authenticated relay before session spawn.
        let (resolved, warn) = resolve_for_session_target(
            &cfg,
            session.path(),
            mission.path(),
            "linux",
            false,
            Some(crate::sandbox_container::ContainerRuntime::Docker),
            None,
        );
        assert!(warn.is_none(), "{warn:?}");
        let resolved = resolved.expect("container fs+net with egress must resolve");
        assert_eq!(resolved.backend, SandboxBackend::Container);
        assert_eq!(resolved.inputs.egress, vec!["crates.io:443".to_string()]);
    }

    #[test]
    fn container_provider_fs_net_with_egress_refuses_non_docker_runtime() {
        let cfg = container_cfg(
            crate::types::SandboxEnforce::FsNet,
            vec!["crates.io:443".to_string()],
        );
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();
        let (resolved, warning) = resolve_for_session_target(
            &cfg,
            session.path(),
            mission.path(),
            "linux",
            false,
            Some(crate::sandbox_container::ContainerRuntime::Podman),
            None,
        );
        assert!(resolved.is_none());
        let warning = warning.expect("unproved runtime must fail closed");
        assert!(warning.contains("requires Docker"), "{warning}");
        assert!(warning.contains("podman"), "{warning}");
    }

    #[test]
    fn container_provider_resolves_runtime_and_image() {
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();

        // Default image when config names none.
        let cfg = container_cfg(crate::types::SandboxEnforce::FsNet, vec![]);
        let (resolved, warn) = resolve_for_session_target(
            &cfg,
            session.path(),
            mission.path(),
            "linux",
            false,
            Some(crate::sandbox_container::ContainerRuntime::Podman),
            None,
        );
        assert!(warn.is_none());
        let resolved = resolved.expect("runtime present and policy supportable");
        assert_eq!(resolved.backend, SandboxBackend::Container);
        let container = resolved.container.expect("container spec must be set");
        assert_eq!(
            container.runtime,
            crate::sandbox_container::ContainerRuntime::Podman
        );
        assert_eq!(container.image, crate::sandbox_container::DEFAULT_IMAGE);

        // Configured image overrides the default.
        let mut cfg = container_cfg(crate::types::SandboxEnforce::Fs, vec![]);
        cfg.image = Some("ghcr.io/example/kranz-worker:1".to_string());
        let (resolved, warn) = resolve_for_session_target(
            &cfg,
            session.path(),
            mission.path(),
            "linux",
            false,
            Some(crate::sandbox_container::ContainerRuntime::Docker),
            None,
        );
        assert!(warn.is_none());
        assert_eq!(
            resolved
                .expect("runtime present")
                .container
                .expect("container spec")
                .image,
            "ghcr.io/example/kranz-worker:1"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn sandbox_resolve_fs_on_macos_yields_resolved_sandbox() {
        let cfg = crate::types::SandboxConfig {
            enforce: crate::types::SandboxEnforce::Fs,
            provider: crate::types::SandboxProvider::Process,
            image: None,
            extra_write: vec![],
            egress: vec![],
        };
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();

        let (resolved, warn) = resolve_for_session(&cfg, session.path(), mission.path());
        assert!(warn.is_none());
        let resolved = resolved.expect("expected an enforced sandbox on macos");
        assert_eq!(resolved.backend, SandboxBackend::Seatbelt);
        assert_eq!(resolved.inputs.session_cwd, session.path());
        assert_eq!(resolved.inputs.mission_dir, mission.path());
        assert!(!resolved.inputs.tmpdir.as_os_str().is_empty());
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn sandbox_resolve_prewarms_apple_git_cache_before_profile_use() {
        use std::process::Command;

        let _guard = SANDBOX_EXEC_TEST_LOCK.lock().unwrap();
        if !sandbox_exec_can_apply() {
            return;
        }

        let repo = tempfile::tempdir().unwrap();
        let init = Command::new("/usr/bin/git")
            .args(["init", "--quiet"])
            .current_dir(repo.path())
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .status()
            .expect("initialize disposable repository");
        assert!(init.success());
        let mission = tempfile::tempdir().unwrap();
        let cfg = crate::types::SandboxConfig {
            enforce: crate::types::SandboxEnforce::Fs,
            provider: crate::types::SandboxProvider::Process,
            image: None,
            extra_write: vec![],
            egress: vec![],
        };

        // Resolution performs the bounded host-side prewarm before the
        // generated profile can deny the shared xcrun cache refresh.
        let (resolved, warn) = resolve_for_session(&cfg, repo.path(), mission.path());
        assert!(warn.is_none());
        let resolved = resolved.expect("Seatbelt resolves on macOS");
        let profile_dir = tempfile::tempdir().unwrap();
        let profile_path =
            write_profile_file(profile_dir.path(), &generate_profile(&resolved.inputs)).unwrap();
        let output = Command::new("sandbox-exec")
            .arg("-f")
            .arg(profile_path)
            .arg("/usr/bin/git")
            .args(["status", "--short"])
            .current_dir(repo.path())
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .output()
            .expect("run Apple Git under the resolved profile");
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(output.status.success(), "Apple Git must run: {stderr}");
        assert!(
            !stderr.contains("xcrun_db"),
            "the host-side prewarm must prevent an in-sandbox cache refresh: {stderr}"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn sandbox_resolve_expands_tilde_extra_write_via_home() {
        let cfg = crate::types::SandboxConfig {
            enforce: crate::types::SandboxEnforce::Fs,
            provider: crate::types::SandboxProvider::Process,
            image: None,
            extra_write: vec!["~/.cargo".to_string()],
            egress: vec![],
        };
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();
        let home = std::env::var("HOME").expect("HOME must be set to run this test");

        let (resolved, _warn) = resolve_for_session(&cfg, session.path(), mission.path());
        let resolved = resolved.expect("expected an enforced sandbox on macos");
        assert_eq!(
            resolved.inputs.extra_write,
            vec![PathBuf::from(home).join(".cargo")]
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn sandbox_resolve_fs_net_on_macos_yields_seatbelt_with_loopback_profile() {
        let cfg = crate::types::SandboxConfig {
            enforce: crate::types::SandboxEnforce::FsNet,
            provider: crate::types::SandboxProvider::Process,
            image: None,
            extra_write: vec![],
            egress: vec![],
        };
        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();

        let (resolved, warn) = resolve_for_session(&cfg, session.path(), mission.path());

        assert!(warn.is_none(), "fs+net on macOS resolves: {warn:?}");
        let resolved = resolved.expect("fs+net on macOS resolves to Seatbelt");
        assert_eq!(resolved.backend, SandboxBackend::Seatbelt);
        let profile = generate_profile(&resolved.inputs);
        assert!(
            profile.contains("(allow network-outbound (remote tcp \"localhost:*\"))"),
            "fs+net profile must restrict egress to loopback so only the egress proxy is reachable:\n{profile}"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn sandbox_enforcement_macos_allows_inside_denies_outside() {
        use std::process::Command;

        let _guard = SANDBOX_EXEC_TEST_LOCK.lock().unwrap();

        if !sandbox_exec_can_apply() {
            return;
        }

        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();

        let profile = generate_profile(&inputs(session.path(), mission.path(), tmp.path(), vec![]));
        let profile_dir = tempfile::tempdir().unwrap();
        let profile_path = write_profile_file(profile_dir.path(), &profile).unwrap();

        let inside_file = session.path().join("inside.txt");
        let inside_status = Command::new("sandbox-exec")
            .arg("-f")
            .arg(&profile_path)
            .arg("/bin/sh")
            .arg("-c")
            .arg(format!("echo hi > {}", inside_file.display()))
            .status()
            .expect("failed to run sandbox-exec");
        assert!(
            inside_status.success(),
            "expected write inside session_cwd to succeed"
        );
        assert!(inside_file.exists(), "expected inside file to be created");

        let dev_null_status = Command::new("sandbox-exec")
            .arg("-f")
            .arg(&profile_path)
            .arg("/bin/sh")
            .arg("-c")
            .arg("echo hi > /dev/null 2>&1")
            .status()
            .expect("failed to run sandbox-exec");
        assert!(
            dev_null_status.success(),
            "ordinary shell redirects to /dev/null must succeed"
        );

        let outside_file = outside.path().join(format!(
            "kranz_sandbox_should_fail_{}",
            uuid::Uuid::new_v4()
        ));
        let outside_status = Command::new("sandbox-exec")
            .arg("-f")
            .arg(&profile_path)
            .arg("/bin/sh")
            .arg("-c")
            .arg(format!("echo hi > {}", outside_file.display()))
            .status()
            .expect("failed to run sandbox-exec");
        assert!(
            !outside_status.success(),
            "expected write outside allowlist to be denied"
        );
        assert!(
            !outside_file.exists(),
            "denied write must not have created the file"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn sandbox_enforcement_macos_denies_authority_material_reads() {
        use std::process::Command;

        let _guard = SANDBOX_EXEC_TEST_LOCK.lock().unwrap();

        if !sandbox_exec_can_apply() {
            return;
        }

        let repo = tempfile::tempdir().unwrap();
        let mission = repo.path().join(".kranz").join("missions").join("m-x");
        std::fs::create_dir_all(&mission).unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let kranz_dir = repo.path().join(".kranz");
        for name in [
            "serve.token",
            "serve.read.token",
            "config.json",
            "domain-terms.local",
        ] {
            std::fs::write(kranz_dir.join(name), "secret").unwrap();
        }
        let public = repo.path().join("public.txt");
        std::fs::write(&public, "public").unwrap();

        let profile = generate_profile(&inputs(repo.path(), &mission, tmp.path(), vec![]));
        let profile_dir = tempfile::tempdir().unwrap();
        let profile_path = write_profile_file(profile_dir.path(), &profile).unwrap();

        for name in [
            "serve.token",
            "serve.read.token",
            "config.json",
            "domain-terms.local",
        ] {
            let status = Command::new("sandbox-exec")
                .arg("-f")
                .arg(&profile_path)
                .arg("/bin/cat")
                .arg(kranz_dir.join(name))
                .status()
                .expect("failed to run sandbox-exec");
            assert!(
                !status.success(),
                "sandboxed read of .kranz/{name} must be denied"
            );
        }

        // Ordinary repo reads keep working under the same profile.
        let output = Command::new("sandbox-exec")
            .arg("-f")
            .arg(&profile_path)
            .arg("/bin/cat")
            .arg(&public)
            .output()
            .expect("failed to run sandbox-exec");
        assert!(
            output.status.success(),
            "ordinary repo reads must keep working: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(String::from_utf8_lossy(&output.stdout), "public");
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn sandbox_enforcement_macos_denies_mission_metadata_writes() {
        use std::process::Command;

        let _guard = SANDBOX_EXEC_TEST_LOCK.lock().unwrap();

        if !sandbox_exec_can_apply() {
            return;
        }

        // Checkout-mode shape: session_cwd is the repo root, an ANCESTOR of
        // the mission dir — the hostile case the write denies exist for.
        let repo = tempfile::tempdir().unwrap();
        let mission = repo.path().join(".kranz").join("missions").join("m-x");
        let runs = mission.join("runs");
        std::fs::create_dir_all(&runs).unwrap();
        let control = mission.join("control");
        std::fs::create_dir_all(&control).unwrap();
        let contract_home = runs.join("contract-home");
        std::fs::create_dir_all(&contract_home).unwrap();
        let events = mission.join("events.jsonl");
        let state = mission.join("state.json");
        let old_transcript = runs.join("run-old.jsonl");
        std::fs::write(&events, "{\"seq\":1}\n").unwrap();
        std::fs::write(&state, "{}").unwrap();
        std::fs::write(&old_transcript, "original\n").unwrap();
        let scratch = tempfile::tempdir().unwrap();

        let profile = generate_profile(&inputs(repo.path(), &mission, scratch.path(), vec![]));
        let profile_dir = tempfile::tempdir().unwrap();
        let profile_path = write_profile_file(profile_dir.path(), &profile).unwrap();

        // Engine-owned paths refuse writes — including a NEW runs/*.jsonl
        // (the transcript regex denies creation, not just modification).
        let denied_writes = [
            format!("echo tampered >> {}", events.display()),
            format!("echo tampered > {}", state.display()),
            format!("echo x > {}", control.join("approve.json").display()),
            format!("echo forged >> {}", old_transcript.display()),
            format!("echo forged > {}", runs.join("run-new.jsonl").display()),
        ];
        for write in denied_writes {
            let status = Command::new("sandbox-exec")
                .arg("-f")
                .arg(&profile_path)
                .arg("/bin/sh")
                .arg("-c")
                .arg(&write)
                .status()
                .expect("failed to run sandbox-exec");
            assert!(!status.success(), "write must be denied: {write}");
        }
        assert_eq!(std::fs::read_to_string(&events).unwrap(), "{\"seq\":1}\n");
        assert_eq!(std::fs::read_to_string(&state).unwrap(), "{}");
        assert_eq!(
            std::fs::read_to_string(&old_transcript).unwrap(),
            "original\n"
        );
        assert!(!runs.join("run-new.jsonl").exists());
        assert!(std::fs::read_dir(&control).unwrap().next().is_none());

        // The session's own work continues under the same profile: the repo
        // tree, the private scratch, and runs/ SUBDIRECTORIES stay writable.
        let allowed_writes = [
            repo.path().join("src.txt"),
            scratch.path().join("notes.txt"),
            contract_home.join("out.txt"),
        ];
        for target in allowed_writes {
            let status = Command::new("sandbox-exec")
                .arg("-f")
                .arg(&profile_path)
                .arg("/bin/sh")
                .arg("-c")
                .arg(format!("echo ok > {}", target.display()))
                .status()
                .expect("failed to run sandbox-exec");
            assert!(
                status.success(),
                "write must be allowed: {}",
                target.display()
            );
            assert!(target.exists());
        }
    }

    /// The live half of `sandbox_profile_denies_authority_material_writes`
    /// and `..._git_config_and_hook_writes...`: a real `sandbox-exec` run
    /// under a checkout-mode profile refuses the writes and keeps the
    /// session's own work going (H2, H11, H3 support).
    #[cfg(target_os = "macos")]
    #[test]
    fn sandbox_enforcement_macos_denies_authority_and_git_metadata_writes() {
        use std::process::Command;

        let _guard = SANDBOX_EXEC_TEST_LOCK.lock().unwrap();

        if !sandbox_exec_can_apply() {
            return;
        }

        let (repo, mission) = authority_write_fixture();
        let scratch = tempfile::tempdir().unwrap();
        let kranz = repo.path().join(".kranz");
        let git = repo.path().join(".git");
        std::fs::write(git.join("index"), "idx").unwrap();

        let profile = generate_profile(&inputs(repo.path(), &mission, scratch.path(), vec![]));
        let profile_dir = tempfile::tempdir().unwrap();
        let profile_path = write_profile_file(profile_dir.path(), &profile).unwrap();

        let denied = [
            // The trust root: overwritten without ever being read.
            format!("echo '{{}}' > {}", kranz.join("config.json").display()),
            // A sibling mission's control inbox (forged operator consent).
            format!(
                "echo x > {}",
                kranz
                    .join("missions")
                    .join("m-other")
                    .join("approve.json")
                    .display()
            ),
            // A NEW sibling mission dir, and a NEW repo-level store.
            format!(
                "mkdir {}",
                kranz.join("missions").join("m-forged").display()
            ),
            format!("mkdir {}", kranz.join("newstore").display()),
            // Repo-level engine stores.
            format!("echo x > {}", kranz.join("queue").join("q.json").display()),
            format!("echo x > {}", kranz.join("lessons").join("l.md").display()),
            // The git hook and config surface the engine's next checkpoint
            // commit would execute.
            format!(
                "echo x > {}",
                git.join("hooks").join("pre-commit").display()
            ),
            format!("echo x > {}", git.join("config").display()),
        ];
        for command in &denied {
            let status = Command::new("sandbox-exec")
                .arg("-f")
                .arg(&profile_path)
                .arg("/bin/sh")
                .arg("-c")
                .arg(command)
                .status()
                .expect("failed to run sandbox-exec");
            assert!(!status.success(), "write must be denied: {command}");
        }
        assert_eq!(
            std::fs::read_to_string(kranz.join("config.json")).unwrap(),
            "secret"
        );
        assert!(!kranz.join("missions").join("m-forged").exists());
        assert!(!kranz.join("newstore").exists());
        assert!(!git.join("hooks").join("pre-commit").exists());

        // The session's own work is untouched: the repo tree, the private
        // scratch, its own mission scratch under runs/, and the git index
        // the worker's own `git commit` writes.
        let allowed = [
            repo.path().join("src.txt"),
            scratch.path().join("notes.txt"),
            mission.join("runs").join("scratch").join("out.txt"),
            git.join("index"),
        ];
        for target in allowed {
            let status = Command::new("sandbox-exec")
                .arg("-f")
                .arg(&profile_path)
                .arg("/bin/sh")
                .arg("-c")
                .arg(format!("echo ok > {}", target.display()))
                .status()
                .expect("failed to run sandbox-exec");
            assert!(
                status.success(),
                "write must be allowed: {}",
                target.display()
            );
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn sandbox_enforcement_macos_denies_sibling_temp_neighbors() {
        use std::process::Command;

        let _guard = SANDBOX_EXEC_TEST_LOCK.lock().unwrap();

        if !sandbox_exec_can_apply() {
            return;
        }

        // The finding's layout: every mission's integration/feature
        // worktrees and scratch homes sit side by side under the shared
        // temp root. A session must write its own worktree + scratch and
        // nothing beside them.
        let root = tempfile::tempdir().unwrap();
        let session = root.path().join("kranz-wt-aaa-m1-f-1-1");
        let scratch = root.path().join("kranz-worker-home-sess-1");
        let scratch_home = scratch.join("home");
        let sibling = root.path().join("kranz-wt-bbb-m2-_integration");
        let sibling_scratch = root.path().join("kranz-worker-home-sess-2");
        for d in [&session, &scratch_home, &sibling, &sibling_scratch] {
            std::fs::create_dir_all(d).unwrap();
        }
        let mission = tempfile::tempdir().unwrap();

        let profile = generate_profile(&inputs(&session, mission.path(), &scratch, vec![]));
        let profile_dir = tempfile::tempdir().unwrap();
        let profile_path = write_profile_file(profile_dir.path(), &profile).unwrap();

        for allowed in [session.join("code.rs"), scratch_home.join("notes.txt")] {
            let status = Command::new("sandbox-exec")
                .arg("-f")
                .arg(&profile_path)
                .arg("/bin/sh")
                .arg("-c")
                .arg(format!("echo ok > {}", allowed.display()))
                .status()
                .expect("failed to run sandbox-exec");
            assert!(
                status.success(),
                "write inside the session's own roots must be allowed: {}",
                allowed.display()
            );
            assert!(allowed.exists());
        }

        for denied in [
            sibling.join("evil.txt"),
            sibling_scratch.join("evil.txt"),
            root.path().join("evil.txt"),
        ] {
            let status = Command::new("sandbox-exec")
                .arg("-f")
                .arg(&profile_path)
                .arg("/bin/sh")
                .arg("-c")
                .arg(format!("echo evil > {}", denied.display()))
                .status()
                .expect("failed to run sandbox-exec");
            assert!(
                !status.success(),
                "write to a temp neighbor must be denied: {}",
                denied.display()
            );
            assert!(!denied.exists());
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn sandbox_enforcement_macos_fs_net_loopback_profile_applies() {
        use std::process::Command;

        let _guard = SANDBOX_EXEC_TEST_LOCK.lock().unwrap();

        if !sandbox_exec_can_apply() {
            return;
        }

        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let mut inputs = inputs(session.path(), mission.path(), tmp.path(), vec![]);
        inputs.enforce = crate::types::SandboxEnforce::FsNet;

        // The fs+net profile (loopback-only egress) must be ACCEPTED by
        // sandbox-exec — unlike the hostname-rule shape Seatbelt rejects with
        // "host must be * or localhost" — or fs+net sessions could not run.
        let profile = generate_profile(&inputs);
        let profile_dir = tempfile::tempdir().unwrap();
        let profile_path = write_profile_file(profile_dir.path(), &profile).unwrap();

        let applied = Command::new("sandbox-exec")
            .arg("-f")
            .arg(&profile_path)
            .arg("/usr/bin/true")
            .output()
            .expect("failed to run sandbox-exec");
        assert!(
            applied.status.success(),
            "loopback-only fs+net profile must apply cleanly on macOS: {}",
            String::from_utf8_lossy(&applied.stderr)
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn sandbox_enforcement_linux_bwrap_allows_inside_denies_outside() {
        use std::process::Command;

        if !bwrap_can_apply() {
            return;
        }

        let session = tempfile::tempdir().unwrap();
        let mission = tempfile::tempdir().unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let inputs = inputs(session.path(), mission.path(), tmp.path(), vec![]);

        let inside_file = session.path().join("inside.txt");
        let inside_args = bubblewrap_args(
            &inputs,
            Path::new("/bin/sh"),
            &["-c".into(), format!("echo hi > {}", inside_file.display())],
        )
        .unwrap();
        let inside_status = Command::new("bwrap")
            .args(inside_args)
            .status()
            .expect("failed to run bwrap");
        assert!(
            inside_status.success(),
            "expected write inside session_cwd to succeed"
        );
        assert!(inside_file.exists(), "expected inside file to be created");

        let outside_file = outside
            .path()
            .join(format!("kranz_bwrap_should_fail_{}", uuid::Uuid::new_v4()));
        let outside_args = bubblewrap_args(
            &inputs,
            Path::new("/bin/sh"),
            &["-c".into(), format!("echo hi > {}", outside_file.display())],
        )
        .unwrap();
        let outside_status = Command::new("bwrap")
            .args(outside_args)
            .status()
            .expect("failed to run bwrap");
        assert!(
            !outside_status.success(),
            "expected write outside allowlist to be denied"
        );
        assert!(
            !outside_file.exists(),
            "denied write must not have created the file"
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn sandbox_enforcement_linux_bwrap_tolerates_disappearing_visible_entries() {
        if crate::agent_env::isolated_global_home_test(
            "sandbox::tests::sandbox_enforcement_linux_bwrap_tolerates_disappearing_visible_entries",
        ) {
            return;
        }
        if !bwrap_can_apply() {
            return;
        }
        let repo = tempfile::tempdir().unwrap();
        let scratch = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        let _env =
            crate::agent_env::EnvTestGuard::engage(&[("HOME", home.path().to_str().unwrap())]);
        let kranz = home.path().join(".kranz");
        let mission = repo.path().join(".kranz/missions/m-mask-race");
        std::fs::create_dir_all(&mission).unwrap();
        let transient_dir = home.path().join("temporary-cache");
        let transient_file = home.path().join("temporary-note");
        let public = home.path().join("public.txt");
        let authority_path = repo.path().join(".kranz/serve.token");
        let late_authority_path = kranz.join("serve.read.token");
        let writable = repo.path().join("result.txt");
        std::fs::create_dir(&transient_dir).unwrap();
        std::fs::write(&transient_file, "temporary").unwrap();
        std::fs::write(&public, "public").unwrap();
        std::fs::write(&authority_path, "secret").unwrap();
        let args = bubblewrap_args(
            &inputs(repo.path(), &mission, scratch.path(), vec![]),
            Path::new("/bin/sh"),
            &[
                "-c".into(),
                "test ! -e \"$1\" && test ! -e \"$2\" \
                 && test \"$(cat \"$3\")\" = public && ! touch \"$3\" \
                 && test ! -e \"$4\" && test ! -e \"$5\" \
                 && printf ok > \"$6\""
                    .into(),
                "mask-race".into(),
                transient_dir.display().to_string(),
                transient_file.display().to_string(),
                public.display().to_string(),
                authority_path.display().to_string(),
                late_authority_path.display().to_string(),
                writable.display().to_string(),
            ],
        )
        .unwrap();
        for path in [&transient_dir, &transient_file] {
            let path = absolutize(path).display().to_string();
            assert!(args.windows(3).any(|part| {
                matches!(part[0].as_str(), "--ro-bind" | "--ro-bind-try")
                    && part[1] == path
                    && part[2] == path
            }));
        }
        // Deterministically reproduce deletion between enumeration and mount
        // setup, while also creating authority that the private view must hide.
        std::fs::remove_dir(&transient_dir).unwrap();
        std::fs::remove_file(&transient_file).unwrap();
        std::fs::create_dir(&kranz).unwrap();
        std::fs::write(&late_authority_path, "late-secret").unwrap();
        let output = std::process::Command::new("bwrap")
            .args(args)
            .env_clear()
            .env("PATH", "/usr/bin:/bin")
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "missing ordinary entries must stay hidden without breaking the sandbox: {output:?}"
        );
        assert_eq!(std::fs::read_to_string(&writable).unwrap(), "ok");
        assert_eq!(std::fs::read_to_string(&public).unwrap(), "public");
        assert_eq!(std::fs::read_to_string(&authority_path).unwrap(), "secret");
        assert_eq!(
            std::fs::read_to_string(&late_authority_path).unwrap(),
            "late-secret"
        );
    }

    #[cfg(unix)]
    #[test]
    fn sandbox_bwrap_rebinding_keeps_git_and_authority_protected() {
        if crate::agent_env::isolated_global_home_test(
            "sandbox::tests::sandbox_bwrap_rebinding_keeps_git_and_authority_protected",
        ) {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path().canonicalize().unwrap();
        let cargo = home.join(".cargo");
        std::fs::create_dir(home.join(".kranz")).unwrap();
        let _env = crate::agent_env::EnvTestGuard::engage(&[
            ("HOME", home.to_str().unwrap()),
            ("CARGO_HOME", cargo.to_str().unwrap()),
        ]);
        // The absent Cargo home promotes its authority mask to HOME, above
        // the checkout. A validator snapshot also gets rebound below runs/.
        assert!(!cargo.exists());
        for snapshot in [false, true] {
            let repo = home.join(if snapshot {
                "validator-repo"
            } else {
                "checkout"
            });
            let mission = repo.join(".kranz/missions/m-rebind");
            let scratch = mission.join("runs/scratch");
            let cwd = if snapshot {
                mission.join("runs/snapshot")
            } else {
                repo.clone()
            };
            for path in [&cwd, &scratch] {
                std::fs::create_dir_all(path).unwrap();
            }
            let protected = if snapshot {
                vec![cwd.join(".git")]
            } else {
                std::fs::create_dir_all(cwd.join(".git/hooks")).unwrap();
                vec![cwd.join(".git/config"), cwd.join(".git/hooks/probe")]
            };
            for path in &protected {
                std::fs::write(path, "protected").unwrap();
            }
            let authority_path = repo.join(".kranz/serve.token");
            std::fs::write(&authority_path, "secret").unwrap();
            let ordinary = if snapshot {
                cwd.join("witness")
            } else {
                cwd.join(".git/index")
            };
            let mut command = vec![
                "-c".into(),
                "printf work > \"$1\" || exit 1; printf work > \"$2\" || exit 2; \
                 if cat \"$3\"; then exit 3; fi; shift 3; \
                 for path in \"$@\"; do \
                 test \"$(cat \"$path\")\" = protected || exit 4; \
                 if printf forged > \"$path\"; then exit 5; fi; done"
                    .into(),
                "rebind-test".into(),
                ordinary.display().to_string(),
                scratch.join("witness").display().to_string(),
                authority_path.display().to_string(),
            ];
            command.extend(protected.iter().map(|path| path.display().to_string()));
            let args = bubblewrap_args(
                &inputs(&cwd, &mission, &scratch, vec![]),
                Path::new("/bin/sh"),
                &command,
            )
            .unwrap();
            for path in &protected {
                let last_bind = args.windows(3).rev().find(|part| {
                    matches!(part[0].as_str(), "--bind" | "--ro-bind" | "--ro-bind-try")
                        && path.starts_with(&part[2])
                });
                assert_eq!(
                    last_bind.map(|part| part[0].as_str()),
                    Some("--ro-bind"),
                    "a later writable ancestor reopened {}: {args:?}",
                    path.display()
                );
            }
            #[cfg(target_os = "linux")]
            if bwrap_can_apply() {
                let output = std::process::Command::new("bwrap")
                    .args(&args)
                    .env_clear()
                    .env("PATH", "/usr/bin:/bin")
                    .output()
                    .unwrap();
                assert!(output.status.success(), "snapshot={snapshot}: {output:?}");
                assert_eq!(std::fs::read_to_string(&ordinary).unwrap(), "work");
                assert_eq!(std::fs::read_to_string(&authority_path).unwrap(), "secret");
                for path in protected {
                    assert_eq!(std::fs::read_to_string(path).unwrap(), "protected");
                }
            }
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn sandbox_enforcement_linux_bwrap_masks_authority_material() {
        if crate::agent_env::isolated_global_home_test(
            "sandbox::tests::sandbox_enforcement_linux_bwrap_masks_authority_material",
        ) {
            return;
        }
        use std::process::Command;

        if !bwrap_can_apply() {
            return;
        }

        let repo = tempfile::tempdir().unwrap();
        let mission = repo.path().join(".kranz").join("missions").join("m-x");
        std::fs::create_dir_all(&mission).unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let serve_token = repo.path().join(".kranz").join("serve.token");
        std::fs::write(&serve_token, "secret").unwrap();
        let public = repo.path().join("public.txt");
        std::fs::write(&public, "public").unwrap();
        let home = tempfile::tempdir().unwrap();
        let authority_target = tempfile::tempdir().unwrap();
        let alias = home.path().join(".kranz");
        std::os::unix::fs::symlink(authority_target.path(), &alias).unwrap();
        let config_target = authority_target.path().join("settings.json");
        std::fs::write(&config_target, "config-secret").unwrap();
        std::os::unix::fs::symlink(&config_target, repo.path().join(".kranz/config.json")).unwrap();
        let _env =
            crate::agent_env::EnvTestGuard::engage(&[("HOME", home.path().to_str().unwrap())]);
        let inputs = inputs(repo.path(), &mission, tmp.path(), vec![home.path().into()]);

        // The private directory has no authority entry at all.
        let masked = Command::new("bwrap")
            .args(
                bubblewrap_args(
                    &inputs,
                    Path::new("/bin/cat"),
                    &[serve_token.display().to_string()],
                )
                .unwrap(),
            )
            .output()
            .expect("failed to run bwrap");
        assert!(
            !masked.status.success(),
            "reading the hidden authority path must fail: {}",
            String::from_utf8_lossy(&masked.stderr)
        );
        assert!(
            !String::from_utf8_lossy(&masked.stdout).contains("secret"),
            "serve.token content must be masked inside the sandbox"
        );

        let late = repo.path().join(".kranz/serve.read.token");
        let args = bubblewrap_args(
            &inputs,
            Path::new("/bin/cat"),
            &[late.display().to_string()],
        )
        .unwrap();
        // Create the token after the mount policy has been resolved. The old
        // existence-filtered file mask would have exposed this value.
        std::fs::write(&late, "late-secret").unwrap();
        let output = Command::new("bwrap").args(args).output().unwrap();
        assert!(!output.status.success());
        assert!(!String::from_utf8_lossy(&output.stdout).contains("late-secret"));

        let host_view = format!("/proc/{}/root{}", std::process::id(), serve_token.display());
        let output = Command::new("bwrap")
            .args(bubblewrap_args(&inputs, Path::new("/bin/cat"), &[host_view]).unwrap())
            .output()
            .unwrap();
        assert!(
            !output.status.success(),
            "host /proc roots must not bypass the namespace"
        );
        assert!(!String::from_utf8_lossy(&output.stdout).contains("secret"));

        for (binary, path) in [("/bin/cat", &config_target), ("/bin/rm", &alias)] {
            let output = Command::new("bwrap")
                .args(
                    bubblewrap_args(&inputs, Path::new(binary), &[path.display().to_string()])
                        .unwrap(),
                )
                .output()
                .unwrap();
            assert!(
                !output.status.success(),
                "authority alias/target was exposed: {output:?}"
            );
        }
        assert!(
            alias.is_symlink(),
            "the operator's authority alias was replaced"
        );

        let control = Command::new("bwrap")
            .args(
                bubblewrap_args(
                    &inputs,
                    Path::new("/bin/cat"),
                    &[public.display().to_string()],
                )
                .unwrap(),
            )
            .output()
            .expect("failed to run bwrap");
        assert_eq!(String::from_utf8_lossy(&control.stdout), "public");
    }

    // -----------------------------------------------------------------------
    // Mandatory validator containment (ticket validator-mandatory-containment)
    // -----------------------------------------------------------------------

    /// A fake real-checkout root in the exact production layout: a source
    /// tree (dir + files, including a dotfile secret), the shared `.git`
    /// dir, and the `.kranz` mission layout with the validator's snapshot
    /// worktree underneath. Returns (tempdir guard, root, snapshot, mission).
    fn validator_containment_fixture() -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("repo");
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src").join("secret.rs"), "fn secret() {}\n").unwrap();
        std::fs::write(root.join("Cargo.toml"), "[package]\n").unwrap();
        // The .env is authority material by NAME (path-based deny); its
        // content is irrelevant to the test and deliberately not
        // secret-shaped (the range scanner fires on TOKEN= shapes — the
        // path is bound separately so no .env + value adjacency exists).
        let dotenv_path = root.join(".env");
        std::fs::write(&dotenv_path, "placeholder-content\n").unwrap();
        std::fs::create_dir_all(root.join(".git")).unwrap();
        std::fs::write(root.join(".git").join("HEAD"), "ref: refs/heads/main\n").unwrap();
        let mission = root.join(".kranz").join("missions").join("m-x");
        let snapshot = mission.join("runs").join("validator-snapshot-scrutiny");
        std::fs::create_dir_all(&snapshot).unwrap();
        std::fs::write(snapshot.join("README.md"), "snapshot copy\n").unwrap();
        std::fs::write(root.join(".kranz").join("serve.token"), "secret-token").unwrap();
        // The sensitive .kranz runtime the 14th-pass over-read finding names
        // (ticket validator-containment-kranz-overread): the plaintext lint
        // vocabulary, the hook-status projection, and the mission control
        // inbox — all reachable through the .kranz carve-out unless the
        // authority read-deny set covers them.
        std::fs::write(
            root.join(".kranz").join("domain-terms.local"),
            "acme widget\n",
        )
        .unwrap();
        let hook_status = root.join(".kranz").join("hook-status").join("m-x");
        std::fs::create_dir_all(&hook_status).unwrap();
        std::fs::write(hook_status.join("run-1.json"), "{\"tokenHash\":\"abc\"}\n").unwrap();
        let control = mission.join("control");
        std::fs::create_dir_all(&control).unwrap();
        std::fs::write(control.join("approve.json"), "{}\n").unwrap();
        (dir, root, snapshot, mission)
    }

    /// A REAL git repo in the same layout (one committed file + a committed
    /// `src/` dir, `.kranz/` ignored, the snapshot as a detached worktree
    /// under the mission's `runs/`) for the applied probes that exercise
    /// the git surface. None when git is not on PATH (mirrors the
    /// orchestrator tests' `lessons_test_repo` skip).
    #[cfg(any(target_os = "macos", target_os = "linux"))]
    fn validator_containment_git_fixture() -> Option<(tempfile::TempDir, PathBuf, PathBuf, PathBuf)>
    {
        let git_ok = std::process::Command::new("git")
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);
        if !git_ok {
            crate::test_capability::skip(
                crate::test_capability::capability::GIT,
                "git is not on PATH",
            );
            return None;
        }
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("repo");
        std::fs::create_dir_all(&root).unwrap();
        let run = |args: &[&str]| {
            let out = std::process::Command::new("git")
                .args(args)
                .current_dir(&root)
                .output()
                .expect("spawn git");
            assert!(out.status.success(), "git {args:?} failed: {out:?}");
        };
        if !std::process::Command::new("git")
            .args(["init", "-b", "main"])
            .current_dir(&root)
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
        {
            run(&["init"]);
            run(&["symbolic-ref", "HEAD", "refs/heads/main"]);
        }
        run(&["config", "user.name", "test"]);
        run(&["config", "user.email", "test@example.com"]);
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src").join("secret.rs"), "fn secret() {}\n").unwrap();
        std::fs::write(root.join("tracked.rs"), "fn tracked() {}\n").unwrap();
        std::fs::write(root.join(".gitignore"), ".kranz/\n").unwrap();
        run(&["add", "-A"]);
        run(&["commit", "-m", "init"]);
        let mission = root.join(".kranz").join("missions").join("m-x");
        let snapshot = mission.join("runs").join("validator-snapshot-scrutiny");
        std::fs::create_dir_all(snapshot.parent().unwrap()).unwrap();
        run(&[
            "worktree",
            "add",
            "--detach",
            snapshot.to_str().expect("utf-8 temp path"),
        ]);
        // Engine-owned metadata + the authority material the denies cover.
        std::fs::write(mission.join("events.jsonl"), "{\"seq\":1}\n").unwrap();
        std::fs::write(root.join(".kranz").join("serve.token"), "secret-token").unwrap();
        Some((dir, root, snapshot, mission))
    }

    /// The mandatory-wrap inputs shape: the snapshot as the sole writable
    /// session root, the real checkout as the read-deny root.
    fn validator_containment_inputs(
        root: &Path,
        snapshot: &Path,
        mission: &Path,
        tmpdir: &Path,
    ) -> SandboxInputs {
        SandboxInputs {
            enforce: crate::types::SandboxEnforce::Fs,
            session_cwd: snapshot.to_path_buf(),
            mission_dir: mission.to_path_buf(),
            tmpdir: tmpdir.to_path_buf(),
            extra_write: Vec::new(),
            egress: Vec::new(),
            validator_read_deny_roots: vec![root.to_path_buf()],
        }
    }

    /// The read-deny set covers the whole source tree — dirs classified as
    /// dirs, files as files, raw AND canonical forms — and NEVER names the
    /// `.git`/`.kranz` carve-outs.
    #[test]
    fn validator_containment_entries_cover_source_tree_and_carve_out_git_and_kranz() {
        let (_dir, root, snapshot, mission) = validator_containment_fixture();
        let scratch = tempfile::tempdir().unwrap();
        let inputs = validator_containment_inputs(&root, &snapshot, &mission, scratch.path());
        let entries = validator_read_deny_entries(&inputs);

        for base in [root.clone(), absolutize(&root)] {
            let src = base.join("src");
            assert!(
                entries.contains(&ValidatorReadDenyEntry {
                    path: src.clone(),
                    is_dir: true
                }),
                "src/ must be a denied dir: {entries:?}"
            );
            for file in ["Cargo.toml", ".env"] {
                assert!(
                    entries.contains(&ValidatorReadDenyEntry {
                        path: base.join(file),
                        is_dir: false
                    }),
                    "{file} must be a denied file: {entries:?}"
                );
            }
        }
        assert!(
            entries.iter().all(|e| e
                .path
                .file_name()
                .is_some_and(|n| n != ".git" && n != ".kranz")),
            "the carve-outs must never be denied: {entries:?}"
        );
    }

    /// The generated profile: a second read-deny block closes the broad read
    /// allow over the real checkout (dirs as subpaths, files and the root
    /// itself as literals) while the snapshot stays writable and the shared
    /// git dir + mission dir stay reachable.
    #[test]
    fn validator_containment_profile_read_denies_source_tree_and_keeps_carveouts() {
        let (_dir, root, snapshot, mission) = validator_containment_fixture();
        let scratch = tempfile::tempdir().unwrap();
        let profile = generate_profile(&validator_containment_inputs(
            &root,
            &snapshot,
            &mission,
            scratch.path(),
        ));
        let read_rules: String = profile
            .split("(deny file-read*")
            .skip(1)
            .map(|block| block.split("\n)\n").next().unwrap_or_default())
            .collect();

        for base in [root.clone(), absolutize(&root)] {
            let src = format!("(subpath \"{}\")", escape_sbpl_literal(&base.join("src")));
            assert!(
                profile.contains(&src),
                "profile missing read deny for src/:\n{profile}"
            );
            for file in ["Cargo.toml", ".env"] {
                let lit = format!("(literal \"{}\")", escape_sbpl_literal(&base.join(file)));
                assert!(
                    profile.contains(&lit),
                    "profile missing read deny for {file}:\n{profile}"
                );
            }
            let root_lit = format!("(literal \"{}\")", escape_sbpl_literal(&base));
            assert!(
                !read_rules.contains(&root_lit),
                "the root itself is deliberately NOT denied (a literal deny breaks \
                 coreutils `mkdir -p`, which stats every ancestor):\n{profile}"
            );
            // The carve-outs are never denied: no rule names the .git or
            // .kranz DIRS themselves (the closing quote makes this exact).
            let git_rule = format!("\"{}\"", escape_sbpl_literal(&base.join(".git")));
            assert!(
                !read_rules.contains(&git_rule),
                ".git must stay readable (the inspection's git surface):\n{profile}"
            );
            let kranz_rule = format!("\"{}\"", escape_sbpl_literal(&base.join(".kranz")));
            assert!(
                !read_rules.contains(&kranz_rule),
                ".kranz must stay reachable (the snapshot lives under it):\n{profile}"
            );
        }
        // …and the .kranz carve-out does not reopen the authority material.
        for base in [root.join(".kranz"), absolutize(&root.join(".kranz"))] {
            let token = format!(
                "(literal \"{}\")",
                escape_sbpl_literal(&base.join("serve.token"))
            );
            assert!(
                profile.contains(&token),
                "the authority read deny must survive the carve-out:\n{profile}"
            );
        }
        // The snapshot stays the writable root.
        let snap_rule = format!(
            "(subpath \"{}\")",
            escape_sbpl_literal(&absolutize(&snapshot))
        );
        assert!(
            profile.contains(&snap_rule),
            "the snapshot must stay writable:\n{profile}"
        );
        // …and /dev/null stays writable (the gate wrap's documented finding:
        // git and the shell open it O_RDWR in ordinary operation).
        assert!(
            profile.contains("(allow file-write* (literal \"/dev/null\"))"),
            "validator profiles must keep /dev/null writable:\n{profile}"
        );
    }

    /// 14th-pass review (ticket `validator-containment-kranz-overread`): the
    /// `.kranz` carve-out the snapshot lives under must not reopen the
    /// sensitive runtime beneath it — the plaintext lint vocabulary
    /// (`domain-terms.local`), the hook-status projection, and the mission
    /// control inbox are read-denied (literal for the file, subpaths for the
    /// dirs) in BOTH raw and canonical forms, exactly like the serve-token
    /// authority material.
    #[test]
    fn validator_containment_profile_denies_sensitive_kranz_runtime_reads() {
        let (_dir, root, snapshot, mission) = validator_containment_fixture();
        let scratch = tempfile::tempdir().unwrap();
        let profile = generate_profile(&validator_containment_inputs(
            &root,
            &snapshot,
            &mission,
            scratch.path(),
        ));
        let read_rules: String = profile
            .split("(deny file-read*")
            .skip(1)
            .map(|block| block.split("\n)\n").next().unwrap_or_default())
            .collect();

        let kranz = root.join(".kranz");
        for base in [kranz.clone(), absolutize(&kranz)] {
            let terms = format!(
                "(literal \"{}\")",
                escape_sbpl_literal(&base.join("domain-terms.local"))
            );
            assert!(
                profile.contains(&terms),
                "profile missing read deny for domain-terms.local:\n{profile}"
            );
            let hook = format!(
                "(subpath \"{}\")",
                escape_sbpl_literal(&base.join("hook-status"))
            );
            assert!(
                profile.contains(&hook),
                "profile missing read deny for hook-status/:\n{profile}"
            );
        }
        for base in [mission.clone(), absolutize(&mission)] {
            let control = format!(
                "(subpath \"{}\")",
                escape_sbpl_literal(&base.join("control"))
            );
            assert!(
                profile.contains(&control),
                "profile missing read deny for the control inbox:\n{profile}"
            );
        }
        // …while the carve-out itself stays: no deny names the .kranz DIR
        // (the closing quote makes this exact).
        for base in [kranz.clone(), absolutize(&kranz)] {
            let kranz_rule = format!("\"{}\"", escape_sbpl_literal(&base));
            assert!(
                !read_rules.contains(&kranz_rule),
                ".kranz must stay reachable (the snapshot lives under it):\n{profile}"
            );
        }
    }

    /// Non-validator sessions (empty roots) get byte-stable profiles: exactly
    /// the pre-containment shape, i.e. only the authority read-deny block.
    #[test]
    fn validator_containment_empty_roots_emit_no_deny_block() {
        let (_dir, root, snapshot, mission) = validator_containment_fixture();
        let scratch = tempfile::tempdir().unwrap();
        let mut inputs = validator_containment_inputs(&root, &snapshot, &mission, scratch.path());
        inputs.validator_read_deny_roots = Vec::new();
        let profile = generate_profile(&inputs);
        assert_eq!(
            profile.matches("(deny file-read*").count(),
            1,
            "empty roots must leave the pre-containment profile shape alone:\n{profile}"
        );

        let profile = generate_profile(&validator_containment_inputs(
            &root,
            &snapshot,
            &mission,
            scratch.path(),
        ));
        assert_eq!(
            profile.matches("(deny file-read*").count(),
            2,
            "the validator read-deny block must land when roots are set:\n{profile}"
        );
    }

    /// The bwrap analogue: source dirs shadowed by tmpfs, source files
    /// masked with /dev/null, carve-outs untouched, the snapshot rw-bound.
    #[test]
    fn validator_containment_bwrap_masks_source_tree_and_keeps_carveouts() {
        let (_dir, root, snapshot, mission) = validator_containment_fixture();
        let scratch = tempfile::tempdir().unwrap();
        let args = bubblewrap_args(
            &validator_containment_inputs(&root, &snapshot, &mission, scratch.path()),
            Path::new("/usr/bin/claude"),
            &[],
        )
        .unwrap();
        let joined = args.join(" ");

        let src = absolutize(&root.join("src")).display().to_string();
        assert!(
            args.windows(2).any(|w| w[0] == "--tmpfs" && w[1] == src),
            "missing tmpfs shadow for src/: {args:?}"
        );
        let env_file = absolutize(&root.join(".env")).display().to_string();
        assert!(
            joined.contains(&format!("--ro-bind /dev/null {env_file}")),
            "missing /dev/null mask for .env: {args:?}"
        );
        // The carve-outs are never masked, and the root itself is not
        // shadowed (bwrap cannot close the listing without hiding them).
        let git = absolutize(&root.join(".git")).display().to_string();
        assert!(
            !joined.contains(&git),
            ".git must not be masked (the inspection's git surface): {args:?}"
        );
        assert!(
            !args
                .windows(2)
                .any(|w| w[0] == "--tmpfs" && w[1] == root.display().to_string()),
            "the root itself must not be shadowed: {args:?}"
        );
        // The snapshot stays rw-bound.
        let snap = absolutize(&snapshot).display().to_string();
        assert!(
            joined.contains(&format!("--bind {snap} {snap}")),
            "the snapshot must stay rw-bound: {args:?}"
        );
    }

    /// The bwrap analogue of the 14th-pass over-read fix (ticket
    /// `validator-containment-kranz-overread`): the plaintext lint
    /// vocabulary gets a `/dev/null` mask, and the hook-status projection +
    /// the control inbox get tmpfs shadows (the control/ shadow was already
    /// the write-deny idiom; the same mechanism now hides hook-status/).
    #[test]
    fn validator_containment_bwrap_masks_sensitive_kranz_runtime() {
        let (_dir, root, snapshot, mission) = validator_containment_fixture();
        let scratch = tempfile::tempdir().unwrap();
        let args = bubblewrap_args(
            &validator_containment_inputs(&root, &snapshot, &mission, scratch.path()),
            Path::new("/usr/bin/claude"),
            &[],
        )
        .unwrap();
        let joined = args.join(" ");

        let kranz = absolutize(&root.join(".kranz")).display().to_string();
        assert!(
            joined.contains(&format!("--tmpfs {kranz}")) && !joined.contains("domain-terms.local"),
            "the private authority directory must exclude domain-terms.local: {args:?}"
        );
        for dir in [
            root.join(".kranz").join("hook-status"),
            mission.join("control"),
        ] {
            let shadow = absolutize(dir.parent().unwrap()).display().to_string();
            assert!(args.windows(2).any(|w| w[0] == "--tmpfs" && w[1] == shadow));
            let denied = absolutize(&dir).display().to_string();
            assert!(
                !args.windows(3).any(|part| {
                    matches!(part[0].as_str(), "--ro-bind" | "--ro-bind-try")
                        && part[1] == denied
                        && part[2] == denied
                }),
                "denied directory must not be rebound: {args:?}"
            );
        }
    }

    // --- the resolution matrix -----------------------------------------------

    fn off_cfg() -> crate::types::SandboxConfig {
        crate::types::SandboxConfig::default()
    }

    fn fs_cfg() -> crate::types::SandboxConfig {
        crate::types::SandboxConfig {
            enforce: crate::types::SandboxEnforce::Fs,
            ..crate::types::SandboxConfig::default()
        }
    }

    /// The case the ticket exists for: `enforce: off` (the default) STILL
    /// wraps the validator on macOS — the mandatory fs-tier wrap with the
    /// real checkout read-denied and NO operator extraWrite widening.
    #[test]
    fn validator_containment_off_macos_wraps_mandatory_seatbelt() {
        let mut cfg = off_cfg();
        cfg.extra_write = vec!["~/elsewhere".to_string()];
        let roots = vec![PathBuf::from("/repo")];
        let containment = resolve_validator_containment_target(
            &cfg,
            crate::types::BackendKind::Claude,
            Path::new("/repo/.kranz/missions/m-x/runs/snap"),
            Path::new("/repo/.kranz/missions/m-x"),
            &roots,
            false,
            "macos",
            false,
            None,
            None,
        )
        .expect("off+macos resolves the mandatory wrap");
        assert!(containment.note.is_none(), "{:?}", containment.note);
        let sandbox = containment.sandbox.expect("a wrap applies");
        assert_eq!(sandbox.backend, SandboxBackend::Seatbelt);
        assert_eq!(
            sandbox.inputs.enforce,
            crate::types::SandboxEnforce::Fs,
            "the mandatory wrap is the fs tier (egress stays open for the API)"
        );
        assert_eq!(sandbox.inputs.validator_read_deny_roots, roots);
        assert!(
            sandbox.inputs.extra_write.is_empty(),
            "no operator extraWrite widening under the mandatory wrap"
        );
        assert_eq!(
            sandbox.inputs.session_cwd,
            PathBuf::from("/repo/.kranz/missions/m-x/runs/snap"),
            "the snapshot is the writable root"
        );
    }

    /// Linux: the mandatory wrap needs `bwrap`; without it the resolution
    /// FAILS CLOSED by default (naming the platform limit and the flag), and
    /// only the explicit `validatorAllowUncontainedDegrade` opt-in restores
    /// the loud degrade note (ticket
    /// validator-containment-degrade-fail-closed).
    #[test]
    fn validator_containment_off_linux_without_bwrap_fails_closed_unless_opted_in() {
        let roots = vec![PathBuf::from("/repo")];
        let err = resolve_validator_containment_target(
            &off_cfg(),
            crate::types::BackendKind::Claude,
            Path::new("/snap"),
            Path::new("/mission"),
            &roots,
            false,
            "linux",
            false,
            None,
            None,
        )
        .expect_err("no bwrap and no opt-in: fail closed");
        let err = err.to_string();
        assert!(err.contains("bwrap"), "{err}");
        assert!(err.contains("validatorAllowUncontainedDegrade"), "{err}");
        assert!(
            err.contains("refusing to run an uncontained validator"),
            "{err}"
        );

        let containment = resolve_validator_containment_target(
            &off_cfg(),
            crate::types::BackendKind::Claude,
            Path::new("/snap"),
            Path::new("/mission"),
            &roots,
            true,
            "linux",
            false,
            None,
            None,
        )
        .expect("the opt-in restores the loud degrade");
        assert!(containment.sandbox.is_none());
        let note = containment.note.expect("the loud note");
        assert!(note.contains("bwrap"), "{note}");
        assert!(note.contains("validator-mandatory-containment"), "{note}");

        let containment = resolve_validator_containment_target(
            &off_cfg(),
            crate::types::BackendKind::Claude,
            Path::new("/snap"),
            Path::new("/mission"),
            &roots,
            false,
            "linux",
            true,
            None,
            None,
        )
        .expect("off+linux+bwrap resolves");
        assert!(containment.note.is_none(), "{:?}", containment.note);
        assert_eq!(
            containment.sandbox.expect("a wrap applies").backend,
            SandboxBackend::Bubblewrap
        );
    }

    /// M7 Windows parity, phase 4: validators resolve the same mandatory
    /// AppContainer fs-tier wrap as other containable platforms, regardless
    /// of the legacy uncontained-degrade opt-in.
    #[test]
    fn validator_containment_off_windows_resolves_appcontainer() {
        let roots = vec![PathBuf::from("C:\\repo")];
        for allow_uncontained_degrade in [false, true] {
            let containment = resolve_validator_containment_target(
                &off_cfg(),
                crate::types::BackendKind::Claude,
                Path::new("C:\\snap"),
                Path::new("C:\\mission"),
                &roots,
                allow_uncontained_degrade,
                "windows",
                false,
                None,
                None,
            )
            .expect("Windows resolves the mandatory AppContainer wrap");
            assert!(containment.note.is_none(), "{:?}", containment.note);
            let sandbox = containment.sandbox.expect("a wrap applies");
            assert_eq!(sandbox.backend, SandboxBackend::AppContainer);
            assert_eq!(sandbox.inputs.enforce, crate::types::SandboxEnforce::Fs);
            assert_eq!(sandbox.inputs.session_cwd, PathBuf::from("C:\\snap"));
            assert_eq!(sandbox.inputs.validator_read_deny_roots, roots);
            assert!(sandbox.inputs.extra_write.is_empty());
        }
    }

    /// A backend that cannot honor the resolved sandbox must never silently
    /// run bare: by default the resolution FAILS CLOSED naming the backend
    /// and the flag; with the opt-in the wrap is skipped and the note names
    /// the backend.
    #[test]
    fn validator_containment_off_non_claude_backend_fails_closed_unless_opted_in() {
        for backend in [
            crate::types::BackendKind::Codex,
            crate::types::BackendKind::Droid,
            crate::types::BackendKind::Kimi,
            crate::types::BackendKind::Local,
            crate::types::BackendKind::Acp,
            crate::types::BackendKind::Cursor,
        ] {
            let err = resolve_validator_containment_target(
                &off_cfg(),
                backend,
                Path::new("/snap"),
                Path::new("/mission"),
                &[PathBuf::from("/repo")],
                false,
                "macos",
                false,
                None,
                None,
            )
            .expect_err("an uncontainable backend fails closed by default");
            let err = err.to_string();
            assert!(err.contains(backend.as_str()), "{err}");
            assert!(err.contains("validatorAllowUncontainedDegrade"), "{err}");

            let containment = resolve_validator_containment_target(
                &off_cfg(),
                backend,
                Path::new("/snap"),
                Path::new("/mission"),
                &[PathBuf::from("/repo")],
                true,
                "macos",
                false,
                None,
                None,
            )
            .expect("the opt-in restores the loud degrade");
            assert!(
                containment.sandbox.is_none(),
                "{backend:?} must not get a wrap it cannot honor"
            );
            let note = containment.note.expect("the loud note");
            assert!(note.contains(backend.as_str()), "{note}");
            assert!(note.contains("validator-mandatory-containment"), "{note}");
        }
    }

    /// `enforce != off` keeps the role's own resolution AND gains the
    /// read-deny roots on the process tier; the operator's extraWrite stays
    /// (the mandatory no-widening rule is the off-case wrap's).
    #[test]
    fn validator_containment_enforced_role_resolves_and_attaches_roots() {
        let mut cfg = fs_cfg();
        cfg.extra_write = vec!["~/keep".to_string()];
        let roots = vec![PathBuf::from("/repo")];
        let containment = resolve_validator_containment_target(
            &cfg,
            crate::types::BackendKind::Claude,
            Path::new("/repo/.kranz/missions/m-x/runs/snap"),
            Path::new("/repo/.kranz/missions/m-x"),
            &roots,
            false,
            "macos",
            false,
            None,
            None,
        )
        .expect("fs on macos resolves");
        assert!(containment.note.is_none(), "{:?}", containment.note);
        let sandbox = containment.sandbox.expect("the role's wrap");
        assert_eq!(sandbox.backend, SandboxBackend::Seatbelt);
        assert_eq!(sandbox.inputs.validator_read_deny_roots, roots);
        assert!(
            !sandbox.inputs.extra_write.is_empty(),
            "an enforced role keeps its declared extraWrite"
        );
    }

    /// `enforce != off` stays fail-closed on an unknown platform (the
    /// runner's resolve_sandbox_or_refuse posture, unchanged).
    #[test]
    fn validator_containment_enforced_role_still_fails_closed_where_unsupported() {
        let err = resolve_validator_containment_target(
            &fs_cfg(),
            crate::types::BackendKind::Claude,
            Path::new("/snap"),
            Path::new("/mission"),
            &[PathBuf::from("/repo")],
            false,
            "solaris",
            false,
            None,
            None,
        )
        .expect_err("enforcement requested but unhonorable must fail closed");
        assert!(err.to_string().contains("unsupported"), "{err}");
    }

    /// The container provider keeps its own (stronger) containment: resolved
    /// untouched, no read-deny roots attached (the real tree is simply not
    /// mounted). Under `enforce: off` the provider is ignored — the
    /// mandatory wrap is the process tier.
    #[test]
    fn validator_containment_container_provider_posture() {
        let cfg = crate::types::SandboxConfig {
            enforce: crate::types::SandboxEnforce::Fs,
            provider: crate::types::SandboxProvider::Container,
            ..crate::types::SandboxConfig::default()
        };
        let containment = resolve_validator_containment_target(
            &cfg,
            crate::types::BackendKind::Claude,
            Path::new("/snap"),
            Path::new("/mission"),
            &[PathBuf::from("/repo")],
            false,
            "linux",
            false,
            Some(crate::sandbox_container::ContainerRuntime::Docker),
            None,
        )
        .expect("container resolves with a runtime");
        let sandbox = containment.sandbox.expect("the container wrap");
        assert_eq!(sandbox.backend, SandboxBackend::Container);
        assert!(
            sandbox.inputs.validator_read_deny_roots.is_empty(),
            "the container's mounts are the containment — no process-tier deny set"
        );

        let mut off_container = off_cfg();
        off_container.provider = crate::types::SandboxProvider::Container;
        let containment = resolve_validator_containment_target(
            &off_container,
            crate::types::BackendKind::Claude,
            Path::new("/snap"),
            Path::new("/mission"),
            &[PathBuf::from("/repo")],
            false,
            "macos",
            false,
            None,
            None,
        )
        .expect("off+container still gets the mandatory process-tier wrap");
        assert_eq!(
            containment.sandbox.expect("a wrap applies").backend,
            SandboxBackend::Seatbelt,
            "provider:container with enforce:off documents 'no sandboxing'; the mandatory wrap is process-tier"
        );
    }

    /// Applied proof on macOS (the ticket's test gate): a validator-session
    /// fixture under `enforce: off`-shape inputs provably CANNOT read the
    /// real checkout's source tree or the authority material, while the
    /// shared git dir and the snapshot stay readable.
    #[cfg(target_os = "macos")]
    #[test]
    fn validator_containment_macos_denies_real_checkout_reads() {
        use std::process::Command;

        let _guard = SANDBOX_EXEC_TEST_LOCK.lock().unwrap();
        if !sandbox_exec_can_apply() {
            return;
        }
        let (_dir, root, snapshot, mission) = validator_containment_fixture();
        let scratch = tempfile::tempdir().unwrap();
        let profile = generate_profile(&validator_containment_inputs(
            &root,
            &snapshot,
            &mission,
            scratch.path(),
        ));
        let profile_dir = tempfile::tempdir().unwrap();
        let profile_path = write_profile_file(profile_dir.path(), &profile).unwrap();

        let read = |path: &Path| {
            Command::new("sandbox-exec")
                .arg("-f")
                .arg(&profile_path)
                .arg("/bin/cat")
                .arg(path)
                .status()
                .expect("failed to run sandbox-exec")
        };
        // The real checkout's source tree is unreadable…
        for denied in [
            root.join("src").join("secret.rs"),
            root.join("Cargo.toml"),
            root.join(".env"),
        ] {
            assert!(
                !read(&denied).success(),
                "read of the real tree must be denied: {}",
                denied.display()
            );
        }
        // …and so is the sensitive .kranz runtime the carve-out would
        // otherwise reopen (14th-pass review,
        // validator-containment-kranz-overread): the plaintext lint
        // vocabulary, the hook-status projection, and the control inbox.
        for denied in [
            root.join(".kranz").join("domain-terms.local"),
            root.join(".kranz")
                .join("hook-status")
                .join("m-x")
                .join("run-1.json"),
            mission.join("control").join("approve.json"),
        ] {
            assert!(
                !read(&denied).success(),
                "read of the sensitive .kranz runtime must be denied: {}",
                denied.display()
            );
        }
        // …the root LISTING stays visible (names, never contents — a
        // literal deny on the root breaks coreutils `mkdir -p`, which stats
        // every ancestor; documented on the entries helper)…
        let listing = Command::new("sandbox-exec")
            .arg("-f")
            .arg(&profile_path)
            .arg("/bin/ls")
            .arg(&root)
            .status()
            .expect("failed to run sandbox-exec");
        assert!(
            listing.success(),
            "the root listing stays open (names, never contents)"
        );
        // …and the authority material stays denied through the carve-out.
        assert!(
            !read(&root.join(".kranz").join("serve.token")).success(),
            "the authority read deny must survive the .kranz carve-out"
        );
        // The narrow legitimate surfaces stay readable: the shared git dir
        // and the validator's own snapshot worktree.
        for allowed in [root.join(".git").join("HEAD"), snapshot.join("README.md")] {
            assert!(
                read(&allowed).success(),
                "read must keep working: {}",
                allowed.display()
            );
        }
    }

    /// The second applied half: writes outside the snapshot are denied
    /// (source tree, mission metadata, and the shared git refs — the
    /// tripwire's domain, now hard-denied), while the snapshot stays
    /// writable and read-only git (`log`/`status`/`diff` — the inspection's
    /// surface) keeps working: the validation round still completes.
    #[cfg(target_os = "macos")]
    #[test]
    fn validator_containment_macos_keeps_snapshot_writes_and_readonly_git() {
        use std::process::Command;

        let _guard = SANDBOX_EXEC_TEST_LOCK.lock().unwrap();
        if !sandbox_exec_can_apply() {
            return;
        }
        let Some((_dir, root, snapshot, mission)) = validator_containment_git_fixture() else {
            return;
        };
        let scratch = tempfile::tempdir().unwrap();
        let profile = generate_profile(&validator_containment_inputs(
            &root,
            &snapshot,
            &mission,
            scratch.path(),
        ));
        let profile_dir = tempfile::tempdir().unwrap();
        let profile_path = write_profile_file(profile_dir.path(), &profile).unwrap();
        let sh = |command: &str| {
            Command::new("sandbox-exec")
                .arg("-f")
                .arg(&profile_path)
                .arg("/bin/sh")
                .arg("-c")
                .arg(command)
                .status()
                .expect("failed to run sandbox-exec")
        };

        // Write denies: the real tree, the root, the engine's metadata, and
        // the shared git plumbing (index + refs).
        for command in [
            format!("echo x >> {}", root.join("tracked.rs").display()),
            format!("echo x > {}", root.join("new.txt").display()),
            format!("echo x >> {}", mission.join("events.jsonl").display()),
            format!("git -C {} add -A", snapshot.display()),
            format!("git -C {} branch -f side HEAD", snapshot.display()),
        ] {
            assert!(!sh(&command).success(), "must be denied: {command}");
        }
        // The snapshot stays fully writable (the warmed-target shape)…
        assert!(sh(&format!(
            "mkdir -p {0}/target && echo built > {0}/target/out && echo note > {0}/notes.txt",
            snapshot.display()
        ))
        .success());
        // …and the read-only git inspection surface works — the functional
        // and scrutiny validators' whole job in the snapshot.
        let git_log = Command::new("sandbox-exec")
            .arg("-f")
            .arg(&profile_path)
            .arg("git")
            .arg("-C")
            .arg(&snapshot)
            .arg("log")
            .arg("--oneline")
            .output()
            .expect("failed to run sandbox-exec");
        assert!(
            git_log.status.success(),
            "read-only git must work in the snapshot: {}",
            String::from_utf8_lossy(&git_log.stderr)
        );
        assert!(String::from_utf8_lossy(&git_log.stdout).contains("init"));
        assert!(sh(&format!("git -C {} status --porcelain", snapshot.display())).success());
        assert!(sh(&format!("git -C {} diff HEAD", snapshot.display())).success());
        // The snapshot's own copy of the source tree reads fine.
        assert!(sh(&format!("cat {}", snapshot.join("tracked.rs").display())).success());
    }

    /// The linux applied analogue: bwrap masks the real tree (dirs ENOENT
    /// under the tmpfs shadow, files empty under /dev/null), keeps the
    /// carve-outs and the snapshot, and read-only git still works.
    #[cfg(target_os = "linux")]
    #[test]
    fn validator_containment_linux_bwrap_denies_real_checkout_and_keeps_snapshot() {
        use std::process::Command;

        if !bwrap_can_apply() {
            return;
        }
        let Some((dir, root, snapshot, mission)) = validator_containment_git_fixture() else {
            return;
        };
        // An absent global authority directory makes its HOME the enclosing
        // private view. Restoring the repo under that view must not reopen
        // the validator's real-checkout read denies.
        let _env =
            crate::agent_env::EnvTestGuard::engage(&[("HOME", dir.path().to_str().unwrap())]);
        let scratch = tempfile::tempdir().unwrap();
        let inputs = validator_containment_inputs(&root, &snapshot, &mission, scratch.path());
        let run = |command: &str| {
            Command::new("bwrap")
                .args(
                    bubblewrap_args(
                        &inputs,
                        Path::new("/bin/sh"),
                        &["-c".to_string(), command.to_string()],
                    )
                    .unwrap(),
                )
                .output()
                .expect("failed to run bwrap")
        };

        // A source DIR is shadowed: reads underneath fail outright.
        let shadowed = run(&format!(
            "cat {}",
            root.join("src").join("secret.rs").display()
        ));
        assert!(
            !shadowed.status.success(),
            "the tmpfs-shadowed source dir must not resolve: {}",
            String::from_utf8_lossy(&shadowed.stderr)
        );
        // A source FILE is /dev/null-masked: the open succeeds, the content
        // does not cross (the authority-mask idiom).
        let masked = run(&format!("cat {}", root.join("tracked.rs").display()));
        assert!(
            !String::from_utf8_lossy(&masked.stdout).contains("tracked"),
            "the masked source file must not yield its content"
        );
        // The authority material is masked too.
        let authority_read = run(&format!(
            "cat {}",
            root.join(".kranz").join("serve.token").display()
        ));
        assert!(
            !String::from_utf8_lossy(&authority_read.stdout).contains("secret-token"),
            "the authority material must stay masked"
        );
        // The carve-outs and the snapshot read fine.
        let git_head = run(&format!("cat {}", root.join(".git").join("HEAD").display()));
        assert!(git_head.status.success());
        let snap_read = run(&format!("cat {}", snapshot.join("tracked.rs").display()));
        assert!(
            String::from_utf8_lossy(&snap_read.stdout).contains("tracked"),
            "the snapshot's own copy reads fine"
        );
        // Writes outside the snapshot fail (the whole fs is ro-bound); the
        // snapshot and the git plumbing behave like the Seatbelt side.
        for command in [
            format!("echo x >> {}", root.join("tracked.rs").display()),
            format!("echo x >> {}", mission.join("events.jsonl").display()),
            format!("git -C {} branch -f side HEAD", snapshot.display()),
        ] {
            assert!(!run(&command).status.success(), "must be denied: {command}");
        }
        assert!(
            run(&format!("echo built > {}/target-out", snapshot.display()))
                .status
                .success()
        );
        let git_log = run(&format!("git -C {} log --oneline", snapshot.display()));
        assert!(
            git_log.status.success(),
            "read-only git must work in the snapshot: {}",
            String::from_utf8_lossy(&git_log.stderr)
        );
    }
}

#[cfg(test)]
#[path = "git_config_protection_tests.rs"]
mod git_config_protection_tests;