capsule-runtime 0.3.0

The runtime that executes Murmur capsules. Runs packaged AI agents in isolation, enforcing WASI capability grants on a Wasmtime component sandbox.
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
//! Containment classes: what an operator *declares* versus what a host actually *achieves*.
//!
//! The two directions are deliberately kept apart:
//!
//! * The **declared floor** ([`murmur_artifact::ContainmentClass`]) is a requirement, combined
//!   from the manifest, the workspace config and `--containment` by taking the strongest (see
//!   [`murmur_artifact::effective_containment_floor`]).
//! * The **achieved class** starts from [`EnforcementTier`], which is host-probed at launch time.
//!   [`achieved_class_for_tier`] takes nothing else — not the manifest, not the grant set — so no
//!   declaration can ever talk a host into reporting a class it cannot back. Exactly one manifest
//!   property may then talk a *capsule* down from that ceiling, and only downwards:
//!   `capabilities.filesystem.workdir_exec: true` caps the result at
//!   [`ContainmentClass::Advisory`] (see [`achieved_containment_class`]), because a capsule whose
//!   own workdir is executable has given up the claim `scoped` makes. The cap is applied in a
//!   separate wrapper rather than inside [`achieved_class_for_tier`] precisely so the "no
//!   declaration raises a class" property stays a property of one small, pure function.
//!
//! [`ContainmentClass::Sealed`] is reachable exactly when [`EnforcementTier::KernelSealed`] is:
//! a Linux host with a usable Landlock ABI, AppArmor out of the way of unprivileged user
//! namespaces, and a namespace probe that really created one. See [`crate::sealed`] for the
//! mechanism and for the [`SealedBlocker`] taxonomy that turns "not sealed here" into a specific
//! command an operator can run.
//!
//! The shortfall reason for `sealed` is therefore *mechanism-specific*, not a fixed string: a
//! host missing the AppArmor profile and a container missing `CAP_SYS_ADMIN` both fail to reach
//! `sealed`, but they are fixed in completely different places, and a refusal that cannot tell
//! them apart is a refusal an operator cannot act on.

use murmur_artifact::{ContainmentClass, ExportMode, Exports, FileExport, PeerFilesExport};
use serde::Serialize;

use crate::{
    cgroup::{IoMaxReport, IoMaxStatus},
    errors::RuntimeError,
    sandbox::{detect_enforcement_tier, EnforcementTier},
    sealed::{SealedBlocker, UsernsGrant},
    types::CapabilityPolicy,
};

pub use crate::sandbox::{detect_sealed_blocker, detect_userns_grant};

/// The class a host in `tier` can actually back, and nothing stronger.
///
/// Pure — the host probe lives in [`detect_enforcement_tier`], mirroring the
/// `tier_from_probe`/`detect_enforcement_tier` split in `sandbox.rs` so this mapping stays
/// unit-testable on any OS.
pub(crate) fn achieved_class_for_tier(tier: EnforcementTier) -> ContainmentClass {
    match tier {
        // A private mount namespace pivoted onto a composed root: paths outside it are absent,
        // not merely denied — exactly the mechanism `sealed` names. Landlock and seccomp still
        // install inside it, so this arm is strictly stronger than `KernelFull`'s, never an
        // alternative to it.
        EnforcementTier::KernelSealed => ContainmentClass::Sealed,
        // Landlock mediates the filesystem and seccomp mediates exec/network: exactly the
        // mechanism `scoped` names.
        EnforcementTier::KernelFull => ContainmentClass::Scoped,
        // Seccomp alone leaves the filesystem scope convention-only, and `EnvironmentOnly` has
        // no kernel primitive at all. Neither can back a filesystem claim, so neither clears
        // `scoped`.
        EnforcementTier::KernelSeccompOnly | EnforcementTier::EnvironmentOnly => {
            ContainmentClass::Advisory
        }
    }
}

/// The class a session actually achieves: the host's ceiling from [`achieved_class_for_tier`],
/// capped by what the capsule's own `capabilities.filesystem.workdir_exec` leaves standing.
///
/// This is the one place a *manifest* property lowers an achieved class, and it does so by capping
/// rather than by deciding: [`achieved_class_for_tier`] above stays pure and tier-only, so no
/// declaration can talk a host up, and this wrapper can only ever talk a capsule *down*.
///
/// Why `workdir_exec` caps at [`ContainmentClass::Advisory`]: `scoped` (and `sealed` above it) both
/// claim that what runs inside the capsule is bounded by what the operator declared. With the
/// workdir's `Execute` right granted, a binary the agent compiles, downloads or renames inside its
/// own workdir runs whatever `capabilities.shell.allow` says — the allowlist stops being an
/// enforceable property. A host that could back `scoped` still cannot back a claim the capsule
/// itself has given up, so the honest report is `advisory`, on every tier.
pub(crate) fn achieved_containment_class(
    tier: EnforcementTier,
    workdir_exec: bool,
) -> ContainmentClass {
    let host_ceiling = achieved_class_for_tier(tier);
    if workdir_exec {
        host_ceiling.min(ContainmentClass::Advisory)
    } else {
        host_ceiling
    }
}

/// Probes this host and reports the strongest class it can actually provide.
///
/// Host-only, and deliberately still takes no capsule input: it answers "what can this machine
/// back?", which is what `mur doctor` and the escape-conformance harness ask. A *session* asks the
/// narrower question and must use [`achieved_containment_class`] with its own probed tier instead
/// — see `runtime::stage_session`, which probes the tier once and passes it to both that call and
/// [`scope_report_for_tier`].
pub fn detect_achieved_containment() -> ContainmentClass {
    achieved_class_for_tier(detect_enforcement_tier())
}

/// Why `achieved` falls short of `declared`, naming the missing *mechanism* rather than the
/// missing class. `None` when the floor is met.
///
/// Pure and host-independent: the caller supplies both classes *and* — for the `sealed` arm — the
/// already-probed [`SealedBlocker`], so this function still probes nothing and stays testable
/// without a kernel. `sealed_blocker` is `None` when the caller has not probed (or cannot: a
/// non-Linux host), in which case the arm falls back to naming the mechanism generically.
///
/// `workdir_exec` is the capsule's own `capabilities.filesystem.workdir_exec`. It is checked before
/// every host arm below, because it is the one shortfall an operator cannot fix by changing hosts:
/// no kernel backs `scoped` for a capsule that has declared its workdir executable. Naming a
/// missing Landlock ABI to someone whose real problem is a line in their own manifest sends them to
/// the wrong machine.
pub fn containment_shortfall_reason(
    declared: ContainmentClass,
    achieved: ContainmentClass,
    sealed_blocker: Option<SealedBlocker>,
    workdir_exec: bool,
) -> Option<String> {
    if achieved >= declared {
        return None;
    }

    if workdir_exec && declared > ContainmentClass::Advisory {
        return Some(WORKDIR_EXEC_SHORTFALL.to_string());
    }

    let reason = match declared {
        // Unreachable in practice — `Advisory` is the weakest class, so nothing is below it —
        // but stated rather than `unreachable!()` so a future variant reordering cannot panic
        // a launch path.
        ContainmentClass::Advisory => {
            "advisory is the weakest containment class and is satisfied by every host".to_string()
        }
        ContainmentClass::Scoped => {
            "scoped requires Landlock filesystem mediation (Linux 5.13+ with a usable Landlock \
             ABI); this host provides no kernel filesystem mediation, so paths outside the \
             workdir are constrained by convention only"
                .to_string()
        }
        // The mechanism exists now, so the reason names *which part of it* this host is missing
        // and how to fix that part — never the old blanket "no host can provide it today".
        ContainmentClass::Sealed => match sealed_blocker {
            Some(blocker) => blocker.reason(),
            None => "sealed requires a private mount namespace pivoted onto a composed root \
                     (unshare(CLONE_NEWUSER|CLONE_NEWNS) + pivot_root), which this host did not \
                     provide"
                .to_string(),
        },
    };

    Some(reason)
}

/// The reason a capsule that declared `capabilities.filesystem.workdir_exec: true` falls short of
/// any floor above `advisory`. Fixed text rather than a `match` arm per declared class: the
/// mechanism, the consequence and the remedy are identical for `scoped` and `sealed`, because both
/// rest on the claim this declaration gives up.
const WORKDIR_EXEC_SHORTFALL: &str =
    "capabilities.filesystem.workdir_exec: true keeps the Landlock Execute right on the session \
     workdir, so a binary the capsule compiles, downloads or renames inside it runs regardless of \
     capabilities.shell.allow — the allowlist stops being an enforceable property of this capsule. \
     No host can back a class above advisory for it. Either remove workdir_exec (the allowlist is \
     then enforced by the kernel on the resolved path) or lower the declared containment floor to \
     advisory";

/// The refusal gate: `Ok(())` when the host's `achieved` class meets or exceeds the `declared`
/// floor, [`RuntimeError::ContainmentFloorUnmet`] otherwise.
///
/// Pure — takes every input as an argument and probes nothing, so the whole decision is
/// testable without a kernel.
pub fn check_containment_floor(
    declared: ContainmentClass,
    achieved: ContainmentClass,
    sealed_blocker: Option<SealedBlocker>,
    workdir_exec: bool,
) -> Result<(), RuntimeError> {
    match containment_shortfall_reason(declared, achieved, sealed_blocker, workdir_exec) {
        None => Ok(()),
        Some(reason) => Err(RuntimeError::ContainmentFloorUnmet {
            declared,
            achieved,
            reason,
        }),
    }
}

/// The declared `exports.files` block as it appears in a [`ScopeReport`] — and therefore in
/// `mur run --explain-scope --json` and in `trace.jsonl`'s `session_start.effective_grants`.
///
/// A flattened copy rather than [`FileExport`] itself: this is a wire shape with a stable field
/// order and a `mode` that serializes as `"read-only"`, and it must not move whenever the
/// manifest type gains a field the report has no business publishing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ExportsFilesReport {
    /// `exports.files.root` verbatim, as declared.
    pub root: String,
    pub mode: ExportMode,
    /// The effective per-file read ceiling, with the default already applied.
    pub max_bytes: u64,
}

impl From<&FileExport> for ExportsFilesReport {
    fn from(export: &FileExport) -> Self {
        Self {
            root: export.root.clone(),
            mode: export.mode,
            max_bytes: export.max_bytes,
        }
    }
}

/// The declared `exports.peer_files` block as it appears in a [`ScopeReport`].
///
/// A flattened copy rather than [`PeerFilesExport`] itself, on the same terms as
/// [`ExportsFilesReport`]: a wire shape with a stable field order, which must not move whenever
/// the manifest type gains a field the report has no business publishing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PeerFilesReport {
    /// `exports.peer_files.root` verbatim, as declared.
    pub root: String,
    /// The effective handle-lifetime ceiling in seconds, with the ephemeral default already
    /// applied — so an operator reads the value the runtime will actually clamp to, not the
    /// absence of a declaration.
    pub max_ttl_secs: u64,
    /// The effective per-file ceiling on a redeemed read, with the default already applied.
    pub max_bytes: u64,
}

impl From<&PeerFilesExport> for PeerFilesReport {
    fn from(export: &PeerFilesExport) -> Self {
        Self {
            root: export.root.clone(),
            max_ttl_secs: export.effective_max_ttl_secs(),
            max_bytes: export.max_bytes,
        }
    }
}

/// One artifact's durable state grant as it appears in a [`ScopeReport`].
///
/// A grant rather than a disclosure, unlike [`ExportsFilesReport`] beside it — but reported on
/// exactly the same terms, and for the same reason: it opens a host path outside the workdir that
/// an operator reading `filesystem scope` alone would never see.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StateStoreReport {
    /// The artifact whose entry declared `capabilities.state`.
    pub artifact: String,
    /// The store directory name, with the capsule-name default already applied — so an operator
    /// reads the directory that will actually be opened, not the absence of a declaration.
    pub store: String,
    /// Absolute host path of the store, `~/.murmur/state/<store>` with the home already resolved.
    /// Reported as a string rather than a path so the JSON shape does not vary by platform.
    pub host_path: String,
}

/// The filesystem surface one artifact's guest is preopened into, as a stable wire name.
///
/// The three values are the whole space: a WASI guest either holds a directory descriptor for the
/// accessible workdir, holds one for a subtree of it, or holds none at all. Which one an entry
/// resolves to is decided by its role and its `capabilities.filesystem.scope` in
/// [`crate::network_policy::preopen_reports`]; the baselines the two roles start from are
/// [`crate::network_policy::ToolCapabilityGrant`] and
/// [`crate::network_policy::HookCapabilityGrant`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum PreopenSurface {
    /// The entire accessible workdir, preopened as `"."` with `DirPerms::all()` and
    /// `FilePerms::all()`. The wide default a `runtime: tool` or `runtime: driver` entry with no
    /// `capabilities.filesystem.scope` resolves to — see
    /// [`crate::network_policy::ToolCapabilityGrant`] for the threat that default is chosen
    /// against and the threat it is not.
    WholeWorkdir,
    /// `<accessible workdir>/<scope>` and nothing above it, preopened as `"."` with the same
    /// rights. What a declared `capabilities.filesystem.scope` resolves to, whatever the role.
    ScopedSubtree,
    /// No preopened directory of any kind, so the guest holds no `wasi:filesystem` descriptor. The
    /// default-deny baseline a `runtime: hook` entry with no `capabilities.filesystem.scope`
    /// resolves to — see [`crate::network_policy::HookCapabilityGrant`].
    Nothing,
}

impl PreopenSurface {
    /// The phrase [`PreopenReport::render`] names this surface with. Distinct per variant rather
    /// than a formatted path, because the point of the line is that an operator can tell the three
    /// apart without knowing the resolved workdir.
    fn summary(self) -> &'static str {
        match self {
            PreopenSurface::WholeWorkdir => "the whole accessible workdir",
            PreopenSurface::ScopedSubtree => "one subtree of the accessible workdir",
            PreopenSurface::Nothing => "nothing preopened",
        }
    }
}

/// One artifact's resolved WASI preopen as it appears in a [`ScopeReport`] — and therefore in
/// `mur run --explain-scope`, in `mur doctor`, and in `trace.jsonl`'s
/// `session_start.effective_grants`.
///
/// Per-artifact, like [`StateStoreReport`] beside it, and reported for the same reason: the
/// capsule-wide [`ScopeReport::filesystem_scope`] is joined into no guest preopen root, so an
/// operator reading that field alone learns nothing about what any tool, driver or hook can
/// actually see.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PreopenReport {
    /// The artifact whose entry in the capsule operator's own manifest this describes.
    pub artifact: String,
    /// [`murmur_artifact::ArtifactRuntime::as_str`] verbatim, so the report and the manifest name
    /// a role with one vocabulary.
    pub role: String,
    /// The entry's declared `capabilities.filesystem.scope`, verbatim. `None` = undeclared, which
    /// is what [`Self::surface`] has already resolved against the role's own baseline.
    pub scope: Option<String>,
    /// What the guest is preopened into once the role's baseline and [`Self::scope`] are both
    /// applied.
    pub surface: PreopenSurface,
}

impl PreopenReport {
    /// The single line this preopen renders as, shared by [`ScopeReport::render`] and by
    /// `mur doctor` so the two cannot word the same grant differently.
    pub fn render(&self) -> String {
        let artifact = &self.artifact;
        let role = &self.role;
        let surface = self.surface.summary();
        match &self.scope {
            Some(scope) => {
                format!("{artifact} ({role}): {surface} — capabilities.filesystem.scope: {scope}")
            }
            None => format!(
                "{artifact} ({role}): {surface} — no capabilities.filesystem.scope declared"
            ),
        }
    }
}

/// What the filesystem mechanism this session installs restricts, as a stable wire name.
///
/// Keyed on [`crate::sandbox::applied_tier`] — the host tier capped by the declared containment
/// floor, which is the same value [`crate::sandbox::ShellEnforcement::resolve`] installs the
/// session's mechanisms from. The achieved containment class answers a different question ("what
/// can this host back"), and a capsule declaring less than `sealed` on a sealed-capable host is
/// where the two part company: it is reported `achieved: sealed` and runs Landlock-scoped.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum FilesystemRestriction {
    /// No kernel mechanism mediates the filesystem, so a path outside the workdir is reachable.
    Advisory,
    /// Landlock refuses the open, and the path outside the granted set still exists.
    Enforced,
    /// A composed root, where the path outside the capsule is not there to open.
    Absent,
}

/// What the filesystem mechanism this session installs does *not* protect, in words an operator
/// can act on.
///
/// The counterpart to every grant beside it in a [`ScopeReport`]: those say what the capsule may
/// reach, and this says which of the restrictions an operator would read into them are not there.
///
/// [`Self::not_protected`] is empty at [`FilesystemRestriction::Absent`] and non-empty below it. It
/// is serialized either way — an absent key identifies a runtime that predates the field, never a
/// capsule with nothing to disclaim.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FilesystemBoundaryReport {
    /// What the session's filesystem mechanism restricts.
    pub restriction: FilesystemRestriction,
    /// One statement per protection an operator would otherwise assume, empty at
    /// [`FilesystemRestriction::Absent`]. Rendered verbatim under `Not protected here`, so the JSON
    /// and the human report cannot word the same disclaimer differently.
    pub not_protected: Vec<String>,
}

/// What a session with no kernel filesystem mechanism leaves unrestricted.
///
/// Names the mechanism rather than the class, because "advisory" is the word an operator has
/// already read on the `achieved:` line and taken for a protection.
const ADVISORY_FILESYSTEM_NOT_PROTECTED: &str =
    "Filesystem restriction is advisory on this host: no kernel mechanism denies a read or a write \
     outside the session workdir, so capabilities.filesystem.scope bounds what the runtime hands a \
     subprocess rather than what that subprocess can reach. A Linux host with a usable Landlock \
     ABI installs a Landlock domain instead, where the kernel refuses the open.";

/// What a Landlock-scoped session leaves unrestricted.
///
/// Not the `advisory` sentence: Landlock really does mediate the filesystem here, and an operator
/// told otherwise goes and hardens something the kernel already holds. What Landlock does not do is
/// make a path absent — it mediates the operations that touch a file, not path resolution.
const ENFORCED_FILESYSTEM_NOT_PROTECTED: &str =
    "A path outside the granted set is denied rather than absent: Landlock refuses the open, and \
     stat, access and readlink on that path still succeed and still report the real file's \
     metadata, because Landlock mediates the operations that touch a file and not path resolution. \
     A probe that only asks whether a path exists therefore learns nothing about what was denied — \
     read the file to see the refusal. Declaring capabilities.containment: sealed on a host that \
     reaches the sealed tier composes a root the path is not in at all.";

/// What no mechanism protects, and the reason `--explain-scope` carries this block at all.
///
/// Identical wherever it prints, because the rewrite it describes is identical: `HOME` is replaced
/// with the session's synthetic home on every tier and every platform (see `crate::shell`), so the
/// obvious `~`-based containment probe answers *no such file* on a host that denies nothing.
const PATH_REWRITING_NOT_PROTECTED: &str =
    "Path rewriting is a convenience, not a boundary: HOME is set to <workdir>/.capsule-home on \
     every tier, so `cat ~/.ssh/id_rsa` answers \"No such file or directory\" whether or not \
     anything was denied — the tilde resolved into the workdir and the host file was never looked \
     for. A ~-based probe is therefore never evidence of containment; test with an absolute path \
     to a real file outside the workdir instead.";

/// The filesystem boundary the tier a session applies actually provides, and the protections it
/// does not.
///
/// Pure and derived from the applied tier alone, so `--explain-scope` and
/// `session_start.effective_grants` cannot word the same disclaimer differently: both go through
/// [`scope_report_for_tier`], which calls this once with the tier it has already resolved.
///
/// The argument is the *applied* tier, never the host tier and never the achieved class. A composed
/// root is what makes a host path absent, and a session composes one only when the host reaches
/// `KernelSealed` **and** the capsule declared a `sealed` floor; a Landlock domain is installed
/// whenever the applied tier is `KernelFull` or `KernelSealed`, including for a capsule whose
/// `capabilities.filesystem.workdir_exec` caps its achieved class at `advisory`.
pub(crate) fn filesystem_boundary(applied: EnforcementTier) -> FilesystemBoundaryReport {
    // The path-rewriting statement rides along with the mechanism-specific one rather than standing
    // on its own, so a composed root — where the paths outside it are absent, and the `~` rewrite
    // lands inside the only writable path in that root — discloses nothing at all.
    let (restriction, filesystem) = match applied {
        EnforcementTier::KernelSealed => (FilesystemRestriction::Absent, None),
        EnforcementTier::KernelFull => (
            FilesystemRestriction::Enforced,
            Some(ENFORCED_FILESYSTEM_NOT_PROTECTED),
        ),
        EnforcementTier::KernelSeccompOnly | EnforcementTier::EnvironmentOnly => (
            FilesystemRestriction::Advisory,
            Some(ADVISORY_FILESYSTEM_NOT_PROTECTED),
        ),
    };

    let not_protected = match filesystem {
        Some(filesystem) => vec![
            filesystem.to_string(),
            PATH_REWRITING_NOT_PROTECTED.to_string(),
        ],
        None => Vec::new(),
    };

    FilesystemBoundaryReport {
        restriction,
        not_protected,
    }
}

/// Read-only answer to "what would this capsule actually be allowed to do on this host?".
///
/// Built from the already-parsed [`CapabilityPolicy`] plus one host tier probe. Nothing here
/// stages artifacts, touches a registry, creates a workdir or resolves DNS — it is a diagnostic,
/// so it reports even when [`Self::floor_met`] is `false`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ScopeReport {
    /// Strongest class any source asked for (manifest / workspace config / `--containment`).
    pub declared_containment: ContainmentClass,
    /// Strongest class this host can actually back, derived from the tier probe alone.
    pub achieved_containment: ContainmentClass,
    /// `achieved_containment >= declared_containment`. `false` means `mur run` would refuse.
    pub floor_met: bool,
    /// The missing mechanism when `floor_met` is `false`; absent otherwise.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shortfall_reason: Option<String>,
    /// The probed host tier, as a stable wire name.
    pub enforcement_tier: &'static str,
    /// Where this host's permission to create an unprivileged user namespace comes from, as
    /// [`UsernsGrant::wire_name`], or `null` off Linux, where AppArmor does not exist and the
    /// question has no answer.
    ///
    /// Always serialized, on the same terms as [`Self::workdir_exec`]: the key's absence
    /// identifies a runtime that predates it, not a host that was not asked. Reported because
    /// three very different hosts — no AppArmor, hardening switched off host-wide, and the shipped
    /// profile confining `mur` — otherwise produce byte-identical reports while differing enormously
    /// in what else on the machine can create a user namespace.
    pub userns_grant: Option<UsernsGrant>,
    /// `capabilities.filesystem.scope`, verbatim.
    pub filesystem_scope: Option<String>,
    /// `capabilities.filesystem.workdir_exec`. Always present (never skipped when `false`), so a
    /// consumer can tell "declared false" from "this runtime predates the key" by the field's
    /// presence rather than by its value.
    ///
    /// `true` is the only manifest declaration that lowers [`Self::achieved_containment`], which is
    /// why it is reported next to the grants rather than buried: reading `achieved: advisory` on a
    /// Landlock-capable host makes sense only alongside it.
    pub workdir_exec: bool,
    /// `capabilities.filesystem.read_only`, verbatim — the workdir subtrees the capsule may read
    /// but must not write. Empty when the capsule declares none, which is the whole workdir
    /// writable. Always serialized as an array (never skipped), on the same terms as
    /// [`Self::state_stores`]: an absent key identifies a runtime that predates the field, not a
    /// capsule that declared nothing.
    ///
    /// The one field here that subtracts rather than grants, which is why it is reported beside
    /// [`Self::read_only_advisory_for`] rather than alone: a protection stated without its
    /// qualification reads as a boundary the capsule does not have.
    pub read_only_paths: Vec<String>,
    /// The entries of [`Self::shell_allow`] that [`Self::read_only_paths`] is only advisory
    /// against — the same set `W-SEC-017` fires for, resolved by the same
    /// [`read_only_advisory_for`] both this report and `mur doctor` call.
    ///
    /// Empty means the declaration is enforced for every readable call. Non-empty names the
    /// binaries whose own file I/O the dispatch-time write-intent analyser cannot read, so the
    /// report cannot claim more than `W-SEC-017` already qualifies. Always serialized as an array
    /// (never skipped), on the same terms as [`Self::read_only_paths`], and always empty when
    /// that list is: nothing is advisory against a protection that was never declared.
    pub read_only_advisory_for: Vec<String>,
    /// The filesystem surface every guest-bearing artifact in this capsule is preopened into, one
    /// entry per `runtime: tool`, `runtime: driver` and `runtime: hook` entry, in manifest order.
    /// Empty when the capsule declares only skills. Always serialized as an array (never skipped),
    /// on the same terms as [`Self::state_stores`]: an absent key identifies a runtime that
    /// predates the field, not a capsule with no guest artifacts.
    ///
    /// This is the field that answers "what can this tool read and write?".
    /// [`Self::filesystem_scope`] above does not: it is the capsule-wide declaration, and it is
    /// joined into no preopen root.
    ///
    /// Copied through untouched, exactly as the reports beside it are — resolving a preopen
    /// changes no class, no floor and no tier.
    pub preopens: Vec<PreopenReport>,
    /// `capabilities.network.allow`, verbatim — declared destinations, not resolved IPs.
    pub network_allow: Vec<String>,
    /// `capabilities.network.unix_sockets`.
    pub unix_sockets: bool,
    /// `capabilities.shell.allow`, verbatim.
    pub shell_allow: Vec<String>,
    /// `capabilities.spawn.allow`, verbatim.
    pub spawn_allow: Vec<String>,
    /// `capabilities.env.allow`, verbatim.
    pub env_allow: Vec<String>,
    /// `capabilities.plan.submit` — whether the model is offered the `submit-plan` tool. Always
    /// serialized (never skipped when `false`), on the same terms as [`Self::workdir_exec`]: an
    /// absent key identifies a runtime that predates the grant, not a capsule that declined it.
    ///
    /// It opens no host resource of its own. It is reported beside the grants because it changes
    /// *how much* of every other grant one model turn can reach: a plan runs many steps against
    /// this capsule's own tools, shell allowlist and spawn grant without a turn in between.
    pub plan_submit: bool,
    /// Every host directory a `capabilities.shell.interpreter_runtime` grant opens, rendered as
    /// `<binary>: <dir>[ (list_dir)]`. These are the paths outside the workdir that stay
    /// reachable even at `scoped`.
    pub interpreter_runtime_grants: Vec<String>,
    /// The read-only file surface `exports.files` declares, or `null` when the capsule declares
    /// none. Always serialized (never skipped), so a consumer can tell "this runtime predates
    /// exports" from "this capsule declined to export anything" by the field's presence rather
    /// than by its value — the same terms [`Self::workdir_exec`] is reported on.
    ///
    /// An export is a *disclosure*, not a grant: it never appears in
    /// [`Self::achieved_containment`], and declaring one cannot change any other field of this
    /// report. It is printed beside the grants because it is the other direction of the same
    /// question — what crosses the capsule boundary, and which way.
    pub exports_files: Option<ExportsFilesReport>,
    /// The peer-handoff surface `exports.peer_files` declares, or `null` when the capsule
    /// declares none. Always serialized, on the same terms as [`Self::exports_files`].
    ///
    /// A separate authoriser from `exports.files`, over a separate subtree: a capsule may declare
    /// either, both or neither, and this field says nothing about the other. Like every export it
    /// is a disclosure rather than a grant, and declaring it cannot change
    /// [`Self::achieved_containment`], [`Self::enforcement_tier`] or [`Self::floor_met`].
    pub peer_files: Option<PeerFilesReport>,
    /// `capabilities.peer_fetch.allow`, verbatim — the peers this capsule may redeem a handle
    /// against. Empty when the block is absent, which is deny.
    ///
    /// A separate list from [`Self::network_allow`] and never an alias for it: a destination
    /// reachable by `send` is not redeemable unless it also appears here, because ingesting a
    /// peer's bytes into this workdir is a different question from being allowed to talk to it.
    pub peer_fetch_allow: Vec<String>,
    /// Every durable state store this session's artifacts declare, one entry per declaring
    /// artifact, empty when none does. Always serialized as an array (never skipped), on the same
    /// terms as [`Self::exports_files`]: an absent key identifies a runtime that predates state
    /// stores, not a capsule that declined one.
    ///
    /// Declaring a store cannot change [`Self::achieved_containment`], [`Self::floor_met`] or
    /// [`Self::enforcement_tier`] — it is copied through untouched, exactly as the export reports
    /// beside it are. It is reported because it is the one grant that opens a path *outside* every
    /// workdir, which nothing else in this block would reveal.
    pub state_stores: Vec<StateStoreReport>,
    /// Every artifact whose manifest entry declares a `config:` block, in manifest order, empty
    /// when none does. Always serialized as an array (never skipped), on the same terms as
    /// [`Self::state_stores`]: an absent key identifies a runtime that predates artifact config,
    /// not a capsule that declined it.
    ///
    /// Names only. What an artifact is configured *with* is operator-authored plaintext that
    /// belongs in the manifest and in nothing this report — or `trace.jsonl`, which carries this
    /// report verbatim — writes out.
    ///
    /// Declaring config cannot change [`Self::achieved_containment`], [`Self::floor_met`] or
    /// [`Self::enforcement_tier`]: it adds one environment variable to one guest and reaches no
    /// grant. Reported because a variable an artifact silently depends on is otherwise invisible
    /// to an operator reading the capsule's scope.
    pub configured_artifacts: Vec<String>,
    /// Every `capabilities.shell.staged_runtime` grant, rendered as
    /// `<binary>: <source_path> (pin: <pin>)`. These are host runtime trees a `sealed` capsule
    /// asks to have bind-mounted read-only into its composed root.
    ///
    /// Reported whatever the floor and whatever this host can back — a capsule that declares a
    /// staged runtime and cannot run here is exactly the case an operator is inspecting when they
    /// reach for `--explain-scope`, so hiding the grant behind a met floor would blank out the
    /// diagnostic in the one case it is for.
    pub staged_runtime_grants: Vec<String>,
    /// Every path the runtime itself writes inside the capsule's workdir, so a consumer for whom
    /// that workdir is the deliverable can subtract them and be left with what the *capsule*
    /// changed. Always serialized as an array (never skipped), on the same terms as
    /// [`Self::state_stores`]: an absent key identifies a runtime that predates the declaration,
    /// not a runtime that writes nothing.
    ///
    /// The one field here that describes what the runtime does rather than what the capsule may
    /// do. It is reported beside the grants because it answers the other half of "what is this
    /// workdir", and because a consumer that has to maintain its own list of runtime entries
    /// silently falls behind every time the set changes — enabling `sealed` being exactly that
    /// case.
    ///
    /// Keyed on the tier this session would install: [`Self::enforcement_tier`] capped by
    /// [`Self::declared_containment`], which is what decides whether a composed root is built at
    /// all. Reading `enforcement_tier: mountns+pivot_root+landlock+seccomp` next to a report with
    /// no `sealed` rows is that cap, not a disagreement — the host could seal and the capsule did
    /// not ask. See [`crate::workdir_writes`].
    pub runtime_writes: Vec<crate::workdir_writes::RuntimeWriteReport>,
    /// The declared `capabilities.resources.cgroup_io_bytes_per_sec` ceiling, and whether it is
    /// actually on this session's cgroup scope.
    ///
    /// Always serialized (never skipped), on the same terms as [`Self::workdir_exec`] and
    /// [`Self::state_stores`]: an absent key identifies a runtime that predates the field, not a
    /// host that was not asked. [`IoMaxStatus::NotProbed`] is what "not asked" looks like, and it
    /// is a value in the report rather than a missing key.
    ///
    /// The one field here filled from a *performed* operation rather than from the policy: at
    /// launch it carries the outcome of the real `io.max` write, established before `session_start`
    /// is written so `trace.jsonl` cannot claim a ceiling the kernel refused; under
    /// `--explain-scope` it carries the outcome of the same write against a throwaway cgroup that
    /// is created and removed. Declaring a ceiling that does not apply changes no class and refuses
    /// no launch — `io.max` is the one non-fatal cgroup limit — so this field is the only place
    /// the shortfall appears.
    pub io_max: IoMaxReport,
    /// What this session's filesystem mechanism does not restrict — the block `--explain-scope`
    /// prints as `Not protected here`, directly under `Containment`.
    ///
    /// Always serialized (never skipped), on the same terms as [`Self::state_stores`]: an absent
    /// key identifies a runtime that predates the field, and an empty
    /// [`FilesystemBoundaryReport::not_protected`] identifies a session with nothing to disclaim.
    ///
    /// Derived in [`filesystem_boundary`] from [`crate::sandbox::applied_tier`] — the same value
    /// [`Self::runtime_writes`] is keyed on — and from no [`CapabilityPolicy`] field. Not from
    /// [`Self::achieved_containment`], which reports the class this *host* can back: a capsule
    /// declaring less than `sealed` on a sealed-capable host reads `achieved: sealed` and composes
    /// no root, so a boundary keyed on the class would report an absence the capsule does not have.
    /// It stands beside the grants rather than among them because it qualifies every one at once.
    pub filesystem_boundary: FilesystemBoundaryReport,
}

impl ScopeReport {
    /// Human-readable rendering used by `mur run --explain-scope` without `--json`.
    pub fn render(&self) -> String {
        let mut out = String::new();
        out.push_str("Containment\n");
        out.push_str(&format!("  declared:  {}\n", self.declared_containment));
        out.push_str(&format!("  achieved:  {}\n", self.achieved_containment));
        out.push_str(&format!(
            "  floor met: {}\n",
            if self.floor_met { "yes" } else { "no" }
        ));
        if let Some(reason) = &self.shortfall_reason {
            out.push_str(&format!("  reason:    {reason}\n"));
        }
        out.push_str(&format!("  mechanism: {}\n", self.enforcement_tier));
        out.push_str(&format!(
            "  userns grant: {}\n",
            match self.userns_grant {
                Some(grant) => grant.wire_name(),
                None => "n/a",
            }
        ));

        out.push_str(&render_not_protected(&self.filesystem_boundary));

        out.push_str("\nEffective grants\n");
        out.push_str(&format!(
            "  filesystem scope: {}\n",
            self.filesystem_scope.as_deref().unwrap_or("<none>")
        ));
        out.push_str(&format!("  workdir exec:     {}\n", self.workdir_exec));
        out.push_str(&render_read_only(
            &self.read_only_paths,
            &self.read_only_advisory_for,
        ));
        push_list(
            &mut out,
            "preopens",
            &self
                .preopens
                .iter()
                .map(PreopenReport::render)
                .collect::<Vec<_>>(),
        );
        push_list(&mut out, "network allow", &self.network_allow);
        out.push_str(&format!("  unix sockets:     {}\n", self.unix_sockets));
        push_list(&mut out, "shell allow", &self.shell_allow);
        push_list(&mut out, "spawn allow", &self.spawn_allow);
        push_list(&mut out, "env allow", &self.env_allow);
        out.push_str(&format!("  plan submit:      {}\n", self.plan_submit));
        push_list(
            &mut out,
            "interpreter runtime",
            &self.interpreter_runtime_grants,
        );
        push_list(&mut out, "staged runtime", &self.staged_runtime_grants);
        push_list(
            &mut out,
            "state stores",
            &self
                .state_stores
                .iter()
                .map(|store| format!("{}: {} -> {}", store.artifact, store.store, store.host_path))
                .collect::<Vec<_>>(),
        );
        push_list(&mut out, "artifact config", &self.configured_artifacts);

        out.push_str("\nResource plane\n");
        match &self.exports_files {
            None => out.push_str("  exports.files: <none>\n"),
            Some(export) => {
                out.push_str(&format!("  exports.files root: {}\n", export.root));
                out.push_str(&format!("  mode:               {}\n", export.mode));
                out.push_str(&format!(
                    "  max bytes:          {} (per file)\n",
                    export.max_bytes
                ));
            }
        }

        out.push_str(&format!(
            "  io.max:        {} ({} bytes/s declared)\n",
            match self.io_max.status {
                IoMaxStatus::Enforced => "enforced",
                IoMaxStatus::Unavailable => "unavailable",
                IoMaxStatus::NotRequired => "not-required",
                IoMaxStatus::NotProbed => "not-probed",
            },
            self.io_max.declared_bytes_per_sec
        ));
        if let Some(reason) = &self.io_max.reason {
            out.push_str(&format!("    {reason}\n"));
        }

        out.push_str("\nPeer handoff\n");
        match &self.peer_files {
            None => out.push_str("  exports.peer_files: <none>\n"),
            Some(peer) => {
                out.push_str(&format!("  exports.peer_files root: {}\n", peer.root));
                out.push_str(&format!(
                    "  max handle ttl:          {}s\n",
                    peer.max_ttl_secs
                ));
                out.push_str(&format!(
                    "  max bytes:               {} (per file)\n",
                    peer.max_bytes
                ));
            }
        }
        push_list(&mut out, "peer_fetch allow", &self.peer_fetch_allow);

        out.push_str("\nRuntime writes\n");
        out.push_str(&crate::workdir_writes::render_runtime_writes(
            &self.runtime_writes,
        ));

        if !self.floor_met {
            out.push_str(
                "\nThis is a report only — `mur run` without --explain-scope would refuse to \
                 launch here.\n",
            );
        }
        out
    }
}

/// The allowlisted binaries a declared `capabilities.filesystem.read_only` is only advisory
/// against: those whose own file I/O the dispatch-time write-intent analyser cannot read, in
/// `shell_allow` order.
///
/// Exactly the set `W-SEC-017` fires one line for, resolved here so `--explain-scope`, `trace.jsonl`
/// and `mur doctor` cannot disagree with the warning printed beside them. Empty when nothing is
/// declared read-only: an interpreter is not advisory against a protection that does not exist.
#[must_use]
pub fn read_only_advisory_for(read_only_paths: &[String], shell_allow: &[String]) -> Vec<String> {
    if read_only_paths.is_empty() {
        return Vec::new();
    }
    shell_allow
        .iter()
        .filter(|binary| crate::protected_paths::is_advisory_interpreter(binary))
        .cloned()
        .collect()
}

/// The `read_only` block of the scope report: the declared paths, then one line saying whether the
/// protection is enforced for every readable call or advisory against a named binary.
///
/// Shared by [`ScopeReport::render`] and by `mur doctor` so the two cannot word the same grant
/// differently — the precedent [`PreopenReport::render`] sets. Ends with a newline; emits nothing
/// beyond the `<none>` line when no path is declared, because there is no enforcement question to
/// answer about a protection nobody asked for.
#[must_use]
pub fn render_read_only(read_only_paths: &[String], advisory_for: &[String]) -> String {
    let mut out = String::new();
    push_list(&mut out, "read_only", read_only_paths);
    if read_only_paths.is_empty() {
        return out;
    }
    if advisory_for.is_empty() {
        out.push_str(
            "  read_only enforcement: enforced for every tool call and every shell command the \
             dispatch check can read\n",
        );
    } else {
        out.push_str(&format!(
            "  read_only enforcement: advisory against {} — an interpreter's own file I/O is not \
             something the dispatch check can read; enforced for every tool call and for every \
             shell command it can read\n",
            advisory_for.join(", ")
        ));
    }
    out
}

/// The `Not protected here` block: one line per statement in
/// [`FilesystemBoundaryReport::not_protected`], and nothing at all when that list is empty.
///
/// A heading with no entries under it would read as a disclaimer the reader had to interpret, so a
/// composed root prints no heading rather than an empty one. Every line is a statement from the report
/// verbatim, so the human rendering and `--explain-scope --json` say the same thing in the same
/// words.
fn render_not_protected(boundary: &FilesystemBoundaryReport) -> String {
    if boundary.not_protected.is_empty() {
        return String::new();
    }
    let mut out = String::from("\nNot protected here\n");
    for statement in &boundary.not_protected {
        out.push_str(&format!("  - {statement}\n"));
    }
    out
}

fn push_list(out: &mut String, label: &str, values: &[String]) {
    if values.is_empty() {
        out.push_str(&format!("  {label}: <none>\n"));
        return;
    }
    out.push_str(&format!("  {label}:\n"));
    for value in values {
        out.push_str(&format!("    - {value}\n"));
    }
}

/// Builds a [`ScopeReport`] for `policy` against this host, with `declared` as the already-
/// combined floor. Takes one [`crate::sandbox::HostProbe`], so the tier, the blocker and the
/// grant it reports all describe one host at one moment.
///
/// `state_stores`, `configured_artifacts` and `preopens` are resolved by the caller (from the
/// manifest's artifact entries, via [`crate::state_store::state_store_reports`],
/// [`crate::artifact_config::configured_artifact_names`] and
/// [`crate::network_policy::preopen_reports`]) rather than derived here, because all three are
/// per-artifact and `policy` is capsule-wide. No resolution creates anything, so this stays a
/// read-only diagnostic.
pub fn explain_scope(
    policy: &CapabilityPolicy,
    declared: ContainmentClass,
    exports: Option<&Exports>,
    state_stores: Vec<StateStoreReport>,
    configured_artifacts: Vec<String>,
    preopens: Vec<PreopenReport>,
    io_max: IoMaxReport,
) -> ScopeReport {
    let probe = crate::sandbox::HostProbe::probe();
    scope_report_for_tier(
        policy,
        declared,
        probe.tier(),
        probe.sealed_blocker(),
        probe.userns_grant(),
        exports,
        state_stores,
        configured_artifacts,
        preopens,
        io_max,
    )
}

/// [`explain_scope`] with the tier and the sealed blocker injected — the seam every test uses so
/// no test depends on the host it happens to run on.
#[allow(clippy::too_many_arguments)]
pub(crate) fn scope_report_for_tier(
    policy: &CapabilityPolicy,
    declared: ContainmentClass,
    tier: EnforcementTier,
    sealed_blocker: Option<SealedBlocker>,
    userns_grant: Option<UsernsGrant>,
    exports: Option<&Exports>,
    state_stores: Vec<StateStoreReport>,
    configured_artifacts: Vec<String>,
    preopens: Vec<PreopenReport>,
    io_max: IoMaxReport,
) -> ScopeReport {
    let achieved = achieved_containment_class(tier, policy.workdir_exec_allowed);
    // The tier this session would actually install: the host reading `enforcement_tier`
    // reports, capped by the declared floor, which is the same `sandbox::applied_tier`
    // `ShellEnforcement::resolve` runs. Two fields below are keyed on it rather than on
    // `achieved`, because both describe mechanisms rather than the class this host can back.
    let applied = crate::sandbox::applied_tier(tier, declared);
    let shortfall_reason = containment_shortfall_reason(
        declared,
        achieved,
        sealed_blocker,
        policy.workdir_exec_allowed,
    );

    ScopeReport {
        declared_containment: declared,
        achieved_containment: achieved,
        floor_met: shortfall_reason.is_none(),
        shortfall_reason,
        enforcement_tier: enforcement_tier_name(tier),
        userns_grant,
        // Copied straight through and never consulted above: `achieved` is already computed, and
        // no export or peer grant may reach it.
        exports_files: exports
            .and_then(|exports| exports.files.as_ref())
            .map(ExportsFilesReport::from),
        peer_files: exports
            .and_then(|exports| exports.peer_files.as_ref())
            .map(PeerFilesReport::from),
        peer_fetch_allow: policy.peer_fetch_allow.clone(),
        // Resolved by `state_store::state_store_reports` before this call and copied through on
        // the same terms as the export reports above: a grant that opens a path outside the
        // workdir still gets no say in what class this host is reported to back.
        state_stores,
        // Resolved by `artifact_config::configured_artifact_names` before this call and copied
        // through on the same terms: one environment variable delivered to one guest gets no say
        // in what class this host is reported to back.
        configured_artifacts,
        filesystem_scope: policy.filesystem_scope.clone(),
        workdir_exec: policy.workdir_exec_allowed,
        read_only_paths: policy.read_only_paths.clone(),
        read_only_advisory_for: read_only_advisory_for(
            &policy.read_only_paths,
            &policy.shell_allow,
        ),
        // Resolved by `network_policy::preopen_reports` before this call and copied through on the
        // same terms as the reports above: what one guest is preopened into gets no say in what
        // class this host is reported to back.
        preopens,
        network_allow: policy.network_allow.clone(),
        unix_sockets: policy.unix_sockets_allowed,
        shell_allow: policy.shell_allow.clone(),
        spawn_allow: policy.spawn_allow.clone(),
        env_allow: policy.env_allow.clone(),
        plan_submit: policy.plan_submit,
        interpreter_runtime_grants: policy
            .shell_interpreter_runtime
            .iter()
            .flat_map(|grant| {
                grant.dirs.iter().map(move |dir| {
                    let listable = if dir.list_dir { " (list_dir)" } else { "" };
                    format!("{}: {}{}", grant.binary, dir.path, listable)
                })
            })
            .collect(),
        staged_runtime_grants: policy
            .shell_staged_runtime
            .iter()
            .map(|grant| {
                format!(
                    "{}: {} (pin: {})",
                    grant.binary, grant.source_path, grant.pin
                )
            })
            .collect(),
        // A capsule declaring `scoped` on a sealed-capable host composes no root and writes no
        // `/tmp` store, so a declaration keyed on the bare host tier would name two directories
        // that never appear. Nothing here touches the filesystem: `--explain-scope` returns before
        // a workdir exists, and a diagnostic that created the directory it describes would be
        // answering a question it had changed.
        runtime_writes: crate::workdir_writes::runtime_writes(applied),
        // Established by performing the `io.max` write, never inferred: `prepare_scope` fills it
        // at launch and `cgroup::probe_io_max` fills it under `--explain-scope`. Like every field
        // above it, it reaches no class and no floor.
        io_max,
        // Derived here, from the `applied` tier already resolved above, rather than filled by
        // either caller: `--explain-scope --json` and `session_start.effective_grants` are the
        // same object, and a field either of them worded for itself would make them differ.
        filesystem_boundary: filesystem_boundary(applied),
    }
}

/// Stable wire name for a tier, so `--explain-scope --json` consumers see the mechanism rather
/// than a `Debug` rendering that is free to change.
fn enforcement_tier_name(tier: EnforcementTier) -> &'static str {
    match tier {
        EnforcementTier::KernelSealed => "mountns+pivot_root+landlock+seccomp",
        EnforcementTier::KernelFull => "landlock+seccomp",
        EnforcementTier::KernelSeccompOnly => "seccomp-only",
        EnforcementTier::EnvironmentOnly => "none",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use murmur_artifact::{InterpreterRuntimeDir, InterpreterRuntimeGrant, StagedRuntimeGrant};

    /// Every tier, so a new variant cannot quietly escape a test that iterates "all of them".
    const ALL_TIERS: &[EnforcementTier] = &[
        EnforcementTier::KernelSealed,
        EnforcementTier::KernelFull,
        EnforcementTier::KernelSeccompOnly,
        EnforcementTier::EnvironmentOnly,
    ];

    #[test]
    fn kernel_full_achieves_scoped() {
        assert_eq!(
            achieved_class_for_tier(EnforcementTier::KernelFull),
            ContainmentClass::Scoped
        );
    }

    /// The sealed tier, and only the sealed tier, reports `sealed`.
    #[test]
    fn only_the_sealed_tier_achieves_sealed() {
        assert_eq!(
            achieved_class_for_tier(EnforcementTier::KernelSealed),
            ContainmentClass::Sealed
        );
        for tier in ALL_TIERS
            .iter()
            .filter(|t| **t != EnforcementTier::KernelSealed)
        {
            assert_ne!(achieved_class_for_tier(*tier), ContainmentClass::Sealed);
        }
    }

    #[test]
    fn tiers_without_landlock_achieve_only_advisory() {
        assert_eq!(
            achieved_class_for_tier(EnforcementTier::KernelSeccompOnly),
            ContainmentClass::Advisory
        );
        assert_eq!(
            achieved_class_for_tier(EnforcementTier::EnvironmentOnly),
            ContainmentClass::Advisory
        );
    }

    /// The whole tier × `workdir_exec` truth table, with both inputs supplied by the test and no
    /// kernel consulted — the seam `achieved_class_for_tier`/`achieved_containment_class` exists
    /// for. This is emphatically *not* a test of the security property (that a workdir binary
    /// cannot execute); it tests only the class arithmetic, which is all that can honestly be
    /// tested without a Landlock-capable host.
    #[test]
    fn workdir_exec_caps_the_achieved_class_at_advisory_on_every_tier() {
        // Without the declaration: the host ceiling, unchanged.
        assert_eq!(
            achieved_containment_class(EnforcementTier::KernelSealed, false),
            ContainmentClass::Sealed
        );
        assert_eq!(
            achieved_containment_class(EnforcementTier::KernelFull, false),
            ContainmentClass::Scoped
        );
        assert_eq!(
            achieved_containment_class(EnforcementTier::KernelSeccompOnly, false),
            ContainmentClass::Advisory
        );
        assert_eq!(
            achieved_containment_class(EnforcementTier::EnvironmentOnly, false),
            ContainmentClass::Advisory
        );

        // With it: advisory, whatever the host could otherwise back.
        for tier in ALL_TIERS {
            assert_eq!(
                achieved_containment_class(*tier, true),
                ContainmentClass::Advisory,
                "workdir_exec must cap tier {tier:?} at advisory"
            );
        }
    }

    /// The cap goes in the wrapper, never in the tier-only function — a regression here would mean
    /// a manifest key had leaked into the one mapping that must stay host-only.
    #[test]
    fn the_tier_only_mapping_is_unaffected_by_the_cap() {
        for tier in ALL_TIERS {
            assert_eq!(
                achieved_class_for_tier(*tier),
                achieved_containment_class(*tier, false),
                "the tier-only mapping and the uncapped wrapper must agree on tier {tier:?}"
            );
        }
    }

    /// The refusal an operator actually hits: `workdir_exec: true` plus
    /// `capabilities.containment: scoped`, on a host that could otherwise back `scoped`. It must
    /// refuse, and the reason must send them to their manifest rather than to another machine.
    #[test]
    fn workdir_exec_refuses_a_scoped_floor_even_on_a_landlock_capable_host() {
        let achieved = achieved_containment_class(EnforcementTier::KernelFull, true);
        assert_eq!(achieved, ContainmentClass::Advisory);

        let error = check_containment_floor(ContainmentClass::Scoped, achieved, None, true)
            .expect_err("workdir_exec + scoped must refuse");
        match error {
            RuntimeError::ContainmentFloorUnmet {
                declared,
                achieved,
                reason,
            } => {
                assert_eq!(declared, ContainmentClass::Scoped);
                assert_eq!(achieved, ContainmentClass::Advisory);
                assert!(
                    reason.contains("workdir_exec"),
                    "the reason must name the manifest key, got: {reason}"
                );
                assert!(
                    !reason.contains("this host provides no kernel filesystem mediation"),
                    "the reason must not blame the host for a manifest declaration: {reason}"
                );
            }
            other => panic!("expected ContainmentFloorUnmet, got {other:?}"),
        }
    }

    /// `sealed` gets the same manifest-side reason rather than a `SealedBlocker` one: a probed
    /// blocker is real but is not what is stopping *this* capsule, and reporting it would send the
    /// operator to install an AppArmor profile that changes nothing.
    #[test]
    fn workdir_exec_outranks_a_probed_sealed_blocker_in_the_reason() {
        let reason = containment_shortfall_reason(
            ContainmentClass::Sealed,
            ContainmentClass::Advisory,
            Some(SealedBlocker::AppArmorProfileMissing),
            true,
        )
        .expect("refusal");
        assert!(reason.contains("workdir_exec"));
        assert!(!reason.contains("apparmor_parser"));
    }

    /// The declaration is not itself a refusal: a capsule that declares `workdir_exec` and asks
    /// for nothing above `advisory` launches normally on every host.
    #[test]
    fn workdir_exec_alone_refuses_nothing() {
        for tier in ALL_TIERS {
            let achieved = achieved_containment_class(*tier, true);
            assert!(
                check_containment_floor(ContainmentClass::Advisory, achieved, None, true).is_ok(),
                "workdir_exec at an advisory floor must launch on tier {tier:?}"
            );
        }
    }

    #[test]
    fn advisory_floor_is_met_on_every_tier() {
        for tier in ALL_TIERS {
            let achieved = achieved_class_for_tier(*tier);
            assert!(
                check_containment_floor(ContainmentClass::Advisory, achieved, None, false).is_ok()
            );
        }
    }

    #[test]
    fn scoped_floor_is_met_on_every_landlock_capable_tier() {
        for tier in [EnforcementTier::KernelFull, EnforcementTier::KernelSealed] {
            let achieved = achieved_class_for_tier(tier);
            assert!(
                check_containment_floor(ContainmentClass::Scoped, achieved, None, false).is_ok()
            );
        }

        for tier in [
            EnforcementTier::KernelSeccompOnly,
            EnforcementTier::EnvironmentOnly,
        ] {
            let achieved = achieved_class_for_tier(tier);
            let error = check_containment_floor(ContainmentClass::Scoped, achieved, None, false)
                .expect_err("scoped must refuse without Landlock");
            match error {
                RuntimeError::ContainmentFloorUnmet {
                    declared,
                    achieved,
                    reason,
                } => {
                    assert_eq!(declared, ContainmentClass::Scoped);
                    assert_eq!(achieved, ContainmentClass::Advisory);
                    assert!(
                        reason.contains("Landlock"),
                        "reason must name the missing mechanism, got: {reason}"
                    );
                }
                other => panic!("expected ContainmentFloorUnmet, got {other:?}"),
            }
        }
    }

    /// The edge case the new tier makes possible: a capsule declaring the *weaker* class on a
    /// sealed-capable host. The floor is met (a stronger host satisfies a weaker requirement),
    /// and the applied mechanism is the declared one — asserted next door in
    /// `sandbox::applied_tier`'s tests, since a careless `match` here could force sealed-only
    /// behaviour onto a `scoped` declaration.
    #[test]
    fn a_weaker_declaration_is_satisfied_by_a_sealed_host_without_being_upgraded() {
        let achieved = achieved_class_for_tier(EnforcementTier::KernelSealed);
        assert_eq!(achieved, ContainmentClass::Sealed);
        assert!(check_containment_floor(ContainmentClass::Advisory, achieved, None, false).is_ok());
        assert!(check_containment_floor(ContainmentClass::Scoped, achieved, None, false).is_ok());
        assert_eq!(
            containment_shortfall_reason(ContainmentClass::Scoped, achieved, None, false),
            None
        );
    }

    #[test]
    fn sealed_floor_is_met_only_on_the_sealed_tier() {
        assert!(check_containment_floor(
            ContainmentClass::Sealed,
            achieved_class_for_tier(EnforcementTier::KernelSealed),
            None,
            false
        )
        .is_ok());

        for tier in ALL_TIERS
            .iter()
            .filter(|t| **t != EnforcementTier::KernelSealed)
        {
            let achieved = achieved_class_for_tier(*tier);
            let error = check_containment_floor(
                ContainmentClass::Sealed,
                achieved,
                Some(SealedBlocker::NamespaceCreationDenied),
                false,
            )
            .expect_err("sealed must refuse on a host that cannot back it");
            match error {
                RuntimeError::ContainmentFloorUnmet {
                    declared, reason, ..
                } => {
                    assert_eq!(declared, ContainmentClass::Sealed);
                    assert!(
                        reason.contains("--cap-add SYS_ADMIN"),
                        "reason must name the blocking mechanism's remediation, got: {reason}"
                    );
                }
                other => panic!("expected ContainmentFloorUnmet, got {other:?}"),
            }
        }
    }

    /// The refusal text is mechanism-specific, not one fixed sentence: the same
    /// declared/achieved pair produces different, individually actionable reasons.
    #[test]
    fn the_sealed_refusal_names_the_specific_blocker() {
        let achieved = ContainmentClass::Scoped;

        let apparmor = containment_shortfall_reason(
            ContainmentClass::Sealed,
            achieved,
            Some(SealedBlocker::AppArmorProfileMissing),
            false,
        )
        .expect("refusal");
        assert!(apparmor.contains("mur-sealed"));
        assert!(apparmor.contains("apparmor_parser -r"));
        assert!(!apparmor.contains("--cap-add"));

        let container = containment_shortfall_reason(
            ContainmentClass::Sealed,
            achieved,
            Some(SealedBlocker::NamespaceCreationDenied),
            false,
        )
        .expect("refusal");
        assert!(container.contains("--cap-add SYS_ADMIN"));
        assert!(container.contains("outside the container"));
        assert!(!container.contains("apparmor_parser"));

        // A host that mounts and will not pivot is refused at launch with its own text, rather
        // than at the first subprocess with `E-RUN-014`.
        let pivot = containment_shortfall_reason(
            ContainmentClass::Sealed,
            ContainmentClass::Advisory,
            Some(SealedBlocker::PivotRootDenied),
            false,
        )
        .expect("refusal");
        assert!(pivot.contains("pivot_root(2)"), "reason was: {pivot}");
        assert_ne!(
            pivot,
            containment_shortfall_reason(
                ContainmentClass::Sealed,
                ContainmentClass::Advisory,
                Some(SealedBlocker::MountDenied),
                false,
            )
            .expect("refusal")
        );

        // Never the pre-mechanism blanket text again, under any blocker.
        for blocker in [
            SealedBlocker::NotLinux,
            SealedBlocker::AppArmorProfileMissing,
            SealedBlocker::NamespaceCreationDenied,
            SealedBlocker::MountDenied,
            SealedBlocker::PivotRootDenied,
            SealedBlocker::KernelUnsupported,
            SealedBlocker::LandlockUnavailable,
        ] {
            let reason = containment_shortfall_reason(
                ContainmentClass::Sealed,
                achieved,
                Some(blocker),
                false,
            )
            .expect("refusal");
            assert!(
                !reason.contains("no host can provide it today"),
                "got: {reason}"
            );
        }
    }

    /// A caller with no probe result still gets a reason naming the mechanism rather than an
    /// empty or misleading one.
    #[test]
    fn the_sealed_refusal_falls_back_to_naming_the_mechanism_without_a_probe() {
        let reason = containment_shortfall_reason(
            ContainmentClass::Sealed,
            ContainmentClass::Advisory,
            None,
            false,
        )
        .expect("refusal");
        assert!(reason.contains("pivot_root"));
        assert!(reason.contains("CLONE_NEWNS"));
    }

    #[test]
    fn shortfall_reason_is_absent_when_the_floor_is_met() {
        assert_eq!(
            containment_shortfall_reason(
                ContainmentClass::Advisory,
                ContainmentClass::Scoped,
                None,
                false
            ),
            None
        );
        assert_eq!(
            containment_shortfall_reason(
                ContainmentClass::Scoped,
                ContainmentClass::Scoped,
                None,
                false
            ),
            None
        );
        assert_eq!(
            containment_shortfall_reason(
                ContainmentClass::Sealed,
                ContainmentClass::Sealed,
                Some(SealedBlocker::NamespaceCreationDenied),
                false
            ),
            None,
            "a met floor must ignore a stale blocker rather than manufacture a refusal"
        );
    }

    fn sample_policy() -> CapabilityPolicy {
        CapabilityPolicy {
            network_allow: vec!["https://api.example.com".to_string()],
            unix_sockets_allowed: false,
            filesystem_scope: Some("workdir".to_string()),
            shell_allow: vec!["python3".to_string()],
            spawn_allow: vec!["helper".to_string()],
            env_allow: vec!["TZ".to_string()],
            shell_interpreter_runtime: vec![InterpreterRuntimeGrant {
                binary: "python3".to_string(),
                dirs: vec![InterpreterRuntimeDir {
                    path: "/usr/lib/python3.11".to_string(),
                    list_dir: true,
                }],
            }],
            ..CapabilityPolicy::default()
        }
    }

    #[test]
    fn scope_report_mirrors_the_policy_and_the_probed_tier() {
        let report = scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Scoped,
            EnforcementTier::KernelFull,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        );

        assert_eq!(report.declared_containment, ContainmentClass::Scoped);
        assert_eq!(report.achieved_containment, ContainmentClass::Scoped);
        assert!(report.floor_met);
        assert_eq!(report.shortfall_reason, None);
        assert_eq!(report.enforcement_tier, "landlock+seccomp");
        assert_eq!(report.filesystem_scope.as_deref(), Some("workdir"));
        assert_eq!(report.network_allow, vec!["https://api.example.com"]);
        assert!(!report.unix_sockets);
        assert_eq!(report.shell_allow, vec!["python3"]);
        assert_eq!(report.spawn_allow, vec!["helper"]);
        assert_eq!(report.env_allow, vec!["TZ"]);
        assert!(!report.workdir_exec);
        assert_eq!(
            report.interpreter_runtime_grants,
            vec!["python3: /usr/lib/python3.11 (list_dir)"]
        );
    }

    /// `--explain-scope` is where an operator finds out *why* a Landlock-capable host is reporting
    /// `advisory`, so the declaration and the class it produced have to appear together — in the
    /// struct, in the JSON, and in the rendered text.
    #[test]
    fn scope_report_surfaces_workdir_exec_and_the_advisory_it_forces() {
        let policy = CapabilityPolicy {
            shell_allow: vec!["gcc".to_string()],
            workdir_exec_allowed: true,
            ..CapabilityPolicy::default()
        };

        let report = scope_report_for_tier(
            &policy,
            ContainmentClass::Scoped,
            EnforcementTier::KernelFull,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        );

        assert!(report.workdir_exec);
        assert_eq!(report.achieved_containment, ContainmentClass::Advisory);
        assert!(!report.floor_met);
        // The host is fully capable; the mechanism line must keep saying so, so the report does
        // not read as a broken host.
        assert_eq!(report.enforcement_tier, "landlock+seccomp");
        assert!(report
            .shortfall_reason
            .as_deref()
            .expect("refusal")
            .contains("workdir_exec"));

        let value: serde_json::Value = serde_json::to_value(&report).unwrap();
        assert_eq!(value["workdir_exec"], true);

        let rendered = report.render();
        assert!(rendered.contains("workdir exec:     true"));
        assert!(rendered.contains("achieved:  advisory"));
    }

    /// The key is always written, on the same terms `workdir_exec` and `state_stores` are: an
    /// absent `io_max` identifies a runtime that predates the field, not a host that was not
    /// asked. "Not asked" is a value — `not-probed` — inside the object.
    #[test]
    fn scope_report_json_always_carries_io_max() {
        let unprobed: serde_json::Value = serde_json::to_value(scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Scoped,
            EnforcementTier::KernelFull,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        ))
        .unwrap();
        assert_eq!(unprobed["io_max"]["status"], "not-probed");
        assert_eq!(unprobed["io_max"]["declared_bytes_per_sec"], 0);
        assert!(unprobed["io_max"].get("reason").is_none());

        let enforced: serde_json::Value = serde_json::to_value(scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Scoped,
            EnforcementTier::KernelFull,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport {
                declared_bytes_per_sec: 52_428_800,
                status: IoMaxStatus::Enforced,
                reason: None,
            },
        ))
        .unwrap();
        assert_eq!(enforced["io_max"]["status"], "enforced");
        assert_eq!(enforced["io_max"]["declared_bytes_per_sec"], 52_428_800);
    }

    /// A ceiling that did not apply has to be visible in the rendering an operator reads, not
    /// only in the JSON: this report is where the claim of an I/O bound would otherwise stand
    /// uncontradicted.
    #[test]
    fn the_rendered_resource_plane_states_what_became_of_the_io_ceiling() {
        let rendered = scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Scoped,
            EnforcementTier::KernelFull,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport {
                declared_bytes_per_sec: 52_428_800,
                status: IoMaxStatus::Unavailable,
                reason: Some("the io controller is not delegated".to_string()),
            },
        )
        .render();

        assert!(rendered.contains("Resource plane"), "{rendered}");
        assert!(rendered.contains("io.max:"), "{rendered}");
        assert!(rendered.contains("unavailable"), "{rendered}");
        assert!(rendered.contains("52428800 bytes/s declared"), "{rendered}");
        assert!(
            rendered.contains("the io controller is not delegated"),
            "{rendered}"
        );
    }

    /// The field is always written, including `false`, so a consumer can distinguish "this capsule
    /// declared nothing" from "this runtime does not know the key".
    #[test]
    fn scope_report_json_always_carries_workdir_exec() {
        let value: serde_json::Value = serde_json::to_value(scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Scoped,
            EnforcementTier::KernelFull,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        ))
        .unwrap();
        assert_eq!(value["workdir_exec"], false);
    }

    /// `--explain-scope` is a diagnostic, not a launch: a capsule declaring `staged_runtime` on a
    /// host that cannot back `sealed` is exactly the case an operator inspects with it, so the
    /// grant must be reported on every tier — including the ones where `mur run` would refuse.
    #[test]
    fn staged_runtime_grants_are_reported_on_every_tier() {
        let policy = CapabilityPolicy {
            shell_allow: vec!["python3".to_string()],
            shell_staged_runtime: vec![StagedRuntimeGrant {
                binary: "python3".to_string(),
                source_path: "/opt/testbed/conda/envs/django__django".to_string(),
                pin: "conda-4.10.3/python-3.9.19".to_string(),
            }],
            ..CapabilityPolicy::default()
        };

        for tier in ALL_TIERS {
            let report = scope_report_for_tier(
                &policy,
                ContainmentClass::Sealed,
                *tier,
                Some(SealedBlocker::NamespaceCreationDenied),
                None,
                None,
                Vec::new(),
                Vec::new(),
                Vec::new(),
                IoMaxReport::default(),
            );
            assert_eq!(
                report.staged_runtime_grants,
                vec![
                    "python3: /opt/testbed/conda/envs/django__django \
                     (pin: conda-4.10.3/python-3.9.19)"
                ],
                "tier {tier:?} must still report the declared staged runtime"
            );
            assert!(
                report.render().contains("staged runtime"),
                "the rendered report must carry a staged runtime section on tier {tier:?}"
            );
        }
    }

    /// The absent case: no `staged_runtime` in the manifest leaves the section empty rather than
    /// inventing one, and `render` still names it as `<none>` like every other empty list.
    #[test]
    fn absent_staged_runtime_reports_nothing() {
        let report = scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Scoped,
            EnforcementTier::KernelFull,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        );
        assert!(report.staged_runtime_grants.is_empty());
        assert!(report.render().contains("staged runtime: <none>"));
    }

    /// A capsule that declares `scoped` *and* opens host paths through `interpreter_runtime`
    /// still achieves only `scoped` — the grant set is reported, never consulted to upgrade
    /// the achieved class.
    #[test]
    fn grant_set_never_raises_the_achieved_class() {
        let report = scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Sealed,
            EnforcementTier::KernelFull,
            Some(SealedBlocker::NamespaceCreationDenied),
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        );
        assert_eq!(report.achieved_containment, ContainmentClass::Scoped);
        assert!(!report.floor_met);
    }

    #[test]
    fn scope_report_still_reports_when_the_floor_is_unmet() {
        let report = scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Sealed,
            EnforcementTier::EnvironmentOnly,
            Some(SealedBlocker::NotLinux),
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        );

        assert_eq!(report.declared_containment, ContainmentClass::Sealed);
        assert_eq!(report.achieved_containment, ContainmentClass::Advisory);
        assert!(!report.floor_met);
        assert!(report.shortfall_reason.unwrap().contains("non-Linux"));
        assert_eq!(report.enforcement_tier, "none");
    }

    #[test]
    fn scope_report_names_the_sealed_mechanism_on_a_sealed_host() {
        let report = scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Sealed,
            EnforcementTier::KernelSealed,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        );
        assert_eq!(report.achieved_containment, ContainmentClass::Sealed);
        assert!(report.floor_met);
        assert_eq!(
            report.enforcement_tier,
            "mountns+pivot_root+landlock+seccomp"
        );
    }

    #[test]
    fn scope_report_json_uses_wire_names() {
        let report = scope_report_for_tier(
            &CapabilityPolicy::default(),
            ContainmentClass::Advisory,
            EnforcementTier::KernelSeccompOnly,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        );
        let value: serde_json::Value = serde_json::to_value(&report).unwrap();

        assert_eq!(value["declared_containment"], "advisory");
        assert_eq!(value["achieved_containment"], "advisory");
        assert_eq!(value["floor_met"], true);
        assert_eq!(value["enforcement_tier"], "seccomp-only");
        // Absent rather than null when the floor is met.
        assert!(value.get("shortfall_reason").is_none());
    }

    /// The grant is reported, and it never moves a class, a floor or a mechanism: the same tier
    /// with four different grants produces four reports that differ in exactly one field.
    #[test]
    fn the_userns_grant_is_reported_without_changing_any_verdict() {
        let baseline = scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Advisory,
            EnforcementTier::KernelSealed,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        );

        for grant in UsernsGrant::ALL {
            let report = scope_report_for_tier(
                &sample_policy(),
                ContainmentClass::Advisory,
                EnforcementTier::KernelSealed,
                None,
                Some(*grant),
                None,
                Vec::new(),
                Vec::new(),
                Vec::new(),
                IoMaxReport::default(),
            );
            assert_eq!(report.achieved_containment, baseline.achieved_containment);
            assert_eq!(report.floor_met, baseline.floor_met);
            assert_eq!(report.enforcement_tier, baseline.enforcement_tier);
            assert_eq!(report.userns_grant, Some(*grant));

            let value: serde_json::Value = serde_json::to_value(&report).unwrap();
            assert_eq!(value["userns_grant"], grant.wire_name());
            assert!(report
                .render()
                .contains(&format!("userns grant: {}", grant.wire_name())));
        }

        // Off Linux the key is present and null — AppArmor does not exist there, which is not the
        // same statement as "the grant was withheld".
        let value: serde_json::Value = serde_json::to_value(&baseline).unwrap();
        assert!(value["userns_grant"].is_null());
        assert!(baseline.render().contains("userns grant: n/a"));
    }

    #[test]
    fn rendered_report_names_both_classes_and_the_refusal() {
        let rendered = scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Sealed,
            EnforcementTier::KernelFull,
            Some(SealedBlocker::AppArmorProfileMissing),
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        )
        .render();

        assert!(rendered.contains("declared:  sealed"));
        assert!(rendered.contains("achieved:  scoped"));
        assert!(rendered.contains("floor met: no"));
        assert!(rendered.contains("mur-sealed"));
        assert!(rendered.contains("would refuse to launch"));
    }

    /// The invariant the whole design rests on: an export is a disclosure, not a grant. Declaring
    /// one must leave the achieved class — and everything else the report says about what the
    /// guest can reach — byte-identical.
    #[test]
    fn an_export_never_changes_what_the_report_says_about_containment() {
        let export = FileExport {
            root: "out/".to_string(),
            mode: ExportMode::ReadOnly,
            max_bytes: 10 * 1024 * 1024,
        };
        for tier in ALL_TIERS {
            for workdir_exec in [false, true] {
                let policy = CapabilityPolicy {
                    workdir_exec_allowed: workdir_exec,
                    ..sample_policy()
                };
                let without = scope_report_for_tier(
                    &policy,
                    ContainmentClass::Scoped,
                    *tier,
                    None,
                    None,
                    None,
                    Vec::new(),
                    Vec::new(),
                    Vec::new(),
                    IoMaxReport::default(),
                );
                let with = scope_report_for_tier(
                    &policy,
                    ContainmentClass::Scoped,
                    *tier,
                    None,
                    None,
                    Some(&Exports {
                        files: Some(export.clone()),
                        peer_files: None,
                    }),
                    Vec::new(),
                    Vec::new(),
                    Vec::new(),
                    IoMaxReport::default(),
                );
                assert_eq!(
                    with.achieved_containment, without.achieved_containment,
                    "tier {tier:?}, workdir_exec {workdir_exec}"
                );
                assert_eq!(with.enforcement_tier, without.enforcement_tier);
                assert_eq!(with.floor_met, without.floor_met);
                assert_eq!(with.shortfall_reason, without.shortfall_reason);
                // Everything but the one new field is identical, which is the strongest form of
                // "an export changes nothing else" this report can state.
                assert_eq!(
                    ScopeReport {
                        exports_files: None,
                        ..with.clone()
                    },
                    without
                );
                assert_eq!(
                    with.exports_files,
                    Some(ExportsFilesReport {
                        root: "out/".to_string(),
                        mode: ExportMode::ReadOnly,
                        max_bytes: 10 * 1024 * 1024,
                    })
                );
            }
        }
    }

    /// The same invariant for the peer-handoff grants, and stated separately because they are a
    /// separate authoriser: declaring either half must leave the achieved class, the tier and the
    /// floor verdict byte-identical, and must change no field of the report but its own.
    #[test]
    fn peer_handoff_never_changes_what_the_report_says_about_containment() {
        let peer_files = PeerFilesExport {
            root: "out/".to_string(),
            max_ttl_secs: Some(900),
            max_bytes: 10 * 1024 * 1024,
        };
        for tier in ALL_TIERS {
            for workdir_exec in [false, true] {
                let without_policy = CapabilityPolicy {
                    workdir_exec_allowed: workdir_exec,
                    ..sample_policy()
                };
                let with_policy = CapabilityPolicy {
                    peer_fetch_allow: vec!["localhost:41234".to_string()],
                    ..without_policy.clone()
                };
                let without = scope_report_for_tier(
                    &without_policy,
                    ContainmentClass::Scoped,
                    *tier,
                    None,
                    None,
                    None,
                    Vec::new(),
                    Vec::new(),
                    Vec::new(),
                    IoMaxReport::default(),
                );
                let with = scope_report_for_tier(
                    &with_policy,
                    ContainmentClass::Scoped,
                    *tier,
                    None,
                    None,
                    Some(&Exports {
                        files: None,
                        peer_files: Some(peer_files.clone()),
                    }),
                    Vec::new(),
                    Vec::new(),
                    Vec::new(),
                    IoMaxReport::default(),
                );
                assert_eq!(
                    with.achieved_containment, without.achieved_containment,
                    "tier {tier:?}, workdir_exec {workdir_exec}"
                );
                assert_eq!(with.enforcement_tier, without.enforcement_tier);
                assert_eq!(with.floor_met, without.floor_met);
                assert_eq!(with.shortfall_reason, without.shortfall_reason);
                assert_eq!(
                    ScopeReport {
                        peer_files: None,
                        peer_fetch_allow: Vec::new(),
                        ..with.clone()
                    },
                    without
                );
                assert_eq!(
                    with.peer_files,
                    Some(PeerFilesReport {
                        root: "out/".to_string(),
                        max_ttl_secs: 900,
                        max_bytes: 10 * 1024 * 1024,
                    })
                );
                assert_eq!(with.peer_fetch_allow, vec!["localhost:41234".to_string()]);
                // Declaring `peer_fetch` does not widen `network.allow`, on either side of the
                // report: the two lists are carried separately and neither is derived from the
                // other.
                assert_eq!(with.network_allow, without.network_allow);
            }
        }
    }

    /// Both peer fields are written whether or not they were declared, on the same terms as
    /// `exports_files`: an absent key identifies an older runtime, a `null`/`[]` identifies a
    /// capsule that declined.
    #[test]
    fn the_peer_fields_are_always_serialized() {
        let undeclared: serde_json::Value = serde_json::to_value(scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Advisory,
            EnforcementTier::KernelSealed,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        ))
        .unwrap();
        assert_eq!(undeclared["peer_files"], serde_json::Value::Null);
        assert_eq!(undeclared["peer_fetch_allow"], serde_json::json!([]));

        let declared: serde_json::Value = serde_json::to_value(scope_report_for_tier(
            &CapabilityPolicy {
                peer_fetch_allow: vec!["localhost:41234".to_string()],
                ..sample_policy()
            },
            ContainmentClass::Advisory,
            EnforcementTier::KernelSealed,
            None,
            None,
            Some(&Exports {
                files: None,
                peer_files: Some(PeerFilesExport {
                    root: "out/".to_string(),
                    max_ttl_secs: None,
                    max_bytes: 10 * 1024 * 1024,
                }),
            }),
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        ))
        .unwrap();
        assert_eq!(
            declared["peer_files"],
            serde_json::json!({"root": "out/", "max_ttl_secs": 3600, "max_bytes": 10_485_760})
        );
        assert_eq!(
            declared["peer_fetch_allow"],
            serde_json::json!(["localhost:41234"])
        );
    }

    #[test]
    fn render_names_peer_handoff_in_both_directions() {
        let undeclared = scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Advisory,
            EnforcementTier::KernelSealed,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        )
        .render();
        assert!(undeclared.contains("Peer handoff"));
        assert!(undeclared.contains("exports.peer_files: <none>"));
        assert!(undeclared.contains("peer_fetch allow: <none>"));

        let declared = scope_report_for_tier(
            &CapabilityPolicy {
                peer_fetch_allow: vec!["localhost:41234".to_string()],
                ..sample_policy()
            },
            ContainmentClass::Advisory,
            EnforcementTier::KernelSealed,
            None,
            None,
            Some(&Exports {
                files: None,
                peer_files: Some(PeerFilesExport {
                    root: "out/".to_string(),
                    max_ttl_secs: Some(900),
                    max_bytes: 4096,
                }),
            }),
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        )
        .render();
        assert!(declared.contains("exports.peer_files root: out/"));
        assert!(declared.contains("max handle ttl:          900s"));
        assert!(declared.contains("max bytes:               4096 (per file)"));
        assert!(declared.contains("- localhost:41234"));
    }

    /// A declared state store is reported, and moves nothing else. Same discipline the export
    /// reports are held to: it is copied through, never consulted, so a durable directory grant
    /// cannot talk a host into reporting a class it does not back.
    #[test]
    fn a_state_store_is_reported_and_moves_no_other_field() {
        let policy = sample_policy();
        let stores = vec![StateStoreReport {
            artifact: "murmur-tool-corpus".to_string(),
            store: "shey".to_string(),
            host_path: "/home/dev/.murmur/state/shey".to_string(),
        }];

        let without = scope_report_for_tier(
            &policy,
            ContainmentClass::Scoped,
            EnforcementTier::KernelFull,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        );
        let with = scope_report_for_tier(
            &policy,
            ContainmentClass::Scoped,
            EnforcementTier::KernelFull,
            None,
            None,
            None,
            stores.clone(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        );

        assert_eq!(with.state_stores, stores);
        assert!(without.state_stores.is_empty());
        assert_eq!(with.achieved_containment, without.achieved_containment);
        assert_eq!(with.floor_met, without.floor_met);
        assert_eq!(with.enforcement_tier, without.enforcement_tier);
        assert_eq!(with.shortfall_reason, without.shortfall_reason);
        // The only field that moved is its own.
        assert_eq!(
            ScopeReport {
                state_stores: Vec::new(),
                ..with.clone()
            },
            without
        );

        // Rendered under the grants, one line per declaring artifact; `<none>` when empty.
        assert!(with
            .render()
            .contains("- murmur-tool-corpus: shey -> /home/dev/.murmur/state/shey"));
        assert!(without.render().contains("state stores: <none>"));

        // Always an array in JSON, never skipped: an absent key means an older runtime, not a
        // capsule that declined a store.
        let json = serde_json::to_value(&without).unwrap();
        assert_eq!(json["state_stores"], serde_json::json!([]));
        assert_eq!(
            serde_json::to_value(&with).unwrap()["state_stores"],
            serde_json::json!([{
                "artifact": "murmur-tool-corpus",
                "store": "shey",
                "host_path": "/home/dev/.murmur/state/shey",
            }])
        );
    }

    /// The preopen set is reported and moves nothing else, on the same terms the state-store
    /// report beside it is held to. It is also the field that answers what `filesystem_scope`
    /// does not: a capsule-wide scope is joined into no guest preopen root, so both can be
    /// present and disagree without either being wrong.
    #[test]
    fn preopens_are_reported_and_move_no_other_field() {
        let policy = sample_policy();
        let preopens = vec![
            PreopenReport {
                artifact: "notes-tool".to_string(),
                role: "tool".to_string(),
                scope: None,
                surface: PreopenSurface::WholeWorkdir,
            },
            PreopenReport {
                artifact: "cache-tool".to_string(),
                role: "tool".to_string(),
                scope: Some("cache".to_string()),
                surface: PreopenSurface::ScopedSubtree,
            },
            PreopenReport {
                artifact: "telemetry-hook".to_string(),
                role: "hook".to_string(),
                scope: None,
                surface: PreopenSurface::Nothing,
            },
        ];

        let without = scope_report_for_tier(
            &policy,
            ContainmentClass::Scoped,
            EnforcementTier::KernelFull,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        );
        let with = scope_report_for_tier(
            &policy,
            ContainmentClass::Scoped,
            EnforcementTier::KernelFull,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            preopens.clone(),
            IoMaxReport::default(),
        );

        assert_eq!(with.preopens, preopens);
        assert!(without.preopens.is_empty());
        // The only field that moved is its own.
        assert_eq!(
            ScopeReport {
                preopens: Vec::new(),
                ..with.clone()
            },
            without
        );

        // Three visibly different lines under `Effective grants`; `<none>` when empty.
        let rendered = with.render();
        assert!(rendered.contains(
            "- notes-tool (tool): the whole accessible workdir — no capabilities.filesystem.scope \
             declared"
        ));
        assert!(rendered.contains(
            "- cache-tool (tool): one subtree of the accessible workdir — \
             capabilities.filesystem.scope: cache"
        ));
        assert!(rendered.contains(
            "- telemetry-hook (hook): nothing preopened — no capabilities.filesystem.scope declared"
        ));
        assert!(without.render().contains("preopens: <none>"));

        // Always an array in JSON, never skipped, with an undeclared scope as `null`.
        assert_eq!(
            serde_json::to_value(&without).unwrap()["preopens"],
            serde_json::json!([])
        );
        assert_eq!(
            serde_json::to_value(&with).unwrap()["preopens"],
            serde_json::json!([
                {
                    "artifact": "notes-tool",
                    "role": "tool",
                    "scope": null,
                    "surface": "whole-workdir",
                },
                {
                    "artifact": "cache-tool",
                    "role": "tool",
                    "scope": "cache",
                    "surface": "scoped-subtree",
                },
                {
                    "artifact": "telemetry-hook",
                    "role": "hook",
                    "scope": null,
                    "surface": "nothing",
                },
            ])
        );
    }

    /// `exports_files` is written whether or not it was declared, on the same terms as
    /// `workdir_exec`: an absent key identifies an older runtime, a `null` a capsule that
    /// exported nothing.
    #[test]
    fn exports_files_is_always_serialized() {
        let undeclared = serde_json::to_value(scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Advisory,
            EnforcementTier::KernelFull,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        ))
        .unwrap();
        assert_eq!(undeclared["exports_files"], serde_json::Value::Null);

        let declared = serde_json::to_value(scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Advisory,
            EnforcementTier::KernelFull,
            None,
            None,
            Some(&Exports {
                files: Some(FileExport {
                    root: "out/".to_string(),
                    mode: ExportMode::ReadOnly,
                    max_bytes: 10_485_760,
                }),
                peer_files: None,
            }),
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        ))
        .unwrap();
        assert_eq!(
            declared["exports_files"],
            serde_json::json!({"root": "out/", "mode": "read-only", "max_bytes": 10_485_760})
        );
    }

    #[test]
    fn render_names_the_resource_plane_in_both_directions() {
        let undeclared = scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Advisory,
            EnforcementTier::KernelFull,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        )
        .render();
        assert!(
            undeclared.contains("Resource plane") && undeclared.contains("exports.files: <none>"),
            "{undeclared}"
        );

        let declared = scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Advisory,
            EnforcementTier::KernelFull,
            None,
            None,
            Some(&Exports {
                files: Some(FileExport {
                    root: "out/".to_string(),
                    mode: ExportMode::ReadOnly,
                    max_bytes: 10_485_760,
                }),
                peer_files: None,
            }),
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        )
        .render();
        assert!(declared.contains("exports.files root: out/"), "{declared}");
        assert!(
            declared.contains("mode:               read-only"),
            "{declared}"
        );
        assert!(
            declared.contains("max bytes:          10485760 (per file)"),
            "{declared}"
        );
    }

    // ── read_only reporting ───────────────────────────────────────────────────

    fn report_for(read_only: &[&str], shell_allow: &[&str]) -> ScopeReport {
        let policy = CapabilityPolicy {
            read_only_paths: read_only.iter().map(|p| (*p).to_string()).collect(),
            shell_allow: shell_allow.iter().map(|b| (*b).to_string()).collect(),
            ..CapabilityPolicy::default()
        };
        scope_report_for_tier(
            &policy,
            ContainmentClass::Scoped,
            EnforcementTier::KernelFull,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        )
    }

    /// With no allowlisted interpreter the declaration holds everywhere the check can reach, and
    /// the report says exactly that and nothing stronger.
    #[test]
    fn declared_read_only_with_no_interpreter_reports_as_enforced() {
        let report = report_for(&["tests", "bench/fixtures"], &["git"]);
        assert_eq!(
            report.read_only_paths,
            vec!["tests".to_string(), "bench/fixtures".to_string()]
        );
        assert!(report.read_only_advisory_for.is_empty());

        let rendered = report.render();
        assert!(rendered.contains("  read_only:\n    - tests\n    - bench/fixtures\n"));
        assert!(rendered.contains(
            "read_only enforcement: enforced for every tool call and every shell command the \
             dispatch check can read"
        ));
        assert!(!rendered.contains("advisory against"));
    }

    /// An allowlisted interpreter is named, and the enforcement line is qualified — the report
    /// must never claim more than `W-SEC-017` already withdraws.
    #[test]
    fn an_allowlisted_interpreter_is_named_as_advisory() {
        let report = report_for(&["tests"], &["git", "python3"]);
        assert_eq!(report.read_only_advisory_for, vec!["python3".to_string()]);

        let rendered = report.render();
        assert!(rendered.contains("read_only enforcement: advisory against python3"));
        assert!(rendered
            .contains("enforced for every tool call and for every shell command it can read"));
    }

    /// The report's advisory set is the set `W-SEC-017` fires for, because both call one
    /// resolver. Asserted through the resolver rather than by re-listing interpreters, so adding
    /// one to `protected_paths::ADVISORY_INTERPRETERS` cannot make the two disagree.
    #[test]
    fn the_reported_advisory_set_is_the_set_the_warning_fires_for() {
        let shell_allow: Vec<String> = ["git", "python3", "node", "make", "bash"]
            .iter()
            .map(|b| (*b).to_string())
            .collect();
        let declared = vec!["tests".to_string()];
        assert_eq!(
            report_for(&["tests"], &["git", "python3", "node", "make", "bash"])
                .read_only_advisory_for,
            read_only_advisory_for(&declared, &shell_allow)
        );
        // Nothing is advisory against a protection that was never declared, whatever is allowed.
        assert!(read_only_advisory_for(&[], &shell_allow).is_empty());
    }

    /// Both keys are always arrays, including for a capsule with no `capabilities.filesystem`
    /// block at all: an absent key must identify a runtime that predates the field, never a
    /// capsule that declared nothing.
    #[test]
    fn both_read_only_keys_are_always_serialized_arrays() {
        let json = serde_json::to_value(report_for(&[], &["python3"])).unwrap();
        assert_eq!(json["read_only_paths"], serde_json::json!([]));
        assert_eq!(json["read_only_advisory_for"], serde_json::json!([]));

        let json = serde_json::to_value(report_for(&["tests"], &["python3"])).unwrap();
        assert_eq!(json["read_only_paths"], serde_json::json!(["tests"]));
        assert_eq!(
            json["read_only_advisory_for"],
            serde_json::json!(["python3"])
        );
    }

    /// An undeclared `read_only` renders one `<none>` line and asks no enforcement question,
    /// because there is no protection to qualify.
    #[test]
    fn an_undeclared_read_only_renders_none_and_no_enforcement_line() {
        let rendered = report_for(&[], &["python3"]).render();
        assert!(rendered.contains("  read_only: <none>\n"));
        assert!(!rendered.contains("read_only enforcement:"));
    }

    // ── Grant coverage ────────────────────────────────────────────────────────

    /// Every `pub` field of [`CapabilityPolicy`] is either reported by [`ScopeReport`] or
    /// exempted here with a written reason.
    ///
    /// The field list is derived from `types.rs`'s own source text rather than written out, so a
    /// grant added later fails this test until someone decides which it is.
    ///
    /// The mapping is checked in both directions — every policy field is accounted for, *and*
    /// every report key the mapping names is really present in a serialized report — so the
    /// table cannot claim coverage it does not have.
    #[test]
    fn every_capability_policy_field_is_reported_or_exempted() {
        /// Policy fields deliberately absent from the scope report, each with the reason.
        const EXEMPT: &[(&str, &str)] = &[
            (
                "shell_strip_env",
                "Names host variables removed from the shell child's environment on top of the \
                 credential patterns the runtime always strips. It subtracts from what the \
                 capsule sees and can open nothing, so reporting it beside the grants would pad \
                 the list an operator audits for reach.",
            ),
            (
                "shell_baseline_env",
                "The fixed variables the shell child starts with (PATH, HOME, …). It shapes the \
                 environment of a subprocess the capsule was already granted, and names no host \
                 resource `shell allow` and `env allow` do not already account for.",
            ),
            (
                "limits",
                "Execution ceilings for a WASM guest — memory, table elements, instance count, \
                 deadline. A bound on how much the capsule may consume, never a reach it gains.",
            ),
            (
                "resources",
                "The same, for native subprocesses: rlimits, the Linux cgroup v2 scope and the \
                 workdir size ceiling. A ceiling, not a grant, on exactly `limits`' terms.",
            ),
            (
                "declared_deadline_seconds",
                "The undefaulted form of `limits.deadline_seconds`, retained only so hook calls \
                 can apply a lower default. Reporting it would report one ceiling twice.",
            ),
            (
                "state_declared",
                "Records that a capsule-wide `capabilities.state` block was declared where \
                 nothing reads it, which `W-SEC-014` says in words. The stores that actually \
                 exist are reported per artifact in `state_stores`.",
            ),
            (
                "conversation_declared",
                "Records a capsule-wide `capabilities.conversation` block that reaches no \
                 artifact, on `state_declared`'s terms; `W-SEC-016` is what an operator needs, \
                 and the grant itself is per artifact.",
            ),
        ];

        /// Policy field → the key it is reported under in a serialized [`ScopeReport`].
        const REPORTED: &[(&str, &str)] = &[
            ("network_allow", "network_allow"),
            ("peer_fetch_allow", "peer_fetch_allow"),
            ("unix_sockets_allowed", "unix_sockets"),
            ("filesystem_scope", "filesystem_scope"),
            ("workdir_exec_allowed", "workdir_exec"),
            ("read_only_paths", "read_only_paths"),
            ("shell_allow", "shell_allow"),
            ("spawn_allow", "spawn_allow"),
            ("shell_interpreter_runtime", "interpreter_runtime_grants"),
            ("shell_staged_runtime", "staged_runtime_grants"),
            ("env_allow", "env_allow"),
            ("plan_submit", "plan_submit"),
            ("containment_floor", "declared_containment"),
        ];

        let declared = capability_policy_field_names(include_str!("types.rs"));
        assert!(
            declared.len() > 10,
            "failed to read CapabilityPolicy's fields out of types.rs (found {declared:?})"
        );

        for field in &declared {
            let reported = REPORTED.iter().any(|(policy, _)| policy == field);
            let exempt = EXEMPT.iter().any(|(policy, _)| policy == field);
            assert!(
                reported || exempt,
                "CapabilityPolicy::{field} is a grant no --explain-scope report mentions. Either \
                 add it to ScopeReport and to this test's REPORTED table, or add it to EXEMPT \
                 with a written reason for why an operator does not need to see it."
            );
            assert!(
                !(reported && exempt),
                "CapabilityPolicy::{field} is listed as both reported and exempt"
            );
        }

        for (policy_field, _) in REPORTED.iter().chain(EXEMPT.iter()) {
            assert!(
                declared.iter().any(|field| field == policy_field),
                "the table names CapabilityPolicy::{policy_field}, which types.rs no longer \
                 declares — remove the stale row"
            );
        }

        // The other direction: a report key the table claims must really be in the JSON, so no
        // row can cover a field with a key that does not exist.
        let json = serde_json::to_value(scope_report_for_tier(
            &sample_policy(),
            ContainmentClass::Scoped,
            EnforcementTier::KernelFull,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        ))
        .unwrap();
        let object = json.as_object().expect("a scope report is a JSON object");
        for (policy_field, report_key) in REPORTED {
            assert!(
                object.contains_key(*report_key),
                "the table maps CapabilityPolicy::{policy_field} to a report key \
                 '{report_key}' that a serialized ScopeReport does not carry"
            );
        }
    }

    /// A report off [`sample_policy`] at a chosen host tier and declared floor, so the mechanism
    /// this session would install is the only thing that varies between the cases below.
    fn boundary_report(declared: ContainmentClass, tier: EnforcementTier) -> ScopeReport {
        scope_report_for_tier(
            &sample_policy(),
            declared,
            tier,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        )
    }

    /// A host that mediates nothing says so, in the block an operator reads before the grants.
    #[test]
    fn a_session_with_no_kernel_mechanism_reports_what_it_does_not_protect() {
        let report = boundary_report(ContainmentClass::Advisory, EnforcementTier::EnvironmentOnly);

        assert_eq!(report.achieved_containment, ContainmentClass::Advisory);
        assert_eq!(
            report.filesystem_boundary.restriction,
            FilesystemRestriction::Advisory
        );
        assert_eq!(report.filesystem_boundary.not_protected.len(), 2);

        let filesystem = &report.filesystem_boundary.not_protected[0];
        assert!(filesystem.contains("advisory"), "{filesystem}");
        assert!(
            filesystem.contains("denies a read or a write outside the session workdir"),
            "{filesystem}"
        );

        let rewriting = &report.filesystem_boundary.not_protected[1];
        assert!(rewriting.contains("not a boundary"), "{rewriting}");
        assert!(rewriting.contains("HOME"), "{rewriting}");

        let rendered = report.render();
        let heading = rendered
            .find("\nNot protected here\n")
            .expect("a session that composes no root prints the block");
        assert!(
            heading > rendered.find("Containment\n").unwrap(),
            "the block belongs under Containment:\n{rendered}"
        );
        assert!(
            heading < rendered.find("\nEffective grants\n").unwrap(),
            "the block belongs ahead of the grants an operator reads it against:\n{rendered}"
        );
        for statement in &report.filesystem_boundary.not_protected {
            assert!(rendered.contains(statement.as_str()), "{rendered}");
        }
    }

    /// A Landlock domain really does mediate the filesystem, so its statement says what Landlock
    /// leaves open rather than repeating the advisory one.
    #[test]
    fn a_landlock_session_reports_denial_rather_than_absence() {
        let report = boundary_report(ContainmentClass::Advisory, EnforcementTier::KernelFull);

        assert_eq!(report.achieved_containment, ContainmentClass::Scoped);
        assert_eq!(
            report.filesystem_boundary.restriction,
            FilesystemRestriction::Enforced
        );
        assert_eq!(report.filesystem_boundary.not_protected.len(), 2);

        let filesystem = &report.filesystem_boundary.not_protected[0];
        assert!(
            !filesystem.contains("advisory"),
            "Landlock mediates the filesystem here: {filesystem}"
        );
        assert!(
            filesystem.contains("denied rather than absent"),
            "{filesystem}"
        );
        for probe in ["stat", "access", "readlink"] {
            assert!(filesystem.contains(probe), "{filesystem}");
        }
    }

    /// A capsule that declares less than `sealed` composes no root on a sealed-capable host: it
    /// runs Landlock-scoped, and the block must say so rather than claim the paths outside its
    /// grants are absent. This is the configuration `achieved_containment` cannot distinguish —
    /// it reads `sealed` on both sides of this test.
    #[test]
    fn a_sealed_capable_host_still_discloses_landlock_for_a_capsule_that_declared_less() {
        let report = boundary_report(ContainmentClass::Advisory, EnforcementTier::KernelSealed);

        assert_eq!(
            report.achieved_containment,
            ContainmentClass::Sealed,
            "the host can back sealed, which is what `achieved` answers"
        );
        assert_eq!(
            report.filesystem_boundary.restriction,
            FilesystemRestriction::Enforced,
            "no composed root is installed for a capsule that did not declare one"
        );
        assert_eq!(
            report.filesystem_boundary.not_protected,
            boundary_report(ContainmentClass::Advisory, EnforcementTier::KernelFull)
                .filesystem_boundary
                .not_protected,
            "the same mechanism gets the same statements on either host"
        );
        assert!(report.render().contains("Not protected here"));
    }

    /// The half of the block that is genuinely mechanism-independent: `HOME` is rewritten on every
    /// tier, so the statement about it is one string, not one per mechanism.
    #[test]
    fn the_path_rewriting_statement_is_identical_wherever_it_is_carried() {
        let advisory =
            boundary_report(ContainmentClass::Advisory, EnforcementTier::EnvironmentOnly);
        let enforced = boundary_report(ContainmentClass::Advisory, EnforcementTier::KernelFull);

        assert_eq!(
            advisory.filesystem_boundary.not_protected[1],
            enforced.filesystem_boundary.not_protected[1]
        );
        assert!(
            advisory.filesystem_boundary.not_protected[1]
                .contains(crate::shell::SYNTHETIC_HOME_DIR_NAME),
            "the statement must name the directory `shell::build_shell_env` really sets HOME to"
        );
    }

    /// A composed root prints no heading — not a heading with an empty list under it — and still
    /// carries the key, because an absent key must identify a runtime that predates the field.
    #[test]
    fn a_composed_root_carries_the_key_with_nothing_to_disclaim() {
        let report = boundary_report(ContainmentClass::Sealed, EnforcementTier::KernelSealed);

        assert_eq!(report.achieved_containment, ContainmentClass::Sealed);
        assert_eq!(
            report.filesystem_boundary.restriction,
            FilesystemRestriction::Absent
        );
        assert!(report.filesystem_boundary.not_protected.is_empty());
        assert!(
            !report.render().contains("Not protected here"),
            "{}",
            report.render()
        );

        let json = serde_json::to_value(&report).unwrap();
        assert_eq!(json["filesystem_boundary"]["restriction"], "absent");
        assert_eq!(
            json["filesystem_boundary"]["not_protected"],
            serde_json::json!([]),
            "the key is present and empty at absent, never missing"
        );
    }

    /// `capabilities.filesystem.workdir_exec` caps the achieved *class* at `advisory` and leaves
    /// the *mechanism* alone: Landlock is still installed, so the block prints the Landlock
    /// statement rather than claiming the host denies nothing.
    #[test]
    fn workdir_exec_caps_the_class_without_changing_the_mechanism() {
        let policy = CapabilityPolicy {
            workdir_exec_allowed: true,
            ..CapabilityPolicy::default()
        };

        let report = scope_report_for_tier(
            &policy,
            ContainmentClass::Advisory,
            EnforcementTier::KernelSealed,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            IoMaxReport::default(),
        );

        assert_eq!(
            report.enforcement_tier,
            "mountns+pivot_root+landlock+seccomp"
        );
        assert_eq!(report.achieved_containment, ContainmentClass::Advisory);
        assert_eq!(
            report.filesystem_boundary.restriction,
            FilesystemRestriction::Enforced
        );
        assert_eq!(report.filesystem_boundary.not_protected.len(), 2);
        assert!(report.render().contains("Not protected here"));
    }

    /// The restriction follows the tier the session applies, at every combination of host tier and
    /// declared floor — which is what `runtime_writes` beside it is already keyed on.
    #[test]
    fn the_restriction_follows_the_tier_the_session_would_install() {
        for tier in ALL_TIERS {
            for declared in [
                ContainmentClass::Advisory,
                ContainmentClass::Scoped,
                ContainmentClass::Sealed,
            ] {
                let report = boundary_report(declared, *tier);
                let expected = match crate::sandbox::applied_tier(*tier, declared) {
                    EnforcementTier::KernelSealed => FilesystemRestriction::Absent,
                    EnforcementTier::KernelFull => FilesystemRestriction::Enforced,
                    EnforcementTier::KernelSeccompOnly | EnforcementTier::EnvironmentOnly => {
                        FilesystemRestriction::Advisory
                    }
                };
                assert_eq!(
                    report.filesystem_boundary.restriction, expected,
                    "{tier:?} / {declared:?}"
                );
                assert_eq!(
                    report.filesystem_boundary.not_protected.is_empty(),
                    expected == FilesystemRestriction::Absent,
                    "{tier:?} / {declared:?}"
                );
                let wire = match expected {
                    FilesystemRestriction::Advisory => "advisory",
                    FilesystemRestriction::Enforced => "enforced",
                    FilesystemRestriction::Absent => "absent",
                };
                assert_eq!(
                    serde_json::to_value(report.filesystem_boundary.restriction).unwrap(),
                    serde_json::Value::String(wire.to_string())
                );
            }
        }
    }

    /// The one assertion the report cannot satisfy by agreeing with itself: what a subprocess in a
    /// real session actually gets back when it probes a host file outside its workdir, compared
    /// against the `restriction` the report prints for that same session.
    ///
    /// Runs on whatever tier this host reaches, and asserts against the restriction it observes
    /// rather than against a tier it assumes. `bash` reads the file with a redirect and tests its
    /// existence with `[[ -e ]]` — both are syscalls the shell makes itself, so nothing here needs
    /// a second binary on the exec allowlist.
    ///
    /// Driving `execute_shell` needs an egress network namespace, so it stands down where the host
    /// withholds one rather than failing: a host that restricts unprivileged user namespaces
    /// refuses the uid_map write every spawn goes through, whatever the filesystem tier.
    #[test]
    fn the_reported_restriction_matches_what_a_subprocess_actually_reaches() {
        if crate::network_namespace::skip_without_egress_namespace(
            "the_reported_restriction_matches_what_a_subprocess_actually_reaches",
        ) {
            return;
        }
        if crate::sandbox::find_on_path("bash").is_none() {
            eprintln!(
                "[SKIP-HOST] the_reported_restriction_matches_what_a_subprocess_actually_reaches: \
                 no bash on PATH"
            );
            return;
        }
        let outside = tempfile::tempdir().expect("a temp directory outside the workdir");
        let secret = outside.path().join("host-file");
        std::fs::write(&secret, "PROBE-CONTENTS\n").unwrap();
        let secret = secret.to_str().unwrap().to_string();

        for declared in [ContainmentClass::Advisory, ContainmentClass::Sealed] {
            let workdir = tempfile::tempdir().unwrap();
            let policy = CapabilityPolicy {
                shell_allow: vec!["bash".to_string()],
                ..CapabilityPolicy::default()
            };
            let probe = crate::sandbox::HostProbe::probe();
            let enforcement =
                crate::sandbox::ShellEnforcement::resolve(&policy, declared, probe).unwrap();
            let report = scope_report_for_tier(
                &policy,
                declared,
                probe.tier(),
                None,
                None,
                None,
                Vec::new(),
                Vec::new(),
                Vec::new(),
                IoMaxReport::default(),
            );

            let command = format!(
                "if read -r line < '{secret}' 2>/dev/null; then echo \"read=$line\"; \
                 else echo read=refused; fi; \
                 if [[ -e '{secret}' ]]; then echo exists=yes; else echo exists=no; fi"
            );
            let result = crate::shell::execute_shell(
                "bash",
                &["-c", &command],
                &[],
                workdir.path(),
                workdir.path(),
                &policy,
                &enforcement,
            )
            .unwrap_or_else(|error| panic!("declared {declared:?}: {error}"));
            let seen = result.stdout;

            match report.filesystem_boundary.restriction {
                FilesystemRestriction::Advisory => assert!(
                    seen.contains("read=PROBE-CONTENTS"),
                    "reported advisory, so nothing denies the read: {seen}"
                ),
                FilesystemRestriction::Enforced => assert!(
                    seen.contains("read=refused") && seen.contains("exists=yes"),
                    "reported enforced, so the read is denied and the path still exists: {seen}"
                ),
                FilesystemRestriction::Absent => assert!(
                    seen.contains("read=refused") && seen.contains("exists=no"),
                    "reported absent, so the path is not in the composed root: {seen}"
                ),
            }
        }
    }

    /// The `pub` field names of `CapabilityPolicy`, read out of `types.rs`'s own text.
    fn capability_policy_field_names(source: &str) -> Vec<String> {
        source
            .split_once("pub struct CapabilityPolicy {")
            .expect("types.rs declares CapabilityPolicy")
            .1
            .split_once("\n}")
            .expect("CapabilityPolicy's declaration is closed at column 0")
            .0
            .lines()
            .filter_map(|line| {
                line.strip_prefix("    pub ")
                    .and_then(|rest| rest.split_once(':'))
                    .map(|(name, _)| name.to_string())
            })
            .collect()
    }
}