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
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
use std::{
    collections::{HashMap, HashSet},
    fs,
    path::{Path, PathBuf},
    sync::{
        atomic::{AtomicBool, AtomicU64, Ordering},
        Arc, Mutex,
    },
    time::Instant,
};

use murmur_artifact::{
    current_platform, is_credential_shaped_env_name, native_binary_verdict,
    parse_hook_config_from_yaml, parse_tool_implementation_from_yaml, read_lockfile,
    security_warning_link, verify_sha256, write_lockfile_atomic, AfterTask, ApiKeyReference,
    ArtifactImplementation, ArtifactRuntime, ContextConfig, ConversationMode, HookBinding,
    InferenceConfig, InterpreterRuntimeGrant, LifecycleConfig, LockedSha256, LockfileError,
    MurmurLock, NativeBinaryVerdict, Registry, RegistryError, RuntimeType, TaskAcceptance,
    LOCK_VERSION, MANIFEST_FILENAME, PACKED_MANIFEST_ENTRY, W_SEC_003, W_SEC_006, W_SEC_007,
    W_SEC_008, W_SEC_009, W_SEC_011, W_SEC_013, W_SEC_014, W_SEC_015, W_SEC_016, W_SEC_017,
    W_SEC_018, W_SEC_020, W_SEC_022, W_SEC_023, W_SEC_024, W_SEC_025, W_SEC_026, W_SEC_027,
};
use serde_yaml::Value;
use wasmtime::{
    component::{Component, HasSelf, Linker, ResourceTable},
    Config, Engine, Store,
};
use wasmtime_wasi::{DirPerms, FilePerms, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
use wasmtime_wasi_http::{
    p2::{
        bindings::http::types::ErrorCode as WasiHttpErrorCode,
        body::HyperOutgoingBody,
        types::{HostFutureIncomingResponse, OutgoingRequestConfig},
        HttpResult, WasiHttpCtxView, WasiHttpHooks, WasiHttpView,
    },
    WasiHttpCtx,
};

use crate::{
    a2a::{IncomingTask, TaskRegistry, TaskState},
    agent::{self, AgentLoopExit},
    artifact::{extract_manifest_yaml, extract_native_binary, extract_root_wasm, extract_skill_md},
    artifact_config::ARTIFACT_CONFIG_ENV,
    bindings::host::murmur::{
        self, artifact_manager::manage, message::send, tool_registry::invoke,
    },
    cgroup,
    containment::{achieved_containment_class, check_containment_floor},
    delegation::SpawnerHandle,
    detached::{
        self, demotion_tool_result, AbandonedDisposition, AbandonedWork, DetachPolicy,
        DetachedRegistry, DetachedReport,
    },
    errors::RuntimeError,
    hooks::{
        dispatch_stage, HookEnvVars, HookEvent, HookRuntime, HookSeed, ResolvedCall,
        SessionContextData, ShellDispatchInfo, TaskReopen,
    },
    identity::{self, CapsuleIdentity},
    inference_credential::{config_holds_credential, InferenceCredential},
    inference_gateway::InferenceGateway,
    inference_import::HookInferenceCtx,
    lanes::LaneQueue,
    limits::{classify_guest_failure, EpochTicker, ExecutionLimiter, GuestFailure},
    murmur_md,
    network_policy::{
        effective_tool_network_rules, parse_network_allow_rules, resolve_scoped_dir,
        validate_filesystem_scope, HookCapabilityGrant, NetworkAllowRule, RequestTarget,
        ToolCapabilityGrant,
    },
    origin::{stamp_for_peer, TaskOrigin, TaskProvenance, TrustClass},
    otel::OtelEmitter,
    outgoing,
    protected_paths::{ProtectedPathRefusal, ProtectedPaths},
    registration::SessionOutcome,
    resources, running, sandbox,
    sealed::UsernsGrant,
    shell::{
        build_shell_env, build_wasi_env_allowlist, is_shell_interpreter, run_shell,
        shell_tool_manifest_yaml, split_shell_words, ShellOutcome, ShellResult,
    },
    spawn_credential::SpawnCredential,
    spend::{MachineLedger, SpendMeter},
    state_store::STATE_PREOPEN_NAME,
    streaming::{
        emit_chunk_sse, emit_sse, emit_thinking_chunk_sse, SseBroadcast, SseEventBuffer,
        StreamStatus, TaskStatusUpdateEvent,
    },
    tool_annotations::ToolAnnotationMap,
    trace::TraceWriter,
    types::{
        ArtifactRequest, CapabilityPolicy, DispatchOutcome, InstalledArtifactSummary, LaunchResult,
        ResolvedLockArtifact, ResumeMode, ResumeRequest, StageRequest, StagedHookArtifact,
        StagedSession,
    },
};

/// Versioned instance export name a guest built against the semver'd
/// `murmur:capsule@0.1.0` WIT package carries. This is the only name the host
/// resolves — the legacy unversioned fallback was removed after the dual-accept
/// runtime shipped (see `wit/VERSIONING.md`).
const WIT_CAPSULE_IFACE_VERSIONED: &str = "murmur:capsule/run@0.1.0";
/// Versioned instance export name a guest built against `murmur:tool@0.1.0`
/// carries. Only name the host resolves; see `WIT_CAPSULE_IFACE_VERSIONED`.
const WIT_TOOL_IFACE_VERSIONED: &str = "murmur:tool/run@0.1.0";

/// The host provides its guest-facing *import* interfaces under the versioned
/// instance name only. The legacy unversioned provisions were dropped after the
/// dual-accept runtime shipped; a guest importing only the
/// unversioned name now fails to link. See `wit/VERSIONING.md`.
const WIT_TOOL_REGISTRY_IFACE: &str = "murmur:tool-registry/invoke@0.1.0";
const WIT_TEXT_CHUNKS_IFACE: &str = "murmur:text/chunks@0.1.0";
const WIT_TASK_IFACE: &str = "murmur:task/task@0.1.0";

/// How long an agent session's teardown may run after the first `SIGTERM` before the process
/// exits with status 143 regardless.
///
/// Longer than the async-hook drain budget (`ASYNC_HOOK_DRAIN_TIMEOUT` in `hooks.rs`, 15 s), so a
/// drain that stays inside its own bound is never cut short by this one. A second `SIGTERM`
/// exits at once without waiting for either.
const TERMINATE_TEARDOWN_DEADLINE: std::time::Duration = std::time::Duration::from_secs(20);

/// Resolve a guest interface instance export by its versioned name. Returns
/// `None` when the versioned name is absent, so a component that exports only
/// the legacy unversioned name (or no recognizable name) surfaces as the
/// missing-export error at the call site. See `wit/VERSIONING.md`.
fn resolve_versioned_iface<T>(
    instance: &wasmtime::component::Instance,
    store: &mut Store<T>,
    versioned: &str,
) -> Option<wasmtime::component::ComponentExportIndex> {
    instance.get_export_index(&mut *store, None, versioned)
}

/// Run one task's agent loop, honoring `on-task-end` `reopen-task` control decisions.
///
/// Fires `on-task-end` after every attempt (via [`HookRuntime::dispatch_task_end`]). If
/// a blocking hook returns `reopen-task(reason)` and both budgets still allow it — fewer
/// than `max_task_reopens` (the manifest's `lifecycle.max_task_reopens`) reopens used AND
/// cumulative task turns still below `inference.max_turns` — the task's
/// `accessible_workdir/task.md` is rewritten as the original content plus every reopen's
/// feedback so far, a `task_reopened` trace record is written, and the loop runs again.
/// Reopening shares one cumulative turn budget with the original attempt: each attempt is
/// handed only `max_turns - task_turns()` turns, so the whole task can never exceed the
/// capsule's turn ceiling.
///
/// Writes the terminal `task_end` record (carrying the final `reopen_count`) itself, and
/// the terminal `on-task-end` dispatch is simply the loop's last one. Returns the task's
/// final result: the last attempt's own result when a hook was satisfied (or none was
/// bound), or `Err` when a hook still wanted to reopen but the reopen budget or turn
/// ceiling was reached — so every existing `.is_err()` branch at the call sites treats an
/// exhausted reopen as a failed task. In that case the terminal record's `exit_status` is
/// `"reopen_budget_exhausted"`; otherwise it is the last attempt's `"ok"`/`"failed"`.
///
/// `seed` is whatever the task's single `on-task-start` dispatch proposed, handed to every
/// attempt so a reopened task starts from the same context as its first run.
///
/// `agent_task_id` is what [`agent::run_agent_loop`] receives (governs A2A SSE emission);
/// `trace_task_id` is the id used for the `task_start`/`task_reopened`/`task_end` records
/// and the `on-task-end` hook event. The two coincide on the A2A path and differ on the
/// backward-compat `task.md` paths, which pass `agent_task_id = None`.
#[allow(clippy::too_many_arguments)]
async fn run_task_with_reopens(
    state: &mut CapsuleStoreState,
    workdir: &Path,
    inference: &InferenceConfig,
    max_task_reopens: u32,
    system_prompt: Option<String>,
    run_config: agent::AgentRunConfig,
    hooks: &mut HookRuntime,
    trace: &mut TraceWriter,
    otel: &mut OtelEmitter,
    agent_task_id: Option<String>,
    sse: Option<(SseBroadcast, Arc<Mutex<SseEventBuffer>>)>,
    accessible_workdir: &Path,
    capsule_name: &str,
    capsule_version: &str,
    mode: ConversationMode,
    context_id: Option<String>,
    trace_task_id: &str,
    seed: Option<HookSeed>,
    // This task's cancel flag, or `None` on the `task.md` paths, which run no A2A task.
    cancel: Option<crate::cancel::CancelSignal>,
) -> Result<AgentLoopExit, RuntimeError> {
    let task_md_path = accessible_workdir.join("task.md");
    // Original task content, captured once before any feedback is appended, so repeated
    // reopens re-inject a fresh copy of every feedback item rather than compounding.
    let original_task = tokio::fs::read_to_string(&task_md_path)
        .await
        .unwrap_or_default();
    // Every reopen's (hook_name, reason) so far — all re-injected on each reopen.
    let mut feedback: Vec<(String, String)> = Vec::new();
    let mut reopens_used: u32 = 0;
    // Exactly the bytes the next attempt's agent loop will be handed, tracked alongside the
    // `task.md` writes below so `murmur:task-io/read`'s `as-given` form is what the model saw
    // rather than a re-read of a file whose path is a convention.
    let mut as_given = original_task.clone();

    loop {
        // This function owns the task's scope: nothing else puts a task in scope, which is why
        // the "no A2A message arrived" bypass path — a direct `run_agent_loop` call that
        // dispatches no `on-task-end` — correctly reports `no-task` to a hook.
        hooks.begin_task_attempt(original_task.clone(), as_given.clone());

        // Reopening never grants turns past `max_turns`: hand this attempt only the turns
        // still unspent by prior attempts of the same task. On the first attempt
        // `task_turns()` is 0 (reset by the preceding `write_task_start`), so it gets the
        // full ceiling.
        let remaining_turns = inference.max_turns.saturating_sub(trace.task_turns());
        let mut attempt_inference = inference.clone();
        attempt_inference.max_turns = remaining_turns;

        let result = agent::run_agent_loop(
            state,
            workdir,
            &attempt_inference,
            system_prompt.clone(),
            run_config.clone(),
            hooks,
            trace,
            otel,
            agent_task_id.clone(),
            sse.clone(),
            accessible_workdir,
            capsule_name,
            capsule_version,
            mode.clone(),
            context_id.clone(),
            // Cloned per attempt rather than moved into the first: a reopened task re-runs
            // the same task, so every attempt must start from the same context the hook
            // proposed. The hook is dispatched once, at task start, and is not asked again.
            seed.clone(),
            cancel.clone(),
        )
        .await;

        // Stands in for work between `task_canceled` and `task_end` — a slow `on-task-end` hook —
        // so a test can hold a capsule in that window. Absent from release builds.
        #[cfg(debug_assertions)]
        {
            if let Some(ms) = std::env::var("MURMUR_DEBUG_TASK_END_DELAY_MS")
                .ok()
                .and_then(|value| value.parse::<u64>().ok())
            {
                tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
            }
        }

        // The attempt's own terminal outcome, not a coarse ok/failed: an agent loop that
        // burned its turn budget reports `max_turns_reached`, and this is the only record
        // that keeps it.
        let exit_str = match &result {
            Ok(exit) => exit.as_str(),
            Err(_) => "failed",
        };

        // Let the `on-task-end` hooks inspect this attempt and decide whether to reopen.
        let reopen = hooks
            .dispatch_task_end(trace_task_id.to_string(), exit_str.to_string())
            .await;

        // A cancelled attempt is not reopened. The hook still saw it — `on-task-end` is
        // dispatched above with exit status `canceled` — but re-running work a person just
        // stopped is the defect this refusal exists to prevent.
        let canceled = matches!(result, Ok(AgentLoopExit::Canceled));
        match reopen.filter(|_| !canceled) {
            Some(TaskReopen { hook_name, reason }) => {
                // A hook wants more. Honor it only if a reopen remains in the budget AND
                // turns remain under the ceiling; otherwise the request is exhausted and
                // ends the task non-silently.
                let budget_ok = reopens_used < max_task_reopens;
                let turns_ok = trace.task_turns() < inference.max_turns;
                if budget_ok && turns_ok {
                    reopens_used += 1;
                    feedback.push((hook_name.clone(), reason.clone()));
                    let _ = trace
                        .write_task_reopened(trace_task_id, &hook_name, &reason, reopens_used)
                        .await;
                    // Rewrite task.md as original + all feedback so far; the resumed
                    // attempt picks it up through its normal `read_task`, so neither
                    // transport's message-building code needs to change.
                    let rewritten = build_reopen_task_md(&original_task, &feedback);
                    if let Err(e) = tokio::fs::write(&task_md_path, rewritten.as_bytes()).await {
                        eprintln!(
                            "[capsule-runtime] failed to inject reopen feedback into task.md: {e}"
                        );
                    }
                    as_given = rewritten;
                    continue;
                }
                // Budget or turn ceiling reached while a hook still wanted to reopen: end
                // the task as a distinct, non-silent failure rather than an ordinary
                // completion. `Err` keeps every existing `.is_err()` downstream branch.
                let _ = trace
                    .write_task_end(trace_task_id, "reopen_budget_exhausted", reopens_used)
                    .await;
                hooks.end_task();
                return Err(RuntimeError::AgentLoopFailed(format!(
                    "task reopen budget exhausted after {reopens_used} reopen(s): hook \
                     '{hook_name}' still requested another reopen"
                )));
            }
            None => {
                // No hook asked to reopen — this attempt is terminal.
                let _ = trace
                    .write_task_end(trace_task_id, exit_str, reopens_used)
                    .await;
                hooks.end_task();
                return result;
            }
        }
    }
}

/// Compose the reopened task's `task.md`: the original task content followed by a clearly
/// delimited feedback section for every reopen so far, each naming the hook that produced
/// it. Used by [`run_task_with_reopens`].
fn build_reopen_task_md(original: &str, feedback: &[(String, String)]) -> String {
    let mut out = original.trim_end().to_string();
    out.push_str(
        "\n\n---\n\n# Reopen feedback\n\nThe previous attempt was not accepted. Address the \
         following feedback, then continue.\n",
    );
    for (i, (hook_name, reason)) in feedback.iter().enumerate() {
        out.push_str(&format!(
            "\n## Reopen {} — from hook `{}`\n\n{}\n",
            i + 1,
            hook_name,
            reason.trim()
        ));
    }
    out
}

/// Live-delivery buffer: only needs to cover the lag between fastest and slowest
/// currently-connected reader.
const SSE_BROADCAST_CAPACITY: usize = 128;

/// Replay buffer: covers observers joining mid-task. Sized to handle the longest
/// expected task turn without eviction. Can be tuned independently of broadcast capacity.
/// Candidate for `LifecycleConfig` if operator tuning is needed in a future slice.
const SSE_REPLAY_CAPACITY: usize = 512;

/// Whether any staged hook can receive the `on-compaction` lifecycle event. Mirrors the
/// binding match the runtime uses when it actually dispatches compaction, so MURMUR.md's
/// "compaction configured" status reflects the real dispatch path rather than an artifact name.
fn has_compaction_hook(hooks: &[StagedHookArtifact]) -> bool {
    hooks.iter().any(|h| {
        matches!(
            h.config.binding,
            HookBinding::OnCompaction | HookBinding::All
        )
    })
}

/// Whether `mur run --resume` can do what it was asked, checked at staging so a launch that
/// cannot continue anything never creates a session directory.
///
/// Two ways to be unlaunchable, and each is refused rather than degraded: `compact` with nothing
/// bound to `on-compaction` has nothing to produce the summary, and a context with no record on
/// disk has nothing to continue. Silently falling back to `full`, or starting fresh, would both
/// be indistinguishable to the operator from a resume that worked.
fn check_resume_launchable(
    resume: &ResumeRequest,
    context_id: Option<&str>,
    context: Option<&ContextConfig>,
    capsule_name: &str,
    inference: Option<&InferenceConfig>,
    hooks: &[StagedHookArtifact],
) -> Result<(), RuntimeError> {
    if resume.mode == ResumeMode::Compact && !has_compaction_hook(hooks) {
        return Err(RuntimeError::ResumeCompactionHookMissing);
    }
    // A resume that reached staging with no context id resolved nothing, so there is no record to
    // look for; the placeholder keeps the refusal's wording honest about that.
    let context_id = context_id.unwrap_or("<unresolved>").to_string();
    let missing = |reason: String| RuntimeError::ResumeRecordMissing {
        session: resume.from_session.clone(),
        context_id: context_id.clone(),
        reason,
    };
    // The same three ways `resolve_conversation_root` returns `None`, plus the two this check
    // adds: a capsule with no `inference:` block at all, and a record path that resolves but
    // holds no file.
    let Some(inference) = inference else {
        return Err(missing(
            "the capsule declares no inference block and keeps no conversation record".to_string(),
        ));
    };
    if inference.transport == "process" {
        return Err(missing(
            "the capsule declares inference.transport: process, whose CLI owns its own \
             conversation, and kept no conversation record"
                .to_string(),
        ));
    }
    let Some(record) = crate::conversation::resolve_record_name(context, capsule_name) else {
        return Err(missing(
            "the capsule declares context.record: off and kept no conversation record".to_string(),
        ));
    };
    let root = crate::conversation::record_root(&record).map_err(&missing)?;
    let path = crate::conversation::record_file(&root, &context_id);
    if !path.is_file() {
        return Err(missing(format!(
            "no conversation record at {}",
            path.display()
        )));
    }
    Ok(())
}

/// Resolves and verifies all artifacts, compiles components, and prepares session state.
///
/// This function is intentionally separate from `launch_session` so policy/capability
/// checks can be layered in the seam between stage and launch without mixing concerns.
pub fn stage_session(
    registry: Arc<dyn Registry>,
    request: StageRequest,
) -> Result<StagedSession, RuntimeError> {
    validate_capability_policy(&request.capability_policy)?;
    // Before any registry pull, component compile or workdir creation: if this host cannot
    // back the declared floor, refuse rather than launch something weaker than was asked for.
    // `achieved` comes from a live kernel probe only — the manifest never gets a vote in what
    // the host is reported to provide.
    // `achieved` is the host's live kernel probe, capped by the one manifest property that can
    // lower it: `capabilities.filesystem.workdir_exec`. The manifest still gets no vote in what the
    // host is *reported* to provide — the cap can only ever subtract (see
    // `containment::achieved_containment_class`).
    let workdir_exec = request.capability_policy.workdir_exec_allowed;
    // The host is probed exactly once per session, right here, and every later consumer — the
    // refusal below, the `ScopeReport` recorded in the trace, and the tier `launch_session`
    // installs — reads this one value. A second probe could read differently from the first (an
    // AppArmor profile loaded, a container's capabilities changed), and the trace would then
    // describe a session that never ran under what it claims.
    let host_probe = sandbox::HostProbe::probe();
    let enforcement_tier = host_probe.tier();
    // Derived only so the refusal can name *which* part of the sealed mechanism is missing —
    // the AppArmor profile, `CAP_SYS_ADMIN` inside a container, or the kernel itself.
    let sealed_blocker = host_probe.sealed_blocker();
    let achieved_containment = achieved_containment_class(enforcement_tier, workdir_exec);
    check_containment_floor(
        request.declared_containment_floor,
        achieved_containment,
        sealed_blocker,
        workdir_exec,
    )?;
    // The complete grant set this session is about to run under, in exactly the shape
    // `mur run --explain-scope --json` prints — same builder, same policy, same declared floor,
    // and the same probe taken above. Computed once here rather than at trace-open time so
    // the record cannot drift from the decision that let the session start.
    let exports_files = request
        .exports
        .as_ref()
        .and_then(|exports| exports.files.clone());
    let exports_peer_files = request
        .exports
        .as_ref()
        .and_then(|exports| exports.peer_files.clone());
    // Resolved before the report and before any per-artifact staging, so a malformed store name
    // refuses the launch on the same terms as an unmeetable containment floor: nothing pulled,
    // nothing created, nothing instantiated. Resolution only — `stage_artifact_grant` below is
    // what actually creates a directory, and only for an artifact whose entry declared one.
    let state_stores = crate::state_store::state_store_reports(
        request
            .artifacts
            .iter()
            .map(|artifact| (artifact.name.as_str(), artifact.capabilities.as_ref())),
        &request.capsule_name,
    )?;
    warn_on_inert_capsule_wide_state(request.capability_policy.state_declared);
    warn_on_inert_capsule_wide_conversation(request.capability_policy.conversation_declared);
    // Both halves of a record path, checked here for the reason a state store name is: a value
    // that cannot be one directory segment refuses the launch before anything is pulled, created
    // or instantiated, naming the key the operator wrote it under.
    if let Some(record) = request
        .context
        .as_ref()
        .filter(|context| context.record)
        .and_then(|context| context.record_store.as_deref())
    {
        crate::conversation::validate_record_segment("context.record_store", record)?;
    }
    if let Some(context_id) = request.context_id.as_deref() {
        crate::conversation::validate_record_segment("--context", context_id)?;
    }
    // An artifact may not claim a name the runtime answers itself. Checked here, ahead of the
    // artifact loop, so the refusal names the collision rather than whatever the registry would
    // have said about a name nothing can legally publish under: no resolve, no pull and no hash
    // verification happens for a manifest that declares one.
    check_no_reserved_tool_names(
        request
            .artifacts
            .iter()
            .map(|artifact| artifact.name.as_str()),
    )?;
    // A grant the credential backstop empties before any guest is built is refused on the same
    // terms, ahead of every resolve and pull: the manifest yields, the backstop does not.
    check_env_allow_reaches_guests(&request.capability_policy)?;
    // Resolved here for the same reason `state_stores` above is: a malformed `config:` block
    // refuses the launch before any registry pull, workdir creation or component instantiation,
    // and through the identical function `mur run --explain-scope` calls on the identical inputs.
    let configured_artifacts = crate::artifact_config::configured_artifact_names(
        request
            .artifacts
            .iter()
            .map(|artifact| (artifact.name.as_str(), artifact.config.as_ref())),
    )?;
    // Resolved through the identical function `mur run --explain-scope` and `mur doctor` call on
    // the identical inputs, so all three describe one preopen set. An escaping scope refuses the
    // launch here, before any registry pull or workdir creation, on the same terms a malformed
    // store name does.
    let preopens =
        crate::network_policy::preopen_reports(request.artifacts.iter().map(|artifact| {
            (
                artifact.name.as_str(),
                &artifact.runtime,
                artifact.capabilities.as_ref(),
            )
        }))?;
    let scope_report = crate::containment::scope_report_for_tier(
        &request.capability_policy,
        request.declared_containment_floor,
        enforcement_tier,
        sealed_blocker,
        host_probe.userns_grant(),
        request.exports.as_ref(),
        state_stores,
        configured_artifacts,
        preopens,
        // Not established at stage time: whether the declared `io.max` ceiling applies is known
        // only once the cgroup scope has been created, which `launch_session` does. Left at
        // `NotProbed` here so the staged report claims nothing, and overwritten from
        // `prepare_scope`'s real write outcome before `session_start` is written.
        crate::cgroup::IoMaxReport::default(),
    );
    // Asked here, beside the containment floors and before any registry pull or workdir creation:
    // an ephemeral capsule's teardown is what bounds every handle it minted, and `after_task:
    // sleep` withdraws that bound on purpose. Once withdrawn, the declared lifetime is the only
    // one there is, so it has to be declared and it has to be short.
    check_persistent_handle_ttl(
        exports_peer_files.as_ref(),
        &resolve_lifecycle(
            request.lifecycle.clone(),
            request.lifecycle_override.as_ref(),
        ),
    )?;
    // A second, independent floor question, deliberately asked right here next to the first: not
    // "can this host back what was declared?" but "did the capsule declare enough for what it
    // asks for?". A `staged_runtime` grant needs a composed root to be staged into, and one is
    // only built for a capsule that declared `sealed` — so this refuses on the declared floor
    // alone and never consults the host probe above.
    crate::staged_runtime::check_staged_runtime_floor(
        &request.capability_policy.shell_staged_runtime,
        request.declared_containment_floor,
    )?;
    // The same question as the line above, asked of the other half of the same gap. That one
    // catches a grant declared at too low a floor; this one catches a `sealed` capsule that
    // declared no grant at all for a `shell.allow` entry that provably needs one — a `#!` script,
    // whose ELF/DT_NEEDED closure is empty, so the staging that makes an ELF binary work stages
    // nothing at all of what the script imports. Same declared-floor-only gating, same
    // pre-registry-pull position, same "name every offender once" refusal shape.
    crate::reachability::check_interpreted_entrypoints_reachable(
        &request.capability_policy,
        request.declared_containment_floor,
    )?;
    // A third refusal, in the same pre-staging seam and for the same fail-closed reason, but
    // about a mechanism that sits outside the containment ladder entirely: a capsule that can
    // spawn a native subprocess needs a network namespace to put it in, because that namespace —
    // not a syscall filter — is now what makes `capabilities.network.allow` mean anything for
    // that subprocess. See `RuntimeError::EgressNamespaceUnavailable` for why this refuses even
    // when the allowlist is empty.
    //
    // Narrower than `cgroup::requires_process_bounding` on purpose, not by oversight: that check
    // also fires for a capsule with a *native-implementation artifact* and neither `shell.allow`
    // nor `spawn.allow`, but `has_native_artifact` comes from `staged.installed_artifacts`, which
    // only exists after staging resolves the registry — i.e. after this very check has to have
    // already run, per the "before any registry pull" rule above. A native-artifact-only capsule
    // therefore does not get this clean refusal on a host that cannot build the namespace; it
    // instead surfaces as a raw `io::Error` out of `create_capsule_netns`'s `pre_exec` failure
    // when that artifact is actually launched.
    crate::network_namespace::check_egress_namespace(
        !request.capability_policy.shell_allow.is_empty()
            || !request.capability_policy.spawn_allow.is_empty(),
        crate::network_namespace::detect_egress_namespace_blocker(),
    )?;
    // Lowered here, in the same pre-registry-pull seam and for the same reason a state store name
    // is: an entry that cannot be a workdir subtree refuses the launch before anything is pulled,
    // created or instantiated, so no call is ever checked against a rule the runtime could not
    // build. This is also the only place it is built — the dispatch check reads this value, never
    // the declared strings.
    let protected_paths =
        ProtectedPaths::from_declared(&request.capability_policy.read_only_paths)?;
    // Capsule-ceiling-level, not per-artifact: `interpreter_runtime` lives on the capsule's own
    // top-level `capabilities.shell`, so warn here (before the per-artifact staging loop) rather
    // than in `stage_artifact_grant`.
    warn_on_interpreter_runtime_grants(&request.capability_policy.shell_interpreter_runtime);
    // Same seam, same reason: a capsule-wide declaration whose cost the operator should see stated
    // once, before anything else happens. Ordered after the refusals above so a manifest that is
    // going to be rejected outright is not first warned about.
    warn_on_workdir_exec(workdir_exec);
    // Ordered beside the other capsule-wide declarations whose cost the operator should read
    // before the session starts, and after the refusals above so a manifest that will be rejected
    // is not first warned about.
    warn_on_advisory_read_only(
        &request.capability_policy.read_only_paths,
        &request.capability_policy.shell_allow,
    );
    // A host posture rather than a manifest declaration, but stated in the same place and for the
    // same reason: this session is about to record an achieved class that a weakened host and the
    // shipped profile can both produce, and the operator should be told which one they are on
    // before reading the result. Never a refusal — see `warn_on_userns_restriction_disabled_host_wide`.
    // Read off the report rather than re-probed, so the warning and the record cannot disagree.
    warn_on_userns_restriction_disabled_host_wide(scope_report.userns_grant);
    // The non-fatal half of the reachability check above. A compiler driver's helper binaries
    // (`cc1`, `as`, `ld`, `collect2`) are exec'd by the driver itself and sit outside its own
    // DT_NEEDED closure, inside the fixed sealed tree that is deliberately bound without the
    // Landlock Execute right — so `cc` starts and the first real compile does not finish. This
    // warns rather than refuses because the probe behind it is a heuristic about one driver
    // family; see `reachability::warn_on_unreachable_toolchain_helpers`, which prints each
    // `W-SEC-012` line, and each `W-SEC-029` line for a driver it could not run, itself so
    // `mur doctor` and this call site cannot state them differently.
    crate::reachability::warn_on_unreachable_toolchain_helpers(
        &request.capability_policy,
        request.declared_containment_floor,
    );

    let engine = build_engine()?;
    // Start ticking before the first guest runs: `dispatch_stage` below invokes on-stage
    // hooks, which are already subject to the epoch deadline.
    let epoch_ticker = EpochTicker::spawn(&engine);
    let lock_expectations = request.lock_expectations.map(|entries| {
        entries
            .into_iter()
            .map(|entry| (entry.name.clone(), entry))
            .collect::<HashMap<_, _>>()
    });

    let mut resolved_lock_artifacts = Vec::with_capacity(request.artifacts.len());
    let mut installed_artifacts = Vec::with_capacity(request.artifacts.len());
    let mut installed_manifests = Vec::with_capacity(request.artifacts.len());
    let mut tool_components = HashMap::with_capacity(request.artifacts.len());
    // Only tools/drivers that declare a `capabilities:` block get an entry; everything else
    // stays absent and therefore runs on the unclamped ceiling.
    let mut artifact_grants: HashMap<String, ToolCapabilityGrant> = HashMap::new();
    let mut hook_components = Vec::new();
    // The ceiling every per-artifact network grant is clamped against. Re-parsed here rather
    // than at launch because narrowing is lowered at staging time; `validate_capability_policy`
    // above already proved these entries parse.
    let ceiling_network_allow_rules =
        parse_network_allow_rules(&request.capability_policy.network_allow)?;
    // The capsule operator's own name for this capsule, borrowed for the length of the staging
    // loop below (which borrows `request.artifacts`). It is what an artifact entry's
    // `capabilities.state` defaults its store name to.
    let capsule_name = request.capsule_name.clone();
    // (name, binary_bytes) for native tool artifacts — installed after workdir creation
    let mut native_binaries: Vec<(String, Vec<u8>)> = Vec::new();
    // (name, skill_md_bytes) for skill artifacts — installed after workdir creation
    let mut skill_files: Vec<(String, Vec<u8>)> = Vec::new();

    for artifact in &request.artifacts {
        // Local-source skill: resolve skill.md directly from the filesystem and skip the
        // registry/lock pipeline entirely. Validated as skill-only at manifest parse time.
        if let Some(source) = &artifact.source {
            let skill_md = load_local_skill_md(&request.manifest_dir, source)?;
            skill_files.push((artifact.name.clone(), skill_md));
            installed_artifacts.push(InstalledArtifactSummary {
                name: artifact.name.clone(),
                version: artifact.version.clone(),
                runtime: artifact.runtime.clone(),
                implementation: None,
            });
            continue;
        }

        let (resolved_version, expected_hash) = match &lock_expectations {
            Some(expected_by_name) => {
                let expected = expected_by_name.get(&artifact.name).ok_or_else(|| {
                    RuntimeError::LockMissingEntry {
                        name: artifact.name.clone(),
                    }
                })?;

                if artifact.version != expected.resolved_version {
                    return Err(RuntimeError::LockVersionMismatch {
                        name: artifact.name.clone(),
                        requested: artifact.version.clone(),
                        pinned: expected.resolved_version.clone(),
                    });
                }

                (
                    expected.resolved_version.clone(),
                    Some(expected.sha256.clone()),
                )
            }
            None => (artifact.version.clone(), None),
        };

        // Always pass current_platform(). LocalRegistry and RemoteRegistry both implement a
        // fallback: if no platform-specific file exists they return the generic file. This
        // means WASM artifacts (which have no platform file) resolve transparently, while
        // native artifacts get their correct platform variant. Nexus must preserve this
        // fallback behaviour — if it ever becomes strict (error on no platform match), WASM
        // resolution will break.
        let resolved = registry
            .resolve_with_platform(&artifact.name, &resolved_version, Some(current_platform()))
            .map_err(|err| map_registry_error(&artifact.name, &resolved_version, err))?;

        verify_sha256(
            &artifact.name,
            &resolved_version,
            &resolved.bytes,
            &resolved.sha256,
        )
        .map_err(|_| RuntimeError::artifact_integrity_failed(&artifact.name, &resolved_version))?;

        // Which platform this payload gets pinned under in `murmur.lock`. A native binary is a
        // different payload per platform, so its hash is only ever the hash for this host; a
        // WASM component or a skill is the same bytes everywhere and is pinned once. Read from
        // the payload's own recorded runtime, the same question `pull` asks.
        let resolved_platform =
            (resolved.meta.runtime == RuntimeType::Native).then(|| current_platform().to_string());

        if let Some(expected) = expected_hash {
            if resolved.sha256 != expected {
                return Err(RuntimeError::artifact_integrity_failed(
                    &artifact.name,
                    &resolved_version,
                ));
            }
        }

        let manifest_yaml =
            extract_manifest_yaml(&artifact.name, &resolved_version, &resolved.bytes)?;

        installed_manifests.push((artifact.name.clone(), manifest_yaml.clone()));

        let mut artifact_implementation: Option<ArtifactImplementation> = None;

        match artifact.runtime {
            ArtifactRuntime::Tool => {
                let implementation = parse_tool_implementation_from_yaml(&manifest_yaml);
                artifact_implementation = Some(implementation.clone());
                match implementation {
                    ArtifactImplementation::Native => {
                        // A native tool is a host subprocess, not a WASI guest: it never
                        // reaches `invoke_tool_component`, so nothing would apply a
                        // per-artifact grant to it. Say so rather than let the block read
                        // as enforced.
                        warn_on_unenforceable_native_capabilities(
                            &artifact.name,
                            artifact.capabilities.as_ref(),
                        );
                        // Same hazard, one layer over: config is delivered in the per-artifact
                        // WASI environment, which a host subprocess never has.
                        warn_on_inert_native_config(&artifact.name, artifact.config.as_ref());
                        let binary = extract_native_binary(
                            &artifact.name,
                            &resolved_version,
                            &resolved.bytes,
                        )?;
                        native_binaries.push((artifact.name.clone(), binary));
                    }
                    ArtifactImplementation::Wasm => {
                        stage_artifact_grant(
                            artifact,
                            &ceiling_network_allow_rules,
                            &capsule_name,
                            &mut artifact_grants,
                        )?;
                        let tool_wasm =
                            extract_root_wasm(&artifact.name, &resolved_version, &resolved.bytes)?;
                        let tool_component = Component::new(&engine, tool_wasm).map_err(|err| {
                            RuntimeError::ToolComponentCompile {
                                name: artifact.name.clone(),
                                version: resolved_version.clone(),
                                message: err.to_string(),
                            }
                        })?;
                        tool_components.insert(artifact.name.clone(), tool_component);
                    }
                }
            }
            ArtifactRuntime::Driver => {
                // Same call as the WASM-tool arm above, and deliberately so: a driver is
                // staged into `tool_components` and dispatched through
                // `invoke_tool_component` like any tool, so narrowing needs no
                // driver-specific enforcement anywhere downstream.
                stage_artifact_grant(
                    artifact,
                    &ceiling_network_allow_rules,
                    &capsule_name,
                    &mut artifact_grants,
                )?;
                let tool_wasm =
                    extract_root_wasm(&artifact.name, &resolved_version, &resolved.bytes)?;
                let tool_component = Component::new(&engine, tool_wasm).map_err(|err| {
                    RuntimeError::ToolComponentCompile {
                        name: artifact.name.clone(),
                        version: resolved_version.clone(),
                        message: err.to_string(),
                    }
                })?;
                tool_components.insert(artifact.name.clone(), tool_component);
            }
            ArtifactRuntime::Hook => {
                let hook_config = parse_hook_config_from_yaml(&manifest_yaml).map_err(|e| {
                    RuntimeError::Runtime(format!(
                        "hook {}@{} invalid config: {e}",
                        artifact.name, resolved_version
                    ))
                })?;
                let hook_wasm =
                    extract_root_wasm(&artifact.name, &resolved_version, &resolved.bytes)?;
                let hook_component = Component::new(&engine, hook_wasm).map_err(|err| {
                    RuntimeError::ToolComponentCompile {
                        name: artifact.name.clone(),
                        version: resolved_version.clone(),
                        message: err.to_string(),
                    }
                })?;
                // The grant comes from `artifact` — the operator's own manifest entry for
                // this hook — and never from `manifest_yaml`, the hook's bundled manifest
                // parsed just above for its behavioral contract. A hook pulled from a
                // registry therefore cannot widen what the host lets it do. Deriving here
                // (rather than at instantiation) means a malformed grant fails staging,
                // before any hook component runs.
                let mut grant =
                    HookCapabilityGrant::derive(artifact.capabilities.as_ref(), &capsule_name)?;
                // Same division as `stage_artifact_grant`: `derive` validated the name and stays
                // pure, and the directory is created here, on the staging path, once.
                if let Some(store) = grant.state_store.as_deref() {
                    grant.state_dir = Some(crate::state_store::ensure_state_store(store)?);
                }
                // Operator-sourced like `grant` itself, and lowered onto the grant rather than
                // into `HookEnvVars`, which is session-wide: the grant is what dispatch already
                // looks up per hook, so this is what scopes the value to the declaring hook.
                grant.config_json = artifact
                    .config
                    .as_ref()
                    .map(|config| {
                        crate::artifact_config::lower_artifact_config(&artifact.name, config)
                    })
                    .transpose()?;
                warn_on_inert_hook_capabilities(&artifact.name, artifact.capabilities.as_ref());
                hook_components.push(StagedHookArtifact {
                    name: artifact.name.clone(),
                    version: resolved_version.clone(),
                    component: hook_component,
                    config: hook_config,
                    grant,
                    // Operator-sourced like `grant`, for the same reason: how much of the
                    // agent's telemetry may be dropped to keep the loop moving is the
                    // operator's call, not the hook author's.
                    on_overflow: artifact.on_overflow,
                });
            }
            ArtifactRuntime::Skill => {
                let skill_md =
                    extract_skill_md(&artifact.name, &resolved_version, &resolved.bytes)?;
                skill_files.push((artifact.name.clone(), skill_md));
            }
        }

        resolved_lock_artifacts.push(ResolvedLockArtifact {
            name: artifact.name.clone(),
            resolved_version: resolved_version.clone(),
            sha256: resolved.sha256,
            platform: resolved_platform,
        });
        installed_artifacts.push(InstalledArtifactSummary {
            name: artifact.name.clone(),
            version: resolved_version,
            runtime: artifact.runtime.clone(),
            implementation: artifact_implementation,
        });
    }

    // Minted before the spend meter rather than beside the workdir it names: the ledger records it.
    let session_id = generate_session_id();

    // Before `dispatch_stage` runs any on-stage hook and before the session directory exists: a
    // machine ceiling that cannot be kept, or a `transport: http` driver that does not say how its
    // provider takes the key (it could only be run by handing it the key), refuses the launch here
    // rather than at the first turn.
    let spend = stage_spend_meter(
        request.inference.as_ref(),
        request.machine_tokens_per_day,
        &session_id,
    )?;
    let inference_gateway = stage_inference_gateway(
        request.inference.as_ref(),
        request.credentials_file.as_deref(),
        &installed_manifests,
        &installed_artifacts,
        &spend,
    )?;

    // Asked as soon as the hook artifacts are staged and their bindings are known, and before
    // the session directory is created: a resume that cannot continue anything must leave no
    // `ses_*` directory behind for the next `--resume @1` to name.
    if let Some(ref resume) = request.resume {
        check_resume_launchable(
            resume,
            request.context_id.as_deref(),
            request.context.as_ref(),
            &request.capsule_name,
            request.inference.as_ref(),
            &hook_components,
        )?;
    }

    // For agent capsules (inference configured, empty WASM bytes) skip component compilation.
    // For script capsules, compile the WASM component.
    let capsule_component =
        if request.inference.is_some() && request.capsule_component_bytes.is_empty() {
            None
        } else if request.capsule_component_bytes.is_empty() {
            return Err(RuntimeError::CapsuleCompile(
                "capsule component bytes are required for non-agent capsules".to_string(),
            ));
        } else {
            Some(
                Component::new(&engine, &request.capsule_component_bytes)
                    .map_err(|err| RuntimeError::CapsuleCompile(err.to_string()))?,
            )
        };

    let (workdir, accessible_workdir) = if let Some(ref user_dir) = request.workdir {
        let user_dir = if user_dir.is_absolute() {
            user_dir.clone()
        } else {
            std::env::current_dir()
                .map_err(|e| RuntimeError::Runtime(format!("failed to get cwd: {e}")))?
                .join(user_dir)
        };
        if !user_dir.exists() || !user_dir.is_dir() {
            return Err(RuntimeError::Runtime(format!(
                "workdir '{}' does not exist or is not a directory",
                user_dir.display()
            )));
        }
        let session_dir = user_dir.join(".murmur").join(&session_id);
        (session_dir, user_dir)
    } else {
        let dir = request.manifest_dir.join("workdir").join(&session_id);
        let accessible = dir.clone();
        (dir, accessible)
    };
    // Before the workdir is created and before anything is staged into it: a declared export
    // whose root already resolves outside the accessible workdir must refuse the launch, not be
    // discovered one served file at a time.
    if let Some(ref export) = exports_files {
        crate::resource_plane::check_export_root(&accessible_workdir, export)?;
    }
    if let Some(ref export) = exports_peer_files {
        crate::resource_plane::check_peer_files_root(&accessible_workdir, export)?;
    }

    fs::create_dir_all(workdir.join("tools")).map_err(|source| RuntimeError::CreateWorkdir {
        path: workdir.display().to_string(),
        source,
    })?;

    for (name, manifest_yaml) in &installed_manifests {
        write_tool_manifest(&workdir, name, manifest_yaml)?;
    }

    install_native_binaries(&workdir, native_binaries)?;
    install_skill_files(&workdir, skill_files)?;

    // Write generic manifests for any shell binary not already covered by a custom manifest.
    write_shell_tool_manifests(&workdir, &request.capability_policy.shell_allow)?;

    // The two peer-handoff tools, written on exactly the terms the shell manifests above are:
    // a synthetic `tools/<name>/murmur.yaml` that `build_tool_inventory` picks up unchanged,
    // paired with a dispatch branch in `dispatch_agent_tool_async`. Each is written **only** when
    // its grant is declared, so an undeclared capsule's model never sees the tool exists.
    write_peer_handoff_tool_manifests(
        &workdir,
        exports_peer_files.is_some(),
        !request.capability_policy.peer_fetch_allow.is_empty(),
    )?;

    // And the delegation tool, on the same terms again. Its schema is built rather than fixed:
    // the `capsule` property's `enum` is this capsule's own `capabilities.spawn.allow`, so the
    // model is offered the names the operator granted and cannot name anything else.
    write_delegate_task_tool_manifest(&workdir, &request.capability_policy.spawn_allow)?;

    // And the plan tool, on the same terms once more. Its schema is fixed rather than built: a
    // plan reaches this session's own tools, so there is no granted list to fold into it.
    write_submit_plan_tool_manifest(&workdir, request.capability_policy.plan_submit)?;

    // Read once, here, from the manifests just staged: the schema is fixed before the session
    // starts, so an annotation is the tool author's statement and never a call-time choice. A
    // capsule that declared nothing read-only reads no schema at all — the analyser it would feed
    // never runs.
    let tool_annotations = if protected_paths.is_empty() {
        ToolAnnotationMap::default()
    } else {
        warn_on_unannotated_tool_schemas(&installed_manifests);
        ToolAnnotationMap::from_workdir(&workdir)
    };

    // Dispatch on-stage hooks synchronously now that manifests are in place.
    let stage_env = HookEnvVars::default();
    dispatch_stage(
        &engine,
        &workdir,
        &hook_components,
        request.capability_policy.shell_allow.clone(),
        &stage_env,
        request.capability_policy.hook_limits(),
    )?;

    // Write MURMUR.md now for agent sessions so that tooling that inspects the workdir after
    // staging (e.g. tests, debuggers) can read it. launch_session overwrites this file after
    // port binding with the complete identity including capsule_url.
    if let Some(ref inference) = request.inference {
        let partial_identity = CapsuleIdentity {
            capsule_name: request.capsule_name.clone(),
            capsule_version: request.capsule_version.clone(),
            session_id: session_id.clone(),
            capsule_url: String::new(),
        };
        murmur_md::write_murmur_md(
            &workdir,
            Some(inference),
            request.context.as_ref(),
            has_compaction_hook(&hook_components),
            &request.capability_policy,
            &partial_identity,
        );
    }

    // When --workdir is used, copy the project manifest to the accessible workdir so the agent
    // can reference it by relative path from ".".
    if request.workdir.is_some() {
        let src = request.manifest_dir.join(MANIFEST_FILENAME);
        let dst = accessible_workdir.join(MANIFEST_FILENAME);
        if src.exists() && !dst.exists() {
            if let Err(e) = fs::copy(&src, &dst) {
                eprintln!(
                    "[capsule-runtime] warning: failed to copy {MANIFEST_FILENAME} to workdir: {e}"
                );
            }
        }
    }

    // Resolve lifecycle: manifest config + any override
    let lifecycle = resolve_lifecycle(request.lifecycle, request.lifecycle_override.as_ref());

    Ok(StagedSession {
        session_id,
        workdir,
        accessible_workdir,
        manifest_dir: request.manifest_dir,
        capsule_name: request.capsule_name,
        capsule_version: request.capsule_version,
        capsule_url: String::new(), // set by launch_session after port binding
        resolved_lock_artifacts,
        installed_artifacts,
        inference: request.inference,
        inference_gateway,
        spend,
        system_prompt_overridden: request.system_prompt_overridden,
        context: request.context,
        context_id: request.context_id,
        resume: request.resume,
        engine,
        capsule_component,
        tool_components,
        artifact_grants,
        hook_components,
        allowlisted_tools: request.allowlisted_tools,
        // The combined floor (manifest + workspace config + `--containment`) replaces the
        // manifest-only value the policy was built with, so every later reader — including
        // `ShellEnforcement::resolve`, which decides whether this session installs a composed
        // root — sees the class that was actually asked for.
        capability_policy: CapabilityPolicy {
            containment_floor: request.declared_containment_floor,
            ..request.capability_policy
        },
        otel_endpoint: request.otel_endpoint,
        eval_config_json: request.eval_config_json,
        case_id: request.case_id,
        dataset_id: request.dataset_id,
        lifecycle,
        trace_capture: request
            .trace
            .as_ref()
            .map(|t| t.capture)
            .unwrap_or_default(),
        trace_retain: request.trace.as_ref().and_then(|t| t.retain),
        host_probe,
        protected_paths,
        tool_annotations,
        bind_addr: request.bind_addr,
        internal_port: request.internal_port,
        declared_containment_floor: request.declared_containment_floor,
        scope_report,
        exports_files,
        exports_peer_files,
        registry,
        _epoch_ticker: epoch_ticker,
        // Minted by the daemon at registration, which `launch_session` performs — it names a
        // session id, and staging is what mints one.
        spawn_credential: None,
        spawn_grant: request.spawn_grant,
        // The one read of `MURMUR_SPAWNER` inside a session. `mur run` validates it earlier and
        // discards the value, so a handle that cannot be read refuses the launch before a session
        // directory exists; this is where the value itself enters the session.
        spawner: SpawnerHandle::from_env()?,
    })
}

/// Instantiates the staged capsule and executes it.
///
/// Agent capsules (inference configured) run the built-in native Rust loop.
/// Script capsules (WASM component present) instantiate and call `murmur:capsule/run#run()`.
///
/// Leaves the process's `SIGTERM` disposition alone: a caller that runs several sessions in one
/// process, or does more work after this returns, keeps the default of ending at once. A caller
/// whose process is the session uses [`launch_session_handling_sigterm`] instead.
pub fn launch_session(
    staged: StagedSession,
    on_url: impl FnOnce(&str),
) -> Result<LaunchResult, RuntimeError> {
    launch(staged, on_url, false)
}

/// [`launch_session`] for a process whose lifetime is this one session.
///
/// On unix an agent session takes `SIGTERM` over for the rest of the process: the first signal
/// cancels every live task and ends the session through its normal teardown, a second exits at
/// once with status 143, and [`TERMINATE_TEARDOWN_DEADLINE`] after the first the process exits
/// with status 143 whatever it is doing. Those exits end the whole process, so nothing that
/// outlives the session may share it. A script capsule, or a platform without `SIGTERM`, launches
/// exactly as [`launch_session`] does.
pub fn launch_session_handling_sigterm(
    staged: StagedSession,
    on_url: impl FnOnce(&str),
) -> Result<LaunchResult, RuntimeError> {
    launch(staged, on_url, true)
}

fn launch(
    mut staged: StagedSession,
    on_url: impl FnOnce(&str),
    handle_sigterm: bool,
) -> Result<LaunchResult, RuntimeError> {
    let network_allow_rules = parse_network_allow_rules(&staged.capability_policy.network_allow)?;

    // Before any WASM is instantiated and before any subprocess is bounded: a session that can
    // delegate announces itself to the daemon that will referee those delegations, and takes the
    // credential it will present. A session that cannot delegate does none of this — it opens no
    // connection, needs no daemon, and is unaffected by there being none.
    let mut roost_session = RoostSession::register(&mut staged)?;

    // Beside the registration and on the same terms: a session that was delegated to must be
    // able to say how it ended, so the handle is read before anything is instantiated and the
    // report is a guard rather than a line at each success return. A session nobody delegated
    // reads an absent variable and does nothing further.
    let mut delegation = DelegationReport::open(&staged)?;

    // --- Host-process bounding, before any WASM is instantiated ------------------------------
    //
    // A capsule that can reach a native subprocess by any route (`shell.allow`, `spawn.allow`,
    // or a native-implementation artifact) needs a cgroup scope around that process tree. On
    // Linux, failing to get one is fatal here — refusing the launch is strictly better than
    // running the tree with no aggregate memory/pids/cpu ceiling, and it must happen before
    // instantiation so no subprocess is ever spawned unbounded. Off Linux there is no cgroup to
    // get, so `prepare_scope` returns `None` and the gap is reported as `W-SEC-010` instead.
    let has_native_artifact = staged.installed_artifacts.iter().any(|artifact| {
        matches!(
            artifact.implementation,
            Some(murmur_artifact::ArtifactImplementation::Native)
        )
    });
    let requires_process_bounding =
        cgroup::requires_process_bounding(&staged.capability_policy, has_native_artifact);
    let prepared_scope = cgroup::prepare_scope(
        requires_process_bounding,
        &staged.capability_policy.resources,
        &staged.session_id,
        &staged.workdir,
    )
    .map_err(|reason| RuntimeError::CgroupDelegationUnavailable { reason })?;
    // Written into the staged report here, immediately after the write that decided it and ahead
    // of every `staged.scope_report.clone()` that feeds a `session_start` event — the agent path
    // and the script path both clone it later in this function. `stage_session` could not fill it:
    // the answer does not exist until the scope has been created.
    staged.scope_report.io_max = prepared_scope.io_max.clone();
    // `io.max` is the one cgroup limit a host is not refused for, so a declared ceiling that did
    // not apply has to be *said* here or the manifest and the scope report both go on implying it.
    cgroup::warn_for_unenforced_io_max(&staged.workdir, &prepared_scope.io_max);
    let cgroup_scope = prepared_scope.scope;
    let workdir_guard = Some(resources::WorkdirGuard::spawn(
        &staged.workdir,
        staged.capability_policy.resources.workdir_max_bytes,
    ));

    let shell_enforcement = sandbox::ShellEnforcement::resolve(
        &staged.capability_policy,
        staged.declared_containment_floor,
        staged.host_probe,
    )
    .map_err(RuntimeError::Runtime)?
    .with_host_bounding(cgroup_scope, workdir_guard);
    let inference_env = staged
        .inference
        .as_ref()
        .map(|inference| inference_env_pairs(inference, staged.inference_gateway.as_deref()))
        .unwrap_or_default();
    let inference_gateway = staged.inference_gateway.clone();
    let spend = Arc::clone(&staged.spend);

    if let Some(ref inference) = staged.inference {
        let workdir = staged.workdir.clone();
        let system_prompt = resolve_system_prompt(&staged.manifest_dir, &workdir, inference)?;
        let compaction_system_prompt =
            resolve_compaction_system_prompt(&staged.manifest_dir, inference.compaction.as_ref())?;
        let session_id = staged.session_id.clone();
        let accessible_workdir = staged.accessible_workdir.clone();
        let context_window = resolve_context_window(staged.context.as_ref());
        let seed_budget = staged
            .context
            .as_ref()
            .map(|c| c.seed_budget)
            .unwrap_or(murmur_artifact::DEFAULT_SEED_BUDGET);
        // Computed once for the whole launch: the ceiling depends only on the manifest, and
        // every `on-task-start` in the session is measured against the same number.
        let seed_budget_tokens = agent::seed_budget_tokens(context_window, seed_budget);

        let run_config = agent::AgentRunConfig {
            context_window,
            compaction_threshold: inference
                .compaction
                .as_ref()
                .and_then(|c| c.threshold)
                .unwrap_or(0.98),
            compaction_model: inference.compaction.as_ref().and_then(|c| c.model.clone()),
            compaction_system_prompt,
            compaction_dump_summaries: inference
                .compaction
                .as_ref()
                .and_then(|c| c.dump_summaries)
                .unwrap_or(false),
            max_output_tokens: inference
                .max_tokens
                .unwrap_or(agent::DEFAULT_MAX_OUTPUT_TOKENS),
            seed_budget,
            seed_overflow_margin: staged
                .context
                .as_ref()
                .map(|c| c.seed_overflow_margin)
                .unwrap_or(murmur_artifact::DEFAULT_SEED_OVERFLOW_MARGIN),
            conversation_root: resolve_conversation_root(
                staged.context.as_ref(),
                &staged.capsule_name,
                inference,
                &workdir,
            ),
            // Ownership is claimed only by a capsule that declares a record policy: without one
            // there is nothing retention needs the header for, and an upgrading capsule's record
            // keeps the exact bytes it had.
            record_owner: staged
                .context
                .as_ref()
                .and_then(|context| context.retain)
                .map(|_| staged.capsule_name.clone()),
            resume: staged.resume.as_ref().map(|resume| resume.mode),
        };

        // --- Identity and HTTP server setup ---

        let rt = tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .build()
            .map_err(|e| RuntimeError::Runtime(format!("failed to create tokio runtime: {e}")))?;

        let (tcp_listener, external_port) = rt.block_on(identity::bind_local_port(
            &staged.bind_addr,
            staged.internal_port,
        ))?;

        let capsule_url = format!("localhost:{external_port}");
        staged.capsule_url = capsule_url.clone();

        // Built while `staged` is still whole. It is written, and the URL announced, inside the
        // task `LocalSet` below, once the door is being served.
        let running_record = running_record_for(&staged, &session_id, &capsule_url);

        // Taken over from the default disposition, when the caller owns the process, before the
        // door is announced, so a `SIGTERM` sent by anyone who has seen the URL is held for the
        // task loop's handler rather than ending the process with no teardown. A signal that
        // arrives before the handler is spawned is delivered to it then.
        #[cfg(not(unix))]
        let _ = handle_sigterm;
        #[cfg(unix)]
        let sigterm = if !handle_sigterm {
            None
        } else {
            let _runtime = rt.enter();
            match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
                Ok(sigterm) => Some(sigterm),
                Err(e) => {
                    eprintln!(
                        "[capsule-runtime] could not install a SIGTERM handler; SIGTERM will end this session without its teardown: {e}"
                    );
                    None
                }
            }
        };

        let capsule_identity = CapsuleIdentity {
            capsule_name: staged.capsule_name.clone(),
            capsule_version: staged.capsule_version.clone(),
            session_id: session_id.clone(),
            capsule_url: capsule_url.clone(),
        };

        // Inject identity env vars into all WASI contexts for this session.
        let mut all_env = inference_env.clone();
        all_env.push((
            "MURMUR_CAPSULE_NAME".to_string(),
            staged.capsule_name.clone(),
        ));
        all_env.push((
            "MURMUR_CAPSULE_VERSION".to_string(),
            staged.capsule_version.clone(),
        ));
        all_env.push(("MURMUR_SESSION_ID".to_string(), session_id.clone()));
        all_env.push(("MURMUR_CAPSULE_URL".to_string(), capsule_url.clone()));

        murmur_md::write_murmur_md(
            &workdir,
            Some(inference),
            staged.context.as_ref(),
            has_compaction_hook(&staged.hook_components),
            &staged.capability_policy,
            &capsule_identity,
        );

        sandbox::warn_for_enforcement_tier(
            shell_enforcement.tier,
            &workdir,
            &staged.capability_policy,
        );
        sandbox::warn_for_missing_aggregate_bounding(
            &workdir,
            requires_process_bounding,
            shell_enforcement.cgroup_scope.is_some(),
        );
        warn_for_unreachable_delegation_outcomes(
            &workdir,
            !staged.capability_policy.spawn_allow.is_empty(),
            &staged.lifecycle,
        );
        warn_for_unreachable_shell_completions(
            &workdir,
            !staged.capability_policy.shell_allow.is_empty(),
            &staged.lifecycle,
        );

        let agent_card = identity::build_agent_card(
            &capsule_identity,
            &staged.installed_artifacts,
            &staged.capability_policy,
        );
        let agent_card_json = agent_card.to_string();

        // --- Lifecycle config ---
        let effective_lifecycle = staged.lifecycle.clone();
        let conversation_mode = effective_lifecycle.conversation_mode.clone();
        // `mur run --context <id>`: the id every `task.md` task of this launch runs under, so two
        // runs given the same one share one conversation record. Validated at staging; `None`
        // mints a fresh id per task, as it always has.
        let supplied_context_id = staged.context_id.clone();
        // Provenance for `session_start`, taken before `staged.resume` is consumed below: which
        // session this launch continues, and the launch-scoped context it runs under. Both are
        // `None` on an ordinary launch, and `context_id` is `None` whenever each task mints its
        // own — `task_start` carries the id a task actually ran under either way.
        let trace_resumed_from = staged
            .resume
            .as_ref()
            .map(|resume| resume.from_session.clone());
        // The same value, read again below by the reconciliation step, which needs the directory
        // name after `TraceWriter::open` has taken the one above.
        let reconcile_from_session = trace_resumed_from.clone();
        let trace_context_id = supplied_context_id.clone();
        // Lineage for `session_start`, from the handle the spawning capsule's launcher injected.
        // Both `None` for a capsule nobody delegated, and both omitted from the record then.
        let trace_spawned_by = staged
            .spawner
            .as_ref()
            .map(|handle| handle.session_id.clone());
        let trace_spawn_delegation_id = staged
            .spawner
            .as_ref()
            .map(|handle| handle.delegation_id.clone());
        let queue_capacity = match effective_lifecycle.task_acceptance {
            TaskAcceptance::Queue => effective_lifecycle.queue_depth,
            _ => 1,
        };

        // --- A2A task registry and incoming channel ---
        let task_registry: Arc<Mutex<TaskRegistry>> = Arc::new(Mutex::new(TaskRegistry::new(
            effective_lifecycle.queue_depth,
            effective_lifecycle.task_acceptance.clone(),
        )));
        let (task_tx, mut task_rx) = tokio::sync::mpsc::channel::<IncomingTask>(queue_capacity);

        // Demoted shell commands and the channel their completions come back on. Unbounded, so
        // the OS thread running a detached command never blocks handing its result over.
        let (detached, mut completion_rx) = DetachedRegistry::new();

        // Delegations in flight. Built here rather than with the store state because the A2A door
        // reads it too: a cancel names every child still running, and the door is spawned first.
        let live_delegations = Arc::new(crate::cancel::LiveDelegations::new());

        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();

        // SSE broadcast channel and replay buffer for SSE clients
        let (sse_tx, _) =
            tokio::sync::broadcast::channel::<std::sync::Arc<String>>(SSE_BROADCAST_CAPACITY);
        let sse_buffer = std::sync::Arc::new(Mutex::new(SseEventBuffer::new(SSE_REPLAY_CAPACITY)));

        let capsule_name = staged.capsule_name.clone();
        let capabilities = capability_names(&staged.capability_policy);
        // Computed once at stage time, not re-derived here: `session_start` records what this
        // session ran with, and the staged report is the single place that value already lives.
        // It also carries the declared/achieved classes and `workdir_exec` the event's own
        // top-level fields are written from.
        let effective_grants = staged.scope_report.clone();
        // The resource plane is built from a host path, a declared export, an achieved class, a
        // counter and a trace handle — nothing the agent loop owns and nothing a completed task
        // leaves behind. That is what a later reader-only launch mode over an existing workdir
        // would need, and no more.
        let exports_files = staged.exports_files.clone();
        let resource_containment = staged.scope_report.achieved_containment;
        let resource_accessible_workdir = accessible_workdir.clone();

        // The peer plane's minting key: 32 random bytes, generated here and only when
        // `exports.peer_files` is declared, held in memory for this session and destroyed with it.
        // Never written to disk and never placed in an environment variable — teardown is the
        // revocation mechanism, so there must be nothing left to reload.
        let exports_peer_files = staged.exports_peer_files.clone();
        let peer_mint_key = match exports_peer_files {
            Some(_) => Some(std::sync::Arc::new(
                crate::peer_handoff::PeerMintKey::generate().map_err(RuntimeError::Runtime)?,
            )),
            None => None,
        };
        // Both sides derive the audience from the fetching capsule's own advertised identity, so
        // what this capsule asserts on a redeem it issues is the same string a peer would read
        // off the card it publishes.
        let own_peer_audience = crate::peer_handoff::own_audience(&capsule_identity);
        let peer_fetch_rules =
            parse_network_allow_rules(&staged.capability_policy.peer_fetch_allow)?;

        // The delegating side of the same registration `RoostSession` opened. Built for every
        // registered session, because the credential is what a delegation is made with and a
        // session holds one exactly when the daemon minted it — the `delegate-task` manifest was
        // written from the same declaration, so the tool and the plane appear together.
        let delegation_plane = roost_session.endpoint().map(|(roost_url, credential)| {
            std::sync::Arc::new(
                crate::delegation_plane::DelegationPlane::new(
                    roost_url.to_string(),
                    credential,
                    accessible_workdir.clone(),
                    session_id.clone(),
                    std::time::Duration::from_secs(effective_lifecycle.delegation_deadline_secs),
                    Arc::clone(&staged.registry),
                    staged.capability_policy.env_allow.clone(),
                )
                // This capsule's own A2A door, bound just above: where a started delegation's
                // completion is posted, and what makes `DelegationPlane::start` available at all.
                .reporting_to(format!("http://{capsule_url}")),
            )
        });

        // Capture staged fields that move into the async block
        let hook_components = staged.hook_components;
        let tool_components = staged.tool_components;
        let artifact_grants = staged.artifact_grants;
        let allowlisted_tools = staged.allowlisted_tools.clone();
        let installed_artifacts = staged.installed_artifacts;
        let engine = staged.engine.clone();
        let capability_policy = staged.capability_policy.clone();
        let protected_paths = staged.protected_paths.clone();
        let tool_annotations = staged.tool_annotations.clone();
        let shell_enforcement_for_state = shell_enforcement.clone();
        let otel_endpoint = staged.otel_endpoint;
        let eval_config_json = staged.eval_config_json;
        let case_id = staged.case_id;
        let dataset_id = staged.dataset_id;
        let capsule_version = staged.capsule_version.clone();
        let inference_model = inference.model.clone();
        // Non-empty only for the WASM-driver transport; a `transport: process`
        // capsule has no driver artifact, so a hook's `run-inference` correctly
        // reports "no driver configured" rather than silently doing nothing.
        let inference_driver_name = inference
            .driver
            .as_ref()
            .map(|d| d.artifact.clone())
            .filter(|a| !a.is_empty());
        let trace_capture = staged.trace_capture;
        // Retention inputs, taken before `staged` and `run_config` are moved into the agent loop.
        // Both are `None` on a capsule that declared no `retain:` block, and `None` deletes
        // nothing, ever.
        let trace_retain = staged.trace_retain;
        let context_retain = staged.context.as_ref().and_then(|context| context.retain);
        let retention_conversation_root = run_config.conversation_root.clone();
        // The trace records the *resolved* prompt — what `resolve_system_prompt` returned, before
        // `build_augmented_system_prompt` prepends the `[Capsule]` block — so a reader compares
        // what the manifest (or `--system-prompt`) actually said, not the runtime's framing of it.
        let trace_system_prompt = system_prompt.clone();
        let system_prompt_overridden = staged.system_prompt_overridden;
        let registry_for_pull = Arc::clone(&staged.registry);
        let lock_path_for_pull = staged.manifest_dir.join("murmur.lock");

        // task.md must live where the agent's own tools are preopened (accessible_workdir),
        // not the internal `.murmur/<session_id>` bookkeeping dir (workdir) — otherwise this
        // pre-seed check misses a `--task`-written file and the agent's own read of task.md
        // 404s even after a task was delivered.
        let workdir_task_md = accessible_workdir.join("task.md");

        // Extra copies retained for the LaunchResult returned after block_on consumes the others.
        let session_id_ret = session_id.clone();
        let workdir_ret = workdir.clone();

        // --- Agent loop inside a LocalSet (handles !Send WasiCtx) ---
        let loop_result: Result<(), RuntimeError> = rt.block_on(async move {
            let mut trace = TraceWriter::open(
                &workdir,
                session_id.clone(),
                capsule_name.clone(),
                capsule_version.clone(),
                inference_model.clone(),
                capabilities.clone(),
                effective_grants,
                trace_capture,
                trace_system_prompt,
                system_prompt_overridden,
                trace_resumed_from,
                trace_context_id,
                trace_spawned_by,
                trace_spawn_delegation_id,
            )
            .await
            .map_err(|e| RuntimeError::AgentLoopFailed(format!("failed to open trace.jsonl: {e}")))?;
            trace.set_spend_ceilings(spend.session_ceiling(), spend.machine_ceiling());

            // The session frame is written once per launch, around the task loop, so it frames
            // the `on-session-start`/`on-session-end` hook pair. It goes in before anything
            // else can write to the file: `session_start`'s `event_id` is the root of the trace's
            // event tree, and the resource plane — opened next, and served concurrently from the
            // moment the listener accepts — names that id as its `parent_id` on every line.
            //
            // Both transports derive `tools_declared` from this same inventory, so one call
            // site serves both.
            let tools_declared: Vec<String> =
                agent::inventory::build_tool_inventory(&workdir, inference.system_prompt_artifact.as_deref())
                    .iter()
                    .filter_map(|t| t.get("name").and_then(serde_json::Value::as_str))
                    .map(str::to_string)
                    .collect();
            let inference_credential = inference_gateway
                .as_ref()
                .and_then(|gateway| gateway.credential())
                .cloned();
            trace.set_credential_source(
                inference_credential
                    .as_ref()
                    .map_or("none", |credential| credential.source().trace_name()),
            );
            trace
                .write_session_start(inference.max_turns, tools_declared)
                .await
                .map_err(|e| RuntimeError::AgentLoopFailed(format!("trace write failed: {e}")))?;

            // Retention runs here and nowhere else: the session node exists from the line above,
            // so every deletion has a parent to hang off, and a policy that only runs when an
            // operator remembers to invoke a command does not run.
            apply_retention(
                &mut trace,
                &workdir,
                &session_id,
                trace_retain.as_ref(),
                context_retain.as_ref(),
                retention_conversation_root.as_deref(),
                &capsule_name,
                supplied_context_id.as_deref(),
            )
            .await;

            // A second handle to the same trace.jsonl, not a borrow of the writer above: the
            // motivating read happens after `session_end`, when the agent loop's writer is gone.
            // A trace that cannot be opened must not make the plane unserveable — the read is
            // still refused or served correctly, it is only unrecorded.
            let resource_trace = crate::trace::ResourceTraceAppender::open(
                &workdir,
                session_id.clone(),
                trace.session_event_id().to_string(),
            )
            .await
            .ok()
            .map(std::sync::Arc::new);
            // The credential records a rotation or rejection through the same kind of handle, and
            // for the same reason: the gateway sends from a task the loop's writer cannot reach,
            // and the record should land when the request does.
            if let (Some(credential), Some(appender)) = (&inference_credential, &resource_trace) {
                credential.attach_trace(Arc::clone(appender));
            }
            // The same file again, for the same reason and on the same terms: a plan's steps run
            // on blocking threads, so they cannot be lent the agent loop's own writer. A trace
            // that cannot be opened leaves a plan unrecorded and still runs it.
            let plan_trace = crate::trace::PlanTraceAppender::open(
                &workdir,
                session_id.clone(),
                trace.session_event_id().to_string(),
            )
            .ok()
            .map(std::sync::Arc::new);
            let resource_plane = std::sync::Arc::new(crate::resource_plane::ResourcePlane::new(
                &resource_accessible_workdir,
                exports_files.as_ref(),
                resource_containment,
                task_registry.lock().unwrap().resource_generation(),
                resource_trace.clone(),
            ));
            // Always built, declared or not: an undeclared capsule still has to record the redeem
            // it refused, and its declared half is `None` only because there is nothing to serve.
            // The key exists exactly when the export does — both come from the same declaration.
            let peer_plane = std::sync::Arc::new(crate::peer_handoff::PeerPlane::new(
                &resource_accessible_workdir,
                exports_peer_files
                    .as_ref()
                    .zip(peer_mint_key.as_ref())
                    .map(|(export, key)| (export, std::sync::Arc::clone(key))),
                session_id.clone(),
                resource_containment,
                task_registry.lock().unwrap().resource_generation(),
                resource_trace.clone(),
            ));

            let mut otel = OtelEmitter::new(
                otel_endpoint.clone(),
                &workdir,
                capsule_name.clone(),
                capsule_version.clone(),
            );

            let local = tokio::task::LocalSet::new();
            local
                .run_until(async move {
                    // Spawn HTTP server as a local task (uses spawn_local for !Send compat)
                    let server_handle =
                        tokio::task::spawn_local(identity::serve_http(
                            tcp_listener,
                            shutdown_rx,
                            agent_card_json,
                            Arc::clone(&task_registry),
                            task_tx,
                            effective_lifecycle.task_acceptance.clone(),
                            sse_tx.clone(),
                            Arc::clone(&sse_buffer),
                            conversation_mode.clone(),
                            std::sync::Arc::clone(&resource_plane),
                            std::sync::Arc::clone(&peer_plane),
                            session_id.clone(),
                            Some(Arc::clone(&detached)),
                            Arc::clone(&live_delegations),
                        ));

                    // Read before `capability_policy` moves into the store state below. Hooks
                    // get the same resource caps as every other guest but their own, lower
                    // deadline default — see `CapabilityPolicy::hook_limits`.
                    let hook_limits = capability_policy.hook_limits();

                    // Build CapsuleStoreState ONCE — reused across all task iterations
                    let mut state = CapsuleStoreState {
                        // Agent capsules have no WASM component of their own, so this state
                        // never backs a `Store` and this limiter is never registered. It is
                        // the per-tool limiters built in `dispatch_tool_async` (from
                        // `capability_policy.limits`) that bound this path's guests.
                        limits: capability_policy.limits.limiter(),
                        table: ResourceTable::new(),
                        // The capsule's own store is the ceiling itself, never narrowed:
                        // per-artifact grants apply to staged tools/drivers, not to the
                        // agent loop's own context.
                        wasi: build_wasi_ctx(
                            &accessible_workdir,
                            None,
                            // Nor does a state store: it too is granted per artifact, and the
                            // capsule holds no artifact grant.
                            None,
                            // Nor a config block, for the same reason — `config:` is declared on
                            // an artifact entry and the capsule is not one.
                            None,
                            &all_env,
                            &capability_policy,
                        )?,
                        http: WasiHttpCtx::new(),
                        http_hooks: NetworkPolicyHooks {
                            network_allow_rules: network_allow_rules.clone(),
                            inference_gateway: None,
                        },
                        network_allow_rules,
                        peer_fetch_rules,
                        peer_plane: Some(std::sync::Arc::clone(&peer_plane)),
                        peer_own_audience: own_peer_audience,
                        peer_trace: resource_trace,
                        delegation: delegation_plane,
                        plan_trace,
                        plan_counter: AtomicU64::new(0),
                        inference_env: all_env,
                        inference_gateway,
                        spend,
                        engine: engine.clone(),
                        workdir: workdir.clone(),
                        accessible_workdir: accessible_workdir.clone(),
                        tool_components,
                        artifact_grants,
                        allowlisted_tools,
                        installed_artifacts,
                        session_id: session_id.clone(),
                        pending_a2a_events: Vec::new(),
                        capability_policy,
                        protected_paths,
                        tool_annotations,
                        shell_enforcement: shell_enforcement_for_state,
                        current_traceparent: None,
                        current_task_provenance: None,
                        current_context_id: None,
                        live_delegations: Arc::clone(&live_delegations),
                        detached: Some(Arc::clone(&detached)),
                        shell_grace_secs: effective_lifecycle.shell_grace_secs,
                        a2a_task_registry: Some(Arc::clone(&task_registry)),
                        a2a_sse: Some((sse_tx.clone(), Arc::clone(&sse_buffer))),
                        a2a_task_id: None,
                        input_timeout_secs: effective_lifecycle.input_timeout_secs,
                        a2a_chunk_event_id: Arc::new(AtomicU64::new(u64::MAX / 4)),
                        a2a_chunks_emitted: Arc::new(AtomicBool::new(false)),
                        registry: registry_for_pull,
                        lock_path: lock_path_for_pull,
                        driver_continuation_id: None,
                        driver_continuation_context_id: None,
                        driver_continuation_acked_len: 0,
                    };

                    // Backing for the hooks' `murmur:runtime/inference` import.
                    // Sourced from `state` (built directly above) so a hook's
                    // `run-inference` runs the *same* driver component, under the
                    // same capability policy and network allowlist, as the agent
                    // loop's own turns. `None` when no driver artifact is staged.
                    let hook_inference = inference_driver_name
                        .as_ref()
                        .and_then(|driver_name| {
                            state
                                .tool_components
                                .get(driver_name)
                                .map(|component| (driver_name.clone(), component.clone()))
                        })
                        .map(|(driver_name, driver_component)| {
                            // Same grant `dispatch_tool_async` would apply to this driver, so
                            // a hook's `run-inference` cannot route around its narrowing.
                            let driver_grant = state.artifact_grants.get(&driver_name).cloned();
                            Arc::new(HookInferenceCtx {
                                driver_name,
                                driver_component,
                                model: inference_model.clone(),
                                engine: state.engine.clone(),
                                accessible_workdir: state.accessible_workdir.clone(),
                                workdir: state.workdir.clone(),
                                inference_env: state.inference_env.clone(),
                                capability_policy: state.capability_policy.clone(),
                                network_allow_rules: state.network_allow_rules.clone(),
                                driver_grant,
                                inference_gateway: state.inference_gateway.clone(),
                                spend: Arc::clone(&state.spend),
                                records: std::sync::Mutex::new(Vec::new()),
                                spend_refusals: std::sync::Mutex::new(Vec::new()),
                            })
                        });

                    // Create hooks ONCE — session_start fires once per capsule lifetime
                    let mut hooks = HookRuntime::new(
                        &engine,
                        &workdir,
                        &accessible_workdir,
                        hook_components,
                        SessionContextData {
                            capsule_name: capsule_name.clone(),
                            capsule_version: capsule_version.clone(),
                            session_id: session_id.clone(),
                            model: inference_model.clone(),
                            capabilities: capabilities.clone(),
                        },
                        HookEnvVars {
                            otel_endpoint: otel_endpoint.as_deref(),
                            eval_config_json: eval_config_json.as_deref(),
                            case_id: case_id.as_deref(),
                            dataset_id: dataset_id.as_deref(),
                        },
                        hook_limits,
                        hook_inference,
                        run_config.conversation_root.clone(),
                    )
                    .await?;

                    // on-session-start fires ONCE per launch, before the task loop —
                    // regardless of task_acceptance. For queue capsules this is the single
                    // session boundary that the per-task on-task-start events nest inside.
                    hooks.emit(&workdir, HookEvent::SessionStart).await;

                    // The session is addressable from here, and this is where it says so. A
                    // caller that sees the URL reads the record and then probes the door, so the
                    // two halves of the order are both load-bearing:
                    //
                    //   - the record exists before `on_url` announces the URL, or `mur ps` run
                    //     on the announcement finds nothing to list;
                    //   - the URL is announced only once `serve_http` is spawned on this
                    //     `LocalSet` and `session_start` is in the trace. The listener's backlog
                    //     accepts a connection from the moment it is bound, and until
                    //     `serve_http` is polled nothing reads it, so a probe sent into that
                    //     window waits out its read deadline and reports a live session as
                    //     unreachable. `serve_http` is first polled at the next `.await`, the
                    //     task loop's wait for work at the latest.
                    //
                    // A guard rather than a line at each return, bound in this future so it lives
                    // until the task loop has ended: a record that outlived its session would
                    // resolve an address onto a port nothing holds. Only the agent path reaches
                    // here; a script capsule binds nothing and is never addressable.
                    let _running_record = write_running_record(&running_record, &workdir);
                    on_url(&capsule_url);

                    // Seeded rather than assigned on every exit path: an iteration that only
                    // closes out work already in a lane can end without a result of its own, and
                    // then the last real task's outcome is the launch's outcome.
                    let mut final_loop_result: Result<AgentLoopExit, RuntimeError> =
                        Ok(AgentLoopExit::Ok);

                    // Set once the loop has stopped taking new work and is running only what is
                    // already in a lane. A task the runtime generated for itself never crossed
                    // the peer door, so `task_acceptance` does not gate it: without this,
                    // `single` and `none` would run the `task.md` task and leave a reconciled
                    // loss report unread with its marker already written, which is the one
                    // outcome reconciliation exists to prevent. Neither channel is read here, so
                    // nothing new can arrive and the loop still ends after one pass.
                    let mut closing_out = false;

                    // Tasks taken off the channel but not yet started. It outlives one iteration
                    // because a task drained while another was running has to still be here when
                    // that one finishes.
                    let mut lanes = LaneQueue::new();

                    // Event ids for the final status a task cancelled before it started emits.
                    // High, like `request-input`'s, so they never collide with the agent loop's
                    // own per-attempt counter, which restarts at 0 for every task.
                    let mut queued_cancel_event_id: u64 = u64::MAX / 8;

                    // Demoted commands the resumed-from session never accounted for. Only a
                    // resume does this, and it costs one read of a file `--resume` has already
                    // read; a launch that resumes nothing does no work here at all.
                    //
                    // An unmatched `shell_detached` can only mean the teardown sweep below never
                    // ran, because that sweep writes `shell_abandoned` for everything outstanding
                    // on every clean exit. The one over-report is a graceful exit whose own
                    // `write_shell_abandoned` failed, which reads here as unplanned death; for
                    // accounting that is the right direction to be wrong in.
                    if let (Some(from_session), Some(sessions_root)) =
                        (reconcile_from_session.as_deref(), workdir.parent())
                    {
                        if let Some(report) =
                            crate::detached_reconcile::reconcile_prior_session(
                                sessions_root,
                                from_session,
                                &session_id,
                                &task_context_id(supplied_context_id.as_deref()),
                            )
                            .await
                        {
                            enqueue_detached_report(
                                DetachedReport::Lost(report),
                                &task_registry,
                                &mut lanes,
                                &mut trace,
                            )
                            .await;
                        }
                    }

                    // Raised once, by the first `SIGTERM`. Every wait below that is not already a
                    // task's own cancel races it, and the loop takes no new work once it is up, so
                    // the session falls through to the same teardown a clean exit runs.
                    let terminating = crate::cancel::CancelSignal::new();
                    #[cfg(unix)]
                    if let Some(mut sigterm) = sigterm {
                        let task_registry = Arc::clone(&task_registry);
                        let terminating = terminating.clone();
                        tokio::spawn(async move {
                            if sigterm.recv().await.is_none() {
                                return;
                            }
                            // Cancelled before the signal is raised, so an agent loop that wakes
                            // on either finds its task already `Canceled`.
                            let _ = task_registry.lock().unwrap().cancel_every_live();
                            terminating.cancel();
                            eprintln!(
                                "[capsule-runtime] SIGTERM received — cancelling live tasks and ending the session"
                            );
                            std::thread::spawn(|| {
                                std::thread::sleep(TERMINATE_TEARDOWN_DEADLINE);
                                std::process::exit(143);
                            });
                            if sigterm.recv().await.is_some() {
                                std::process::exit(143);
                            }
                        });
                    }

                    // ── LOOP BODY STARTS HERE ──────────────────────────────
                    // Each iteration processes one task. Single/none modes break after
                    // the first iteration; queue+sleep iterates until channel closes.
                    'task_loop: loop {
                        if terminating.is_canceled() {
                            close_lanes_on_termination(
                                &mut lanes,
                                &task_registry,
                                &mut trace,
                                &detached,
                                &live_delegations,
                                &Some((sse_tx.clone(), Arc::clone(&sse_buffer))),
                                &mut queued_cancel_event_id,
                            )
                            .await;
                            break 'task_loop;
                        }
                        // ── WAIT FOR NEXT TASK ──
                        let (incoming_lane, incoming) = if closing_out {
                            let active = task_registry.lock().unwrap().active_lane();
                            match lanes.next(active) {
                                Some(selected) => selected,
                                None => break 'task_loop,
                            }
                        } else {
                            match effective_lifecycle.task_acceptance {
                                TaskAcceptance::None => {
                                    // Does not accept incoming tasks; run from task.md if present
                                    if workdir_task_md.exists() {
                                        let task_id = format!("tsk_{}", uuid::Uuid::now_v7().simple());
                                        let context_id = task_context_id(supplied_context_id.as_deref());
                                        let bytes = tokio::fs::metadata(&workdir_task_md)
                                            .await
                                            .map(|m| m.len())
                                            .unwrap_or(0);
                                        let provenance =
                                            TaskProvenance::derive(TaskOrigin::User, None);
                                        let _ = trace
                                            .write_task_start(
                                                &task_id,
                                                &context_id,
                                                "task_md",
                                                provenance,
                                                // A `task.md` task is a person's instruction, not a
                                                // child reporting back.
                                                None,
                                                bytes,
                                            )
                                            .await;
                                        let seed = hooks
                                            .dispatch_task_start(
                                                task_id.clone(),
                                                context_id.clone(),
                                                "task_md".to_string(),
                                                bytes,
                                                seed_budget_tokens,
                                                u64::from(context_window),
                                                agent::prior_history_tokens(
                                                    run_config.conversation_root.as_deref(),
                                                    &workdir,
                                                    &conversation_mode,
                                                    Some(&context_id),
                                                    run_config.resume.is_some(),
                                                ),
                                            )
                                            .await;
                                        otel.begin_session(None);
                                        state.current_traceparent = otel.outgoing_traceparent();
                                        state.current_task_provenance = Some(provenance);
                                        state.current_context_id = Some(context_id.clone());
                                        // run_task_with_reopens fires on-task-end, honors any
                                        // reopen-task within budget, and writes the terminal
                                        // task_end (with reopen_count) itself.
                                        let result = run_task_with_reopens(
                                            &mut state,
                                            &workdir,
                                            inference,
                                            effective_lifecycle.max_task_reopens,
                                            system_prompt.clone(),
                                            run_config.clone(),
                                            &mut hooks,
                                            &mut trace,
                                            &mut otel,
                                            None,
                                            None,
                                            &accessible_workdir,
                                            &capsule_name,
                                            &capsule_version,
                                            conversation_mode.clone(),
                                            Some(context_id.clone()),
                                            &task_id,
                                            seed,
                                            // No A2A task, so nothing a person can address a
                                            // `tasks/cancel` to; only `SIGTERM` cancels it.
                                            Some(terminating.clone()),
                                        )
                                        .await;
                                        let failed = result.is_err();
                                        final_loop_result = result;
                                        if failed {
                                            break 'task_loop;
                                        }
                                        closing_out = true;
                                        continue 'task_loop;
                                    } else {
                                        closing_out = true;
                                        continue 'task_loop;
                                    }
                                }
                                TaskAcceptance::Single | TaskAcceptance::Queue => {
                                    if workdir_task_md.exists() {
                                        // Backward compat: existing task.md → single run, no A2A
                                        let task_id = format!("tsk_{}", uuid::Uuid::now_v7().simple());
                                        let context_id = task_context_id(supplied_context_id.as_deref());
                                        let bytes = tokio::fs::metadata(&workdir_task_md)
                                            .await
                                            .map(|m| m.len())
                                            .unwrap_or(0);
                                        let provenance =
                                            TaskProvenance::derive(TaskOrigin::User, None);
                                        let _ = trace
                                            .write_task_start(
                                                &task_id,
                                                &context_id,
                                                "task_md",
                                                provenance,
                                                // A `task.md` task is a person's instruction, not a
                                                // child reporting back.
                                                None,
                                                bytes,
                                            )
                                            .await;
                                        let seed = hooks
                                            .dispatch_task_start(
                                                task_id.clone(),
                                                context_id.clone(),
                                                "task_md".to_string(),
                                                bytes,
                                                seed_budget_tokens,
                                                u64::from(context_window),
                                                agent::prior_history_tokens(
                                                    run_config.conversation_root.as_deref(),
                                                    &workdir,
                                                    &conversation_mode,
                                                    Some(&context_id),
                                                    run_config.resume.is_some(),
                                                ),
                                            )
                                            .await;
                                        otel.begin_session(None);
                                        state.current_traceparent = otel.outgoing_traceparent();
                                        state.current_task_provenance = Some(provenance);
                                        state.current_context_id = Some(context_id.clone());
                                        let result = run_task_with_reopens(
                                            &mut state,
                                            &workdir,
                                            inference,
                                            effective_lifecycle.max_task_reopens,
                                            system_prompt.clone(),
                                            run_config.clone(),
                                            &mut hooks,
                                            &mut trace,
                                            &mut otel,
                                            None,
                                            None,
                                            &accessible_workdir,
                                            &capsule_name,
                                            &capsule_version,
                                            conversation_mode.clone(),
                                            Some(context_id.clone()),
                                            &task_id,
                                            seed,
                                            Some(terminating.clone()),
                                        )
                                        .await;
                                        let _ = trace.flush().await;
                                        let failed = result.is_err();
                                        let single = matches!(
                                            effective_lifecycle.task_acceptance,
                                            TaskAcceptance::Single
                                        );
                                        if single || failed {
                                            final_loop_result = result;
                                            if failed {
                                                break 'task_loop;
                                            }
                                            closing_out = true;
                                            continue 'task_loop;
                                        }
                                        // Queue mode: remove task.md so the next iteration
                                        // falls through to task_rx.recv() for queued subtasks.
                                        let _ = tokio::fs::remove_file(&workdir_task_md).await;
                                        continue 'task_loop;
                                    }
                                    // Wait for the next task from the mpsc channel.
                                    // queue+sleep mode waits indefinitely — no self-terminating
                                    // timeout. The host (mur-roost) is responsible for shutdown.
                                    // All other modes apply MURMUR_A2A_TIMEOUT_SECS (default 30 s).
                                    let is_queue_sleep =
                                        effective_lifecycle.can_receive_background_tasks();

                                    loop {
                                        // Detached shell commands that finished are turned into
                                        // tasks first, so a completion delivered while the previous
                                        // task was running is in its lane before anything is chosen
                                        // — behind everything a person or a peer is waiting for.
                                        while let Ok(report) = completion_rx.try_recv() {
                                            enqueue_detached_report(
                                                report,
                                                &task_registry,
                                                &mut lanes,
                                                &mut trace,
                                            )
                                            .await;
                                        }
                                        // Everything already delivered goes into its lane before
                                        // anything is chosen, so the choice is made over the whole
                                        // backlog. A disconnected channel ends the drain and is
                                        // handled by the blocking wait below, which sees `None`.
                                        while let Ok(task) = task_rx.try_recv() {
                                            lanes.push(task);
                                        }
                                        if terminating.is_canceled() {
                                            close_lanes_on_termination(
                                                &mut lanes,
                                                &task_registry,
                                                &mut trace,
                                                &detached,
                                                &live_delegations,
                                                &Some((sse_tx.clone(), Arc::clone(&sse_buffer))),
                                                &mut queued_cancel_event_id,
                                            )
                                            .await;
                                            break 'task_loop;
                                        }
                                        let active = task_registry.lock().unwrap().active_lane();
                                        if let Some(selected) = lanes.next(active) {
                                            break selected;
                                        }

                                        let arrived = if is_queue_sleep {
                                            // A completion is a second thing worth waking for, so
                                            // the indefinite wait covers both channels. The
                                            // completion sender lives as long as the registry does,
                                            // so only `task_rx` can close, and it still ends the
                                            // loop when it does.
                                            tokio::select! {
                                                () = terminating.canceled() => break 'task_loop,
                                                arrived = task_rx.recv() => match arrived {
                                                    Some(task) => task,
                                                    None => {
                                                        final_loop_result = Ok(AgentLoopExit::Ok);
                                                        break 'task_loop;
                                                    }
                                                },
                                                Some(report) = completion_rx.recv() => {
                                                    enqueue_detached_report(
                                                        report,
                                                        &task_registry,
                                                        &mut lanes,
                                                        &mut trace,
                                                    )
                                                    .await;
                                                    continue;
                                                }
                                            }
                                        } else {
                                            let idle_timeout_secs: u64 =
                                                std::env::var("MURMUR_A2A_TIMEOUT_SECS")
                                                    .ok()
                                                    .and_then(|v| v.parse().ok())
                                                    .unwrap_or(30);
                                            // The timeout is on the whole wait, not on the task
                                            // channel alone: a completion is a second thing worth
                                            // waking for, and one that arrives inside the window
                                            // must not be left sitting until the window expires.
                                            match tokio::time::timeout(
                                                std::time::Duration::from_secs(idle_timeout_secs),
                                                async {
                                                    tokio::select! {
                                                        () = terminating.canceled() => Woke::Terminating,
                                                        arrived = task_rx.recv() => Woke::Task(arrived),
                                                        Some(report) = completion_rx.recv() => {
                                                            Woke::Report(report)
                                                        }
                                                    }
                                                },
                                            )
                                            .await
                                            {
                                                // Filed and reconsidered on the next pass around the
                                                // drain, alongside anything else queued.
                                                Ok(Woke::Report(report)) => {
                                                    enqueue_detached_report(
                                                        report,
                                                        &task_registry,
                                                        &mut lanes,
                                                        &mut trace,
                                                    )
                                                    .await;
                                                    continue;
                                                }
                                                Ok(Woke::Terminating) => break 'task_loop,
                                                Ok(Woke::Task(Some(task))) => task,
                                                Ok(Woke::Task(None)) => {
                                                    final_loop_result = Ok(AgentLoopExit::Ok);
                                                    break 'task_loop;
                                                }
                                                Err(_elapsed) => {
                                                    eprintln!("[capsule-runtime] no A2A message received within timeout; running with empty task");
                                                    otel.begin_session(None);
                                                    state.current_traceparent = otel.outgoing_traceparent();
                                                    final_loop_result = agent::run_agent_loop(
                                                        &mut state,
                                                        &workdir,
                                                        inference,
                                                        system_prompt,
                                                        run_config,
                                                        &mut hooks,
                                                        &mut trace,
                                                        &mut otel,
                                                        None,
                                                        None,
                                                        &accessible_workdir,
                                                        &capsule_name,
                                                        &capsule_version,
                                                        conversation_mode.clone(),
                                                        None,
                                                        // No task was ever put in scope on this
                                                        // path, so `on-task-start` never fired and
                                                        // there is no seed to apply.
                                                        None,
                                                        // Nor is there a task to cancel; only
                                                        // `SIGTERM` ends this attempt early.
                                                        Some(terminating.clone()),
                                                    )
                                                    .await;
                                                    break 'task_loop;
                                                }
                                            }
                                        };
                                        // Back around the drain: a task that landed while this one
                                        // was in flight is considered alongside it.
                                        lanes.push(arrived);
                                    }
                                }
                            }
                        };

                        // ── ACTIVATE TASK ──
                        // A task cancelled while it was still `submitted` never starts: no
                        // `task_start`, no `on-task-start`, no request to the provider. The
                        // registry already holds `Canceled` and has given the queue slot back,
                        // so all that is left is to say so and take the next task.
                        let cancel_signal = {
                            let mut reg = task_registry.lock().unwrap();
                            if reg.is_canceled(&incoming.task_id) {
                                None
                            } else {
                                reg.start_task(
                                    incoming.task_id.clone(),
                                    incoming.context_id.clone(),
                                    incoming_lane,
                                );
                                Some(reg.cancel_watch(&incoming.task_id))
                            }
                        };
                        let Some(cancel_signal) = cancel_signal else {
                            record_canceled_before_start(
                                &incoming,
                                &mut trace,
                                &detached,
                                &live_delegations,
                                &Some((sse_tx.clone(), Arc::clone(&sse_buffer))),
                                &mut queued_cancel_event_id,
                            )
                            .await;
                            continue 'task_loop;
                        };
                        if let Err(e) =
                            tokio::fs::write(&workdir_task_md, &incoming.message_text).await
                        {
                            eprintln!(
                                "[capsule-runtime] failed to write A2A message to task.md: {e}"
                            );
                        }
                        // Only a task that actually arrived over the peer door gets the
                        // received record; a completion the runtime produced for itself never
                        // crossed that boundary.
                        if incoming.source == crate::a2a::SOURCE_A2A {
                            let _ = trace
                                .write_a2a_task_received(
                                    &incoming.task_id,
                                    &incoming.context_id,
                                    &incoming.message_id,
                                    incoming.traceparent.as_deref(),
                                )
                                .await;
                        }
                        let _ = trace
                            .write_task_start(
                                &incoming.task_id,
                                &incoming.context_id,
                                incoming.source,
                                incoming.provenance,
                                incoming.delegation_id.as_deref(),
                                incoming.message_text.len() as u64,
                            )
                            .await;
                        // A task naming a delegation is that delegation's outcome arriving, which
                        // is where a `delegate-task` call that returned on start finally ends.
                        if let Some(delegation_id) = &incoming.delegation_id {
                            state.close_started_delegation(delegation_id).await;
                        }
                        let seed = hooks
                            .dispatch_task_start(
                                incoming.task_id.clone(),
                                incoming.context_id.clone(),
                                incoming.source.to_string(),
                                incoming.message_text.len() as u64,
                                seed_budget_tokens,
                                u64::from(context_window),
                                agent::prior_history_tokens(
                                    run_config.conversation_root.as_deref(),
                                    &workdir,
                                    &conversation_mode,
                                    Some(&incoming.context_id),
                                    run_config.resume.is_some(),
                                ),
                            )
                            .await;

                        // ── RUN AGENT LOOP ──
                        otel.begin_session(incoming.traceparent.as_deref());
                        state.current_traceparent = otel.outgoing_traceparent();
                        state.current_task_provenance = Some(incoming.provenance);
                        state.current_context_id = Some(incoming.context_id.clone());
                        state.a2a_task_id = Some(incoming.task_id.clone());
                        let loop_result = run_task_with_reopens(
                            &mut state,
                            &workdir,
                            inference,
                            effective_lifecycle.max_task_reopens,
                            system_prompt.clone(),
                            run_config.clone(),
                            &mut hooks,
                            &mut trace,
                            &mut otel,
                            Some(incoming.task_id.clone()),
                            Some((sse_tx.clone(), Arc::clone(&sse_buffer))),
                            &accessible_workdir,
                            &capsule_name,
                            &capsule_version,
                            conversation_mode.clone(),
                            Some(incoming.context_id.clone()),
                            &incoming.task_id,
                            seed,
                            Some(cancel_signal),
                        )
                        .await;

                        // ── POST-LOOP SLOT UPDATE ──
                        // task_end (with reopen_count) and the terminal on-task-end dispatch
                        // already happened inside run_task_with_reopens; an exhausted reopen
                        // budget surfaces here as loop_result.is_err(), i.e. a failed task.
                        // `finish_task` refuses to overwrite an accepted cancel whatever is
                        // passed, so this is the loop's own reading rather than the authority:
                        // an attempt that reported `canceled` says so here too.
                        let exit_state = match &loop_result {
                            Ok(AgentLoopExit::Canceled) => TaskState::Canceled,
                            Ok(_) => TaskState::Completed,
                            Err(_) => TaskState::Failed,
                        };
                        let _ = trace.flush().await;
                        {
                            let mut reg = task_registry.lock().unwrap();
                            reg.finish_task(exit_state);
                            // Immediately after the terminal state, so a resource-plane read that
                            // lands next reports the turn these bytes belong to.
                            reg.advance_resource_generation();
                        }

                        // A terminating session starts nothing after the task it was running:
                        // what is still in a lane gets its cancel recorded, and the loop ends.
                        if terminating.is_canceled() {
                            final_loop_result = loop_result;
                            close_lanes_on_termination(
                                &mut lanes,
                                &task_registry,
                                &mut trace,
                                &detached,
                                &live_delegations,
                                &Some((sse_tx.clone(), Arc::clone(&sse_buffer))),
                                &mut queued_cancel_event_id,
                            )
                            .await;
                            break 'task_loop;
                        }

                        // ── DECIDE WHETHER TO CONTINUE ──
                        // Closing out runs down whatever is already in a lane and then ends the
                        // loop, whatever `after_task` says: nothing can arrive to extend it.
                        if closing_out {
                            final_loop_result = loop_result;
                            continue 'task_loop;
                        }
                        match effective_lifecycle.after_task {
                            AfterTask::Exit => {
                                final_loop_result = loop_result;
                                break 'task_loop;
                            }
                            AfterTask::Sleep => {
                                if matches!(
                                    effective_lifecycle.task_acceptance,
                                    TaskAcceptance::Single
                                ) {
                                    // single mode always exits after one task
                                    final_loop_result = loop_result;
                                    break 'task_loop;
                                }
                                // Queue+sleep: clear task.md and wait for next task
                                let _ = tokio::fs::remove_file(&workdir_task_md).await;
                                continue 'task_loop;
                            }
                        }
                    }
                    // ── LOOP BODY ENDS HERE ────────────────────────────────

                    // on-session-end fires ONCE per launch, after the task loop exits.
                    // total_turns is the whole-launch aggregate accumulated by HookRuntime
                    // (one per Inference event across every task). exit_status is the last
                    // agent loop's own terminal outcome, so a launch that ended on a driver
                    // error or a spent turn budget says so rather than reading `"ok"` because
                    // the runtime kept the session alive to report it.
                    let session_exit_status = match &final_loop_result {
                        Ok(exit) => exit.as_str(),
                        Err(_) => "failed",
                    };
                    let session_total_turns = hooks.total_turns();
                    hooks
                        .emit(
                            &workdir,
                            HookEvent::SessionEnd {
                                total_turns: session_total_turns,
                                exit_status: session_exit_status.to_string(),
                            },
                        )
                        .await;

                    // Every async hook's queue is drained — and its worker awaited — while the
                    // `LocalSet` is still alive. Without this, `run_until` returning would drop
                    // the workers mid-call and take the session-end export with them. Bounded,
                    // so a wedged hook delays the exit by at most the drain budget; whatever it
                    // did not finish is reported through the same fault path as any other hook
                    // fault, which is why this runs *before* the flush below.
                    hooks.drain_async_hooks().await;
                    agent::flush_hook_dispatch_faults(&mut hooks, &mut trace).await;

                    // Work this session started and is not waiting for. Nothing here waits on a
                    // detached command — that is the point of having detached it — but the loss
                    // of its result is recorded rather than passed over in silence: a demoted
                    // command lives entirely in process memory, so nothing of it survives here.
                    let abandoned_at_ms = crate::trace::timestamp_ms();
                    // Outstanding work first, then the channel. `complete` removes a work id
                    // before it sends, so a command finishing during this teardown is briefly in
                    // neither place; reading `outstanding` first and draining second means it is
                    // seen in one or the other rather than falling between them. A command
                    // caught in both is recorded once.
                    let mut abandoned: Vec<AbandonedWork> = Vec::new();
                    for work in detached.outstanding() {
                        abandoned.push(AbandonedWork {
                            work_id: work.work_id,
                            binary: work.binary,
                            command: work.command,
                            disposition: AbandonedDisposition::StillRunning {
                                running_ms: abandoned_at_ms.saturating_sub(work.started_at_ms),
                            },
                        });
                    }
                    // Work that reported after the task loop stopped reading. No task will carry
                    // the result, so it is discarded on the same terms as work still running — but
                    // the exit code, the duration and the written output log all exist, and the
                    // record and the report both name them rather than flattening this case into
                    // the other one.
                    while let Ok(report) = completion_rx.try_recv() {
                        match report {
                            DetachedReport::Completed(completion) => {
                                if abandoned
                                    .iter()
                                    .any(|work| work.work_id == completion.work_id)
                                {
                                    continue;
                                }
                                let status = completion.status();
                                abandoned.push(AbandonedWork {
                                    work_id: completion.work_id,
                                    binary: completion.binary,
                                    command: completion.command,
                                    disposition: AbandonedDisposition::FinishedTooLate {
                                        exit_code: completion.exit_code,
                                        duration_ms: completion.duration_ms,
                                        output_path: completion.output_path,
                                        output_bytes: completion.output_bytes,
                                        resource_limit: completion.resource_limit,
                                        wait_error: completion.error,
                                        status,
                                    },
                                });
                            }
                            DetachedReport::Lost(_) => {}
                        }
                    }
                    // The discard is stated to the operator in full, on the two surfaces that are
                    // not `trace.jsonl`: there is no turn left to tell the agent in, so every
                    // remaining surface is the operator's.
                    if !abandoned.is_empty() {
                        let report = detached::abandonment_report_text(&session_id, &abandoned);
                        eprintln!("{report}");
                        agent::append_bootstrap_log(&workdir, &report);
                        for work in &abandoned {
                            let _ = trace
                                .write_shell_abandoned(
                                    &work.work_id,
                                    &work.binary,
                                    &work.command,
                                    work.running_ms(),
                                    work.recovered(),
                                )
                                .await;
                        }
                    }

                    let _ = trace
                        .write_session_end_if_not_ended(session_exit_status)
                        .await;
                    otel.emit_session_end_if_not_ended("failed").await;
                    trace.flush().await.map_err(|e| {
                        RuntimeError::AgentLoopFailed(format!("failed to flush trace: {e}"))
                    })?;

                    // Signal HTTP server to shut down, then wait for it
                    let _ = shutdown_tx.send(());
                    let _ = server_handle.await;

                    final_loop_result.map(|_| ())
                })
                .await
        });

        loop_result?;

        delegation.complete();
        roost_session.complete();
        return Ok(LaunchResult {
            session_id: session_id_ret,
            workdir: workdir_ret,
        });
    }

    // Script capsule path — requires a compiled WASM component.
    let capsule_component = staged
        .capsule_component
        .ok_or(RuntimeError::CapsuleCompile(
            "non-agent capsule has no compiled component".to_string(),
        ))?;

    let mut linker = Linker::new(&staged.engine);
    wasmtime_wasi::p2::add_to_linker_async(&mut linker)
        .map_err(|err| RuntimeError::Runtime(err.to_string()))?;
    wasmtime_wasi_http::p2::add_only_http_to_linker_sync(&mut linker)
        .map_err(|err| RuntimeError::Runtime(err.to_string()))?;

    // `murmur:tool-registry/invoke@0.1.0` is the one host-provided interface a
    // capsule guest imports. Register it by hand against the same `invoke::Host`
    // impl on `CapsuleStoreState` (the generated `invoke::add_to_linker` would do
    // the same, but this keeps the registration alongside the tool-side ones).
    {
        let iface = WIT_TOOL_REGISTRY_IFACE;
        linker
            .instance(iface)
            .map_err(|err| RuntimeError::Runtime(err.to_string()))?
            .func_wrap(
                "invoke",
                |mut store: wasmtime::StoreContextMut<'_, CapsuleStoreState>,
                 (tool_name, input): (String, murmur::tool::run::ToolInput)|
                 -> wasmtime::Result<(Result<murmur::tool::run::ToolResult, String>,)> {
                    Ok((invoke::Host::invoke(store.data_mut(), tool_name, input),))
                },
            )
            .map_err(|err| RuntimeError::Runtime(err.to_string()))?;
    }
    manage::add_to_linker::<_, HasSelf<_>>(&mut linker, |state| state)
        .map_err(|err| RuntimeError::Runtime(err.to_string()))?;
    send::add_to_linker::<_, HasSelf<_>>(&mut linker, |state| state)
        .map_err(|err| RuntimeError::Runtime(err.to_string()))?;

    // Read before `staged.capability_policy` moves into the store state below.
    let capsule_limits = staged.capability_policy.limits;

    let state = CapsuleStoreState {
        table: ResourceTable::new(),
        wasi: build_wasi_ctx(
            &staged.accessible_workdir,
            // The capsule component runs on the ceiling, not on any artifact's grant — so it gets
            // neither a narrowed workdir preopen, nor a state preopen, nor a config block. A
            // capsule cannot reach a tool's store, by construction and not by convention: it holds
            // no descriptor that names one.
            None,
            None,
            None,
            &inference_env,
            &staged.capability_policy,
        )?,
        http: WasiHttpCtx::new(),
        http_hooks: NetworkPolicyHooks {
            network_allow_rules: network_allow_rules.clone(),
            inference_gateway: None,
        },
        network_allow_rules,
        // A script capsule has no peer-handoff surface: `share-file` and `fetch-peer-file` are
        // agent-loop tools, and no WIT import exposes either to a wasm component. These are the
        // deny values rather than an omission — a future `murmur:peer-file` interface would fill
        // them here, from `staged.exports_peer_files` and `staged.capability_policy`.
        peer_fetch_rules: Vec::new(),
        peer_plane: None,
        peer_own_audience: String::new(),
        peer_trace: None,
        // Nor a plan surface: `submit-plan` is an agent-loop tool too, so a script capsule that
        // declares `capabilities.plan.submit` has nothing to call and nothing to record.
        plan_trace: None,
        plan_counter: AtomicU64::new(0),
        // Nor a delegation surface: `delegate-task` is an agent-loop tool and no WIT import
        // exposes delegation to a wasm component. A script capsule that declares
        // `capabilities.spawn.allow` still registers, and its credential is still what a
        // `capsule` plan step would delegate with — it simply has no tool to call.
        delegation: None,
        inference_env,
        inference_gateway: staged.inference_gateway.clone(),
        spend: Arc::clone(&staged.spend),
        engine: staged.engine.clone(),
        workdir: staged.workdir.clone(),
        accessible_workdir: staged.accessible_workdir.clone(),
        tool_components: staged.tool_components,
        artifact_grants: staged.artifact_grants,
        allowlisted_tools: staged.allowlisted_tools,
        installed_artifacts: staged.installed_artifacts,
        session_id: staged.session_id.clone(),
        pending_a2a_events: Vec::new(),
        capability_policy: staged.capability_policy,
        protected_paths: staged.protected_paths,
        tool_annotations: staged.tool_annotations,
        shell_enforcement: shell_enforcement.clone(),
        current_traceparent: None,
        current_task_provenance: None,
        current_context_id: None,
        live_delegations: Arc::new(crate::cancel::LiveDelegations::new()),
        // The script-capsule path runs no task loop, so a demoted command's completion would
        // have nowhere to be delivered: every command it dispatches runs to completion in the
        // foreground.
        detached: None,
        shell_grace_secs: 0,
        a2a_task_registry: None,
        a2a_sse: None,
        a2a_task_id: None,
        input_timeout_secs: None,
        a2a_chunk_event_id: Arc::new(AtomicU64::new(u64::MAX / 4)),
        a2a_chunks_emitted: Arc::new(AtomicBool::new(false)),
        registry: Arc::clone(&staged.registry),
        lock_path: staged.manifest_dir.join("murmur.lock"),
        driver_continuation_id: None,
        driver_continuation_context_id: None,
        driver_continuation_acked_len: 0,
        limits: capsule_limits.limiter(),
    };

    let mut store = Store::new(&staged.engine, state);
    // Must precede instantiation: `Store::limiter` latches the instance/table/memory counts
    // the store enforces, and instantiation itself allocates against them.
    store.limiter(|state| &mut state.limits);

    // Script capsule uses a multi-thread runtime so block_in_place works inside send::Host::send
    let rt = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .map_err(|e| RuntimeError::Runtime(format!("failed to create tokio runtime: {e}")))?;

    rt.block_on(async {
        // Instantiation runs the guest's own start/init code, so it gets a deadline too.
        store.set_epoch_deadline(capsule_limits.deadline_ticks());
        let instantiated = linker
            .instantiate_async(&mut store, &capsule_component)
            .await;
        let instance = match instantiated {
            Ok(instance) => instance,
            Err(err) => return Err(capsule_guest_error(&err, &store.data().limits)),
        };

        let capsule_iface =
            resolve_versioned_iface(&instance, &mut store, WIT_CAPSULE_IFACE_VERSIONED)
                .ok_or(RuntimeError::CapsuleExportMissing)?;
        let capsule_run = instance
            .get_export_index(&mut store, Some(&capsule_iface), "run")
            .and_then(|idx| instance.get_func(&mut store, idx))
            .ok_or(RuntimeError::CapsuleExportMissing)?;

        let run = capsule_run
            .typed::<(), ()>(&store)
            .map_err(|err| RuntimeError::Runtime(err.to_string()))?;

        // Fresh budget for `run` itself, so instantiation cost cannot eat into it.
        store.set_epoch_deadline(capsule_limits.deadline_ticks());
        let called = run.call_async(&mut store, ()).await;
        if let Err(err) = called {
            return Err(capsule_guest_error(&err, &store.data().limits));
        }

        Ok(())
    })?;

    // Drain any buffered a2a_send trace events from the capsule run.
    let pending = std::mem::take(&mut store.data_mut().pending_a2a_events);
    if !pending.is_empty() {
        rt.block_on(async {
            if let Ok(mut trace) = TraceWriter::open(
                &staged.workdir,
                staged.session_id.clone(),
                staged.capsule_name.clone(),
                staged.capsule_version.clone(),
                String::new(),
                Vec::new(),
                staged.scope_report.clone(),
                // This writer exists only to drain buffered `a2a_send` events; it writes no
                // record that can carry a hash or a body.
                murmur_artifact::TraceCapture::None,
                None,
                false,
                None,
                None,
                None,
                None,
            )
            .await
            {
                for (peer_url, message_id, task_id, context_id, traceparent, trust) in pending {
                    let _ = trace
                        .write_a2a_send(
                            &peer_url,
                            &message_id,
                            &task_id,
                            &context_id,
                            traceparent.as_deref(),
                            trust,
                        )
                        .await;
                }
                let _ = trace.flush().await;
            }
        });
    }

    // Notify the caller that the capsule has started (no URL for script capsules).
    on_url("");

    delegation.complete();
    roost_session.complete();
    Ok(LaunchResult {
        session_id: staged.session_id,
        workdir: staged.workdir,
    })
}

/// This session's entry for `~/.murmur/running/`, not yet written — see [`write_running_record`].
///
/// `outlives_launcher` is derived from whether the launching process has a controlling terminal.
/// A capsule started in a terminal dies with that window; one started without a terminal —
/// `nohup … </dev/null &`, a `setsid`, a service manager — survives whoever started it.
fn running_record_for(
    staged: &StagedSession,
    session_id: &str,
    capsule_url: &str,
) -> running::RunningRecord {
    let pid = std::process::id();
    running::RunningRecord {
        session_id: session_id.to_string(),
        url: capsule_url.to_string(),
        pid,
        // An unreadable start time is recorded as the empty string, which no freshly read token
        // equals, so the record fails layer 2 on the first read instead of resolving unverified.
        process_start: running::process_start_token(pid).unwrap_or_default(),
        capsule_name: staged.capsule_name.clone(),
        capsule_version: staged.capsule_version.clone(),
        workdir: staged.workdir.clone(),
        outlives_launcher: !running::has_controlling_terminal(),
        started_at: chrono::Utc::now().to_rfc3339(),
    }
}

/// Writes `record` into `~/.murmur/running/` and returns the guard that removes it.
///
/// `None` when the record could not be written, which warns `W-SEC-023` and changes nothing else:
/// the session runs and serves exactly as it would have, reachable by the URL `mur run` prints
/// rather than by session address.
fn write_running_record(
    record: &running::RunningRecord,
    workdir: &Path,
) -> Option<running::RunningGuard> {
    match running::RunningGuard::write(record) {
        Ok(guard) => Some(guard),
        Err(reason) => {
            let link = security_warning_link(W_SEC_023);
            let message = format!(
                "this session's record under ~/.murmur/running/ could not be written, so \
                 `mur watch` and `mur cancel` cannot reach it by session address — only by the \
                 URL it announces: {reason}"
            );
            eprintln!("[capsule-runtime] warning[{W_SEC_023}]: {message} ({link})");
            agent::append_bootstrap_log(
                workdir,
                &format!("[running-record] warning[{W_SEC_023}]: {message} ({link})"),
            );
            None
        }
    }
}

/// This session's registration with `mur-roost`, for exactly as long as the session runs.
///
/// Registration is one call and deregistration is its mirror; holding them in a guard is what
/// makes the pair total. `launch_session` has one `?` per staging step and two success returns,
/// and a session that ended without retiring its registration would leave a credential that still
/// verifies and a job the daemon still reports as `running`.
struct RoostSession {
    /// `None` for every session that declares no `capabilities.spawn.allow`, which registers
    /// nothing and therefore has nothing to retire.
    registered: Option<(String, SpawnCredential)>,
    outcome: SessionOutcome,
}

impl RoostSession {
    /// Registers `staged` and hands it the credential the daemon minted, or returns the refusal
    /// that stops the launch.
    fn register(staged: &mut StagedSession) -> Result<Self, RuntimeError> {
        // Two reasons to register, and a session with neither never opens a connection at all.
        //
        // A session that declares `capabilities.spawn.allow` must, because the daemon has to hold
        // its ceiling before it can referee anything it asks for. A session launched with a grant
        // must too, whatever it declares: presenting the approval is what marks it spent, and an
        // approval that is never presented would cover as many launches as a parent cared to make
        // from it.
        if staged.capability_policy.spawn_allow.is_empty() && staged.spawn_grant.is_none() {
            return Ok(Self {
                registered: None,
                // Never read: a session with nothing registered deregisters nothing.
                outcome: SessionOutcome::Failed,
            });
        }

        let roost_url = match std::env::var("MURMUR_ROOST_URL") {
            Ok(value) if !value.trim().is_empty() => value.trim().to_string(),
            _ => {
                return Err(RuntimeError::SpawnRegistrationFailed {
                    roost_url: "<unset>".to_string(),
                    reason: "MURMUR_ROOST_URL is not set".to_string(),
                })
            }
        };

        let credential = crate::registration::register_session(
            &roost_url,
            &staged.session_id,
            &staged.capsule_name,
            &staged.capsule_version,
            staged.spawn_grant.as_ref(),
        )?;
        staged.set_spawn_credential(credential.clone());
        Ok(Self {
            // A session that fails between here and a success return is reported as `failed`,
            // which is what a reader of `GET /status` would otherwise have to infer from silence.
            registered: Some((roost_url, credential)),
            outcome: SessionOutcome::Failed,
        })
    }

    /// The daemon and the credential this session presents to it, for the one other thing a
    /// registration is for: delegating.
    ///
    /// `None` for a session that registered nothing. The credential is cloned rather than
    /// borrowed because the plane outlives this guard's borrow, and it is still the same closed
    /// type — no `Display`, no `Serialize`, redacted `Debug`.
    fn endpoint(&self) -> Option<(&str, SpawnCredential)> {
        self.registered
            .as_ref()
            .map(|(url, credential)| (url.as_str(), credential.clone()))
    }

    fn complete(&mut self) {
        self.outcome = SessionOutcome::Complete;
    }
}

impl Drop for RoostSession {
    fn drop(&mut self) {
        if let Some((roost_url, credential)) = self.registered.take() {
            crate::registration::deregister_session(&roost_url, &credential, self.outcome);
        }
    }
}

/// This session's obligation to tell the capsule that delegated to it how it ended.
///
/// The mirror of [`RoostSession`], and a guard for the same reason: `launch_session` has one `?`
/// per staging step and two success returns, and a delegated child that ended without reporting
/// would leave a parent holding a delegation nothing ever closes. Defaults to
/// [`DelegationStatus::Error`] and is promoted by [`Self::complete`] at each success return, so
/// every path that is not a success reports as one that failed.
///
/// `max_turns_reached` is not distinguishable from here: the agent path collapses it into `Ok`
/// before the value leaves its async block, so a session that spent its turn budget reports `ok`.
/// The child's own trace holds the precise exit status, at a path the completion names.
struct DelegationReport {
    /// `None` for every capsule nobody delegated, which reports to nobody.
    handle: Option<SpawnerHandle>,
    capsule_name: String,
    capsule_version: String,
    session_id: String,
    /// The child's own directory — where `completion.json` goes, and the root the completion's
    /// `result_path` is relative to.
    accessible_workdir: PathBuf,
    /// This session's directory beneath it, the other place the runtime writes `out/result.txt`.
    session_workdir: PathBuf,
    started: Instant,
    status: crate::delegation::DelegationStatus,
}

impl DelegationReport {
    /// This session's obligation, taken from the handle staging already read.
    fn open(staged: &StagedSession) -> Result<Self, RuntimeError> {
        Ok(Self {
            handle: staged.spawner.clone(),
            capsule_name: staged.capsule_name.clone(),
            capsule_version: staged.capsule_version.clone(),
            session_id: staged.session_id.clone(),
            accessible_workdir: staged.accessible_workdir.clone(),
            session_workdir: staged.workdir.clone(),
            started: Instant::now(),
            status: crate::delegation::DelegationStatus::Error,
        })
    }

    fn complete(&mut self) {
        self.status = crate::delegation::DelegationStatus::Ok;
    }

    /// Where this session's result text landed, relative to the directory the completion names.
    ///
    /// Two places, one rule: a script capsule writes into its own preopen, which is the
    /// accessible workdir, and the agent loop writes into this session's directory beneath it.
    /// `None` when neither exists — a terminal path that failed without result text legitimately
    /// writes no file.
    fn result_path(&self) -> Option<String> {
        let relative = Path::new("out").join("result.txt");
        if self.accessible_workdir.join(&relative).is_file() {
            return Some("out/result.txt".to_string());
        }
        let session_result = self.session_workdir.join(&relative);
        if session_result.is_file() {
            return session_result
                .strip_prefix(&self.accessible_workdir)
                .ok()
                .map(|path| path.to_string_lossy().replace('\\', "/"));
        }
        None
    }
}

impl Drop for DelegationReport {
    /// Writes `completion.json` into this capsule's own directory and posts the notification to
    /// the address its parent injected. A delivery that fails is recorded in that file and on
    /// stderr; it never fails this session, whose work was already done.
    ///
    /// A handle that names no address writes nothing and posts nothing: the parent that made that
    /// delegation waits on the connection it already holds, so the child knows its parent and
    /// reports to nobody.
    fn drop(&mut self) {
        let Some(handle) = self.handle.take() else {
            return;
        };
        let Some(address) = handle.report_to.clone() else {
            return;
        };
        let outcome = crate::delegation::DelegationOutcome {
            delegation_id: handle.delegation_id.clone(),
            capsule_name: self.capsule_name.clone(),
            capsule_version: self.capsule_version.clone(),
            session_id: self.session_id.clone(),
            status: self.status,
            result_path: self.result_path(),
            workdir: self.accessible_workdir.display().to_string(),
            duration_ms: self
                .started
                .elapsed()
                .as_millis()
                .try_into()
                .unwrap_or(u64::MAX),
            // Reserved for a `crashed` or `terminated` outcome, neither of which a session can
            // report about itself.
            detail: None,
            reported_by: crate::delegation::Reporter::Child,
            delivered: false,
            delivery_error: None,
        };
        crate::delegation::report_completion(&handle, &address, outcome, &self.accessible_workdir);
    }
}

/// Reads a manifest-relative prompt file, returning the resolved path alongside any I/O
/// error so the caller can map it to its own `RuntimeError` variant.
fn read_prompt_file(manifest_dir: &Path, path: &str) -> Result<String, (PathBuf, std::io::Error)> {
    let prompt_path = manifest_dir.join(path);
    fs::read_to_string(&prompt_path).map_err(|source| (prompt_path, source))
}

fn resolve_system_prompt(
    manifest_dir: &Path,
    workdir: &Path,
    inference: &murmur_artifact::InferenceConfig,
) -> Result<Option<String>, RuntimeError> {
    if let Some(prompt) = inference.system_prompt.as_ref() {
        return Ok(Some(prompt.clone()));
    }

    if let Some(path) = inference.system_prompt_file.as_ref() {
        return read_prompt_file(manifest_dir, path)
            .map(Some)
            .map_err(|(prompt_path, source)| RuntimeError::SystemPromptFileRead {
                path: prompt_path.display().to_string(),
                source,
            });
    }

    if let Some(art_name) = inference.system_prompt_artifact.as_ref() {
        let skill_path = workdir.join("tools").join(art_name).join("skill.md");
        return fs::read_to_string(&skill_path).map(Some).map_err(|source| {
            RuntimeError::SystemPromptArtifactRead {
                name: art_name.clone(),
                source,
            }
        });
    }

    Ok(None)
}

/// Resolves the compaction system prompt from the two mutually exclusive manifest
/// sources — the inline `inference.compaction.system_prompt` string, or the contents of
/// the file named by `inference.compaction.system_prompt_file`, read relative to the
/// manifest directory. Absence stays absence: no default prompt is substituted, and the
/// hook receives `option::none`.
///
/// Mutual exclusion is enforced at manifest parse time, so an inline prompt winning here
/// is unreachable for a manifest that loaded successfully.
fn resolve_compaction_system_prompt(
    manifest_dir: &Path,
    compaction: Option<&murmur_artifact::CompactionConfig>,
) -> Result<Option<String>, RuntimeError> {
    let Some(compaction) = compaction else {
        return Ok(None);
    };

    if let Some(prompt) = compaction.system_prompt.as_ref() {
        return Ok(Some(prompt.clone()));
    }

    if let Some(path) = compaction.system_prompt_file.as_ref() {
        return read_prompt_file(manifest_dir, path)
            .map(Some)
            .map_err(
                |(prompt_path, source)| RuntimeError::CompactionSystemPromptFileRead {
                    path: prompt_path.display().to_string(),
                    source,
                },
            );
    }

    Ok(None)
}

fn capability_names(policy: &CapabilityPolicy) -> Vec<String> {
    let mut names = Vec::new();
    if !policy.network_allow.is_empty() {
        names.push("network".to_string());
    }
    if policy.filesystem_scope.is_some() {
        names.push("filesystem".to_string());
    }
    if !policy.shell_allow.is_empty() {
        names.push("shell".to_string());
    }
    names
}

/// Core message for the bash+network bypass warning (finding C-7 in
/// `murmur-security-assessment.md`) — shared verbatim between the stderr line and the
/// `logs/bootstrap.log` line so the two never drift apart.
const BASH_NETWORK_BYPASS_WARNING: &str = "capabilities.shell.allow includes \"bash\" and \
capabilities.network.allow is non-empty, but network.allow does not constrain bash's own \
outbound connections on this platform.";

/// Warns (non-fatal — matches the warn-and-continue convention of `murmur_md::write_murmur_md`
/// and the murmur.yaml-copy warning above) when `policy.shell_allow` contains the exact binary
/// name `"bash"` and `policy.network_allow` is non-empty. The check is an exact match on the
/// literal `"bash"`, not `shell::is_shell_interpreter` (which also matches `sh`/`zsh`/`fish`/
/// `dash`/`ksh`) — a deliberate scope limit matching C-7's own scoping, not an oversight.
pub(crate) fn warn_if_bash_network_bypass(workdir: &Path, policy: &CapabilityPolicy) {
    let has_bash = policy.shell_allow.iter().any(|binary| binary == "bash");
    if has_bash && !policy.network_allow.is_empty() {
        let link = security_warning_link(W_SEC_003);
        eprintln!("[capsule-runtime] warning[{W_SEC_003}]: {BASH_NETWORK_BYPASS_WARNING} ({link})");
        agent::append_bootstrap_log(
            workdir,
            &format!(
                "[capability-policy] warning[{W_SEC_003}]: {BASH_NETWORK_BYPASS_WARNING} ({link})"
            ),
        );
    }
}

const NO_COMPLETION_LANE_WARNING: &str = "this capsule declares capabilities.spawn.allow, but \
its lifecycle block cannot receive a delegation's outcome: delegate-task returns as soon as the \
sub-capsule is running, and what the sub-capsule did arrives afterwards as a background task. \
Declare lifecycle.task_acceptance: queue with lifecycle.after_task: sleep, and a \
lifecycle.queue_depth covering how many delegations one turn issues, or every outcome this \
capsule delegates for will be posted to a session that has already exited.";

/// Pure decision for the delegation-lifecycle warning, split out of
/// [`warn_for_unreachable_delegation_outcomes`] the same way `sandbox::aggregate_bounding_warning`
/// is split out of its emitter, so a test can assert it without capturing stderr.
///
/// Fires exactly where an outcome has nowhere to land: a capsule that can delegate and either
/// exits after its task or accepts no second one. Never a refusal — a capsule that delegates and
/// deliberately does not wait for the answer is legitimate, and this is what makes that a choice
/// rather than an accident.
pub(crate) fn unreachable_delegation_outcomes_warning(
    can_delegate: bool,
    lifecycle: &LifecycleConfig,
) -> Option<(&'static str, &'static str)> {
    (can_delegate && !lifecycle.can_receive_background_tasks())
        .then_some((W_SEC_020, NO_COMPLETION_LANE_WARNING))
}

/// Fires at every launch, not just once.
pub(crate) fn warn_for_unreachable_delegation_outcomes(
    workdir: &Path,
    can_delegate: bool,
    lifecycle: &LifecycleConfig,
) {
    if let Some((code, message)) = unreachable_delegation_outcomes_warning(can_delegate, lifecycle)
    {
        let link = security_warning_link(code);
        eprintln!("[capsule-runtime] warning[{code}]: {message} ({link})");
        agent::append_bootstrap_log(
            workdir,
            &format!("[capability-policy] warning[{code}]: {message} ({link})"),
        );
    }
}

const NO_SHELL_COMPLETION_LANE_WARNING: &str = "this capsule declares \
capabilities.shell.allow, but its lifecycle block cannot receive a background command's \
completion: a shell command that outruns lifecycle.shell_grace_secs is demoted to the background, \
and its exit code and output path arrive afterwards as a background task. Declare \
lifecycle.task_acceptance: queue with lifecycle.after_task: sleep, or every command this capsule \
demotes will be discarded at session end and reported to the operator instead of to the agent.";

/// Pure decision for the shell-lifecycle warning, split out of
/// [`warn_for_unreachable_shell_completions`] on the same terms as
/// [`unreachable_delegation_outcomes_warning`], so a test can assert it without capturing stderr.
///
/// Fires exactly where a completion has nowhere to land: a capsule that can run shell commands and
/// either exits after its task or accepts no second one. Deliberately not conditioned on
/// `lifecycle.shell_grace_secs` — `0` demotes on the first check after the spawn, so a low grace
/// makes the discard more likely rather than less, and no value of it turns demotion off.
pub(crate) fn unreachable_shell_completions_warning(
    can_run_shell: bool,
    lifecycle: &LifecycleConfig,
) -> Option<(&'static str, &'static str)> {
    (can_run_shell && !lifecycle.can_receive_background_tasks())
        .then_some((W_SEC_022, NO_SHELL_COMPLETION_LANE_WARNING))
}

/// Fires at every launch, not just once.
pub(crate) fn warn_for_unreachable_shell_completions(
    workdir: &Path,
    can_run_shell: bool,
    lifecycle: &LifecycleConfig,
) {
    if let Some((code, message)) = unreachable_shell_completions_warning(can_run_shell, lifecycle) {
        let link = security_warning_link(code);
        eprintln!("[capsule-runtime] warning[{code}]: {message} ({link})");
        agent::append_bootstrap_log(
            workdir,
            &format!("[capability-policy] warning[{code}]: {message} ({link})"),
        );
    }
}

/// Warns (non-fatal, once per declared grant) for every `capabilities.shell.interpreter_runtime`
/// entry. Declaring one narrows an allowlisted binary's Landlock scope to specific host
/// directories so a path-based interpreter can reach its stdlib — but it couples the capsule to a
/// specific host distro/interpreter-version layout (e.g. `/usr/lib/python3.11` stops resolving the
/// moment the host ships Python 3.12), which the operator should see plainly. The durable fix is
/// the still-unbuilt staged runtime bind-mount; this grant only bridges until then.
///
/// Shared verbatim between `mur run` (from [`stage_session`]) and `mur doctor`, so both surface
/// the same code, wording, and doc link. Like [`warn_on_inert_hook_capabilities`], it fires before
/// any session workdir exists (the capsule-ceiling check runs at the top of `stage_session`, and
/// `doctor` never launches a session at all), so it goes to stderr only, not `logs/bootstrap.log`.
pub fn warn_on_interpreter_runtime_grants(grants: &[InterpreterRuntimeGrant]) {
    for grant in grants {
        let link = security_warning_link(W_SEC_009);
        let dirs = grant
            .dirs
            .iter()
            .map(|dir| {
                let list = if dir.list_dir { "list_dir" } else { "no-list" };
                format!("{} ({list})", dir.path)
            })
            .collect::<Vec<_>>()
            .join(", ");
        eprintln!(
            "[capsule-runtime] warning[{W_SEC_009}]: capabilities.shell.interpreter_runtime grants \
             '{}' host directories outside the workdir [{dirs}] — this couples the capsule to a \
             specific host distro/interpreter-version layout (e.g. /usr/lib/python3.11 breaks the \
             moment the host ships Python 3.12); the durable fix is the staged runtime bind-mount, \
             which this grant only bridges until ({link})",
            grant.binary
        );
    }
}

/// Warns (non-fatal, once per session) when a capsule declares
/// `capabilities.filesystem.workdir_exec: true`.
///
/// This is the one grant that trades away an enforcement property rather than widening a scope:
/// with the workdir's Landlock `Execute` right granted, `capabilities.shell.allow` stops being
/// something the kernel can hold the capsule to — a binary it compiles, downloads or renames inside
/// its own workdir runs regardless. The declaration is legitimate (compile-and-run workflows need
/// it) and the class report already says `advisory`, but a class in a JSON field is easy to miss
/// and the reason for it is not self-evident, so it is also stated in words, once, at staging.
///
/// Shared shape with [`warn_on_interpreter_runtime_grants`]: fires before any session workdir
/// exists, so it goes to stderr only, not `logs/bootstrap.log`.
pub fn warn_on_workdir_exec(workdir_exec: bool) {
    if !workdir_exec {
        return;
    }
    let link = security_warning_link(W_SEC_011);
    eprintln!(
        "[capsule-runtime] warning[{W_SEC_011}]: capabilities.filesystem.workdir_exec is true — \
         the session workdir keeps its Landlock Execute right, so anything the capsule writes \
         there can run regardless of capabilities.shell.allow; this capsule reports containment \
         class 'advisory' on every host, including a Landlock-capable one ({link})"
    );
}

/// One credential-shaped entry of `capabilities.env.allow` that reaches every WASM guest.
///
/// The judgment is made from the name alone: nothing here reads the host environment, so the
/// warning an operator sees reads identically on a machine that has the variable set and one that
/// does not. A capsule's own value is never a diagnostic's business.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SecretShapedEnvGrant {
    /// The declared variable name, verbatim. Never its value.
    pub name: String,
    /// `true` when the resolved `lifecycle.after_task` is `Sleep`.
    pub outlives_launcher: bool,
}

/// Pure decision for the `capabilities.env.allow` secret warning, split out of
/// [`warn_on_secret_shaped_env_grants`] on the same terms as
/// [`unreachable_delegation_outcomes_warning`], so a test can assert it without capturing stderr.
///
/// One entry per distinct name that [`is_credential_shaped_env_name`] flags and the credential
/// backstop keeps, in declaration order — a name repeated in `env.allow` is judged once, because
/// the grant it describes is one grant. A name the backstop drops is passed over: it is refused at
/// staging with `E-CAP-016` by [`check_env_allow_reaches_guests`], and the skip reads
/// [`crate::credential_backstop_drops`] so the two agree with what
/// [`crate::shell::build_wasi_env_allowlist`] passes through.
///
/// `outlives_launcher` reads `lifecycle.after_task` directly instead of
/// [`LifecycleConfig::can_receive_background_tasks`]: that predicate also requires
/// `task_acceptance: queue`, and a `single` + `sleep` capsule still outlives the task that launched
/// it while holding the value.
pub fn secret_shaped_env_grants(
    policy: &CapabilityPolicy,
    lifecycle: &LifecycleConfig,
) -> Vec<SecretShapedEnvGrant> {
    let mut grants: Vec<SecretShapedEnvGrant> = Vec::new();

    for name in &policy.env_allow {
        if crate::shell::credential_backstop_drops(name, &policy.shell_strip_env) {
            continue;
        }
        if !is_credential_shaped_env_name(name) {
            continue;
        }
        if grants.iter().any(|grant| &grant.name == name) {
            continue;
        }
        grants.push(SecretShapedEnvGrant {
            name: name.clone(),
            outlives_launcher: lifecycle.after_task == AfterTask::Sleep,
        });
    }

    grants
}

/// The line body for one judged grant, so the two arms exist once rather than once per call site.
fn secret_shaped_env_grant_message(grant: &SecretShapedEnvGrant) -> String {
    let name = &grant.name;
    let held = if grant.outlives_launcher {
        "murmur does not broker this secret and cannot withdraw it, and lifecycle.after_task: \
         sleep keeps this capsule alive past the task that launched it, so it holds that value \
         with nothing left waiting on it"
    } else {
        "murmur does not broker this secret and cannot withdraw it: for as long as the capsule \
         runs, the capsule holds it"
    };

    format!(
        "capabilities.env.allow names '{name}', a credential-shaped variable the credential \
         backstop does not drop — every WASM guest this capsule runs observes the host's value. \
         {held}"
    )
}

/// Warns (non-fatal, once per distinct credential-shaped `capabilities.env.allow` entry) that the
/// capsule was handed a host secret murmur does not broker.
///
/// `capabilities.env.allow` is the one grant whose value murmur never sees, issues or revokes: an
/// operator names a host variable and the runtime passes it through. Without this line nothing
/// states that a name surviving the credential backstop reaches every WASM guest, so an operator
/// cannot ask which of their capsules holds what. A name the backstop drops is not reported here:
/// staging refuses it with `E-CAP-016`.
///
/// Never a refusal, including for the `after_task: sleep` combination: a long-lived worker holding
/// an operator-granted database password is an ordinary shape, and refusing it would make that
/// shape unbuildable. The combination gets its own sentence instead.
///
/// Shared verbatim between `mur run` and `mur doctor`, on the same terms as
/// [`warn_on_interpreter_runtime_grants`] — one emitter, two call sites, so the two surfaces cannot
/// word one grant differently. Resolves the lifecycle itself, from the manifest block and the CLI
/// override, so the `sleep` sentence follows `--lifecycle-after-task` as well as the manifest.
/// `lifecycle: None` means the manifest declared no block (`after_task` defaults to `exit`), and
/// `lifecycle_override: None` means the surface has no lifecycle flag to apply — which is `mur
/// doctor` always. Decided before any session workdir exists, so it goes to stderr only, not
/// `logs/bootstrap.log`.
pub fn warn_on_secret_shaped_env_grants(
    policy: &CapabilityPolicy,
    lifecycle: Option<&LifecycleConfig>,
    lifecycle_override: Option<&murmur_artifact::LifecycleOverride>,
) {
    let resolved = resolve_lifecycle(lifecycle.cloned(), lifecycle_override);
    for grant in secret_shaped_env_grants(policy, &resolved) {
        let link = security_warning_link(W_SEC_024);
        eprintln!(
            "[capsule-runtime] warning[{W_SEC_024}]: {} ({link})",
            secret_shaped_env_grant_message(&grant)
        );
    }
}

/// Warns (non-fatal, once per matching entry) when a `transport: http` capsule names its inference
/// endpoint in `capabilities.network.allow`.
///
/// The runtime reaches the provider itself, so inference no longer uses the entry. It still grants
/// tools, subprocesses and the driver direct reach to that host, without the key, which is why this
/// is a warning and not a refusal. Shared between `mur run` and `mur doctor` on the same terms as
/// [`warn_on_secret_shaped_env_grants`], and decided before any session workdir exists, so it goes
/// to stderr only.
pub fn warn_on_inference_endpoint_in_network_allow(
    policy: &CapabilityPolicy,
    inference: Option<&InferenceConfig>,
) {
    for entry in inference_endpoint_allow_entries(&policy.network_allow, inference) {
        let link = security_warning_link(W_SEC_025);
        eprintln!(
            "[capsule-runtime] warning[{W_SEC_025}]: capabilities.network.allow entry '{entry}' \
             names the inference endpoint; inference no longer uses it — the runtime reaches the \
             provider itself — so the entry now only grants tools, subprocesses and the driver \
             direct reach to that host without the key ({link})"
        );
    }
}

/// Warns (non-fatal, once) when a `transport: http` capsule's `inference.api_key` can only be read
/// at launch: a literal in the manifest, or a `${NAME}` that the global config's `credentials:`
/// map does not hold and the environment supplies.
///
/// Such a capsule keeps the key it launched with, so a key rotated with `mur config set -g
/// credentials.NAME` does not reach it until it restarts. Reads only whether `credentials_file`
/// holds the name, never prints a value, and stays silent for a `${NAME}` found nowhere — staging
/// refuses that one. Shared between `mur run` and `mur doctor` on the same terms as
/// [`warn_on_inference_endpoint_in_network_allow`].
pub fn warn_on_launch_only_inference_credential(
    inference: Option<&InferenceConfig>,
    credentials_file: Option<&Path>,
) {
    let Some(reference) = inference
        .filter(|inference| inference.transport == "http")
        .and_then(|inference| inference.api_key.as_ref())
    else {
        return;
    };
    let (source, name) = match reference {
        ApiKeyReference::Literal(_) => (
            "inference.api_key is written literally in murmur.yaml".to_string(),
            "<NAME>",
        ),
        ApiKeyReference::Environment(name) => {
            if credentials_file.is_some_and(|path| config_holds_credential(path, name))
                || std::env::var_os(name).is_none_or(|value| value.is_empty())
            {
                return;
            }
            (
                format!(
                    "inference.api_key: ${{{name}}} is read from the environment variable {name}, \
                     because credentials.{name} is not set in the global config"
                ),
                name.as_str(),
            )
        }
    };
    let link = security_warning_link(W_SEC_027);
    eprintln!(
        "[capsule-runtime] warning[{W_SEC_027}]: {source}, so the key is read once at launch and \
         this capsule cannot pick up a rotated key until it is restarted; store the key with \
         `mur config set -g credentials.{name} <key>` to have it re-read ({link})"
    );
}

/// Print `W-SEC-026` when `spend.machine_tokens_per_day` is in effect and the capsule uses
/// `transport: process`.
///
/// That transport's CLI reaches its provider with its own credentials, so nothing it spends passes
/// the inference gateway and the machine ceiling does not cover it. Shared between `mur run` and
/// `mur doctor` on the same terms as [`warn_on_inference_endpoint_in_network_allow`]: decided
/// before any session workdir exists, so it goes to stderr only. Never a refusal.
pub fn warn_on_machine_spend_ceiling_under_process_transport(
    machine_tokens_per_day: Option<u64>,
    inference: Option<&InferenceConfig>,
) {
    if machine_tokens_per_day.is_none()
        || !inference.is_some_and(|inference| inference.transport == "process")
    {
        return;
    }
    let link = security_warning_link(W_SEC_026);
    eprintln!(
        "[capsule-runtime] warning[{W_SEC_026}]: spend.machine_tokens_per_day is set and this \
         capsule uses transport: process — the CLI reaches its provider with its own credentials, \
         so murmur neither counts nor limits this capsule's spend ({link})"
    );
}

/// The `network_allow` entries whose rule matches the `transport: http` inference endpoint, in
/// declaration order. An entry that does not parse matches nothing: validation refuses it
/// elsewhere.
fn inference_endpoint_allow_entries<'a>(
    network_allow: &'a [String],
    inference: Option<&InferenceConfig>,
) -> Vec<&'a str> {
    let Some(endpoint) = inference
        .filter(|inference| inference.transport == "http")
        .and_then(|inference| inference.endpoint.as_deref())
    else {
        return Vec::new();
    };
    let Some(target) = endpoint
        .parse::<http::Uri>()
        .ok()
        .and_then(|uri| RequestTarget::from_request(&uri, uri.scheme_str() == Some("https")))
    else {
        return Vec::new();
    };
    network_allow
        .iter()
        .filter(|entry| NetworkAllowRule::parse(entry).is_ok_and(|rule| rule.matches(&target)))
        .map(String::as_str)
        .collect()
}

/// Warns (non-fatal, once per allowlisted interpreter) when `capabilities.filesystem.read_only`
/// is declared alongside a binary that can construct a write the dispatch-time analyser cannot
/// see.
///
/// The analyser reads a shell call's argv and its `-c` script body. An interpreter's own file I/O
/// is in neither: `python3 -c "open(p,'w').write(x)"` is one opaque argument, and nothing in it
/// names a redirection or a write verb. The declaration still holds for every call the analyser
/// can read and for the whole tool path — this names the one route around the shell half rather
/// than leaving an operator to discover it.
///
/// Deliberately not a refusal: the pairing is legitimate and common, and the answer to it is the
/// kernel-backing layer, not a manifest rule. Same seam as [`warn_on_workdir_exec`] — fires at
/// staging, before any session workdir exists, so it goes to stderr only.
fn warn_on_advisory_read_only(read_only: &[String], shell_allow: &[String]) {
    // The same resolver `--explain-scope` and `mur doctor` report from, so the set this warns
    // about and the set they print `advisory against` cannot drift apart.
    for binary in crate::containment::read_only_advisory_for(read_only, shell_allow) {
        let link = security_warning_link(W_SEC_017);
        eprintln!(
            "[capsule-runtime] warning[{W_SEC_017}]: capabilities.filesystem.read_only is \
             declared and capabilities.shell.allow includes '{binary}', an interpreter that \
             can construct a write the dispatch check cannot read — the declaration is \
             advisory for that binary. It still holds for every tool call and for every \
             shell command whose write the dispatch check can identify ({link})"
        );
    }
}

/// Warns (non-fatal, once per installed tool) when a capsule that declares
/// `capabilities.filesystem.read_only` installs a tool whose `input_schema` leaves a path-shaped
/// or destination-shaped property unannotated.
///
/// Such a property is judged by key name — the analyser guesses whether it is a filesystem
/// destination from [`crate::protected_paths::TOOL_PATH_KEYS`] and
/// [`crate::protected_paths::TOOL_DESTINATION_KEYS`] — and a guess is wrong in both directions: a
/// stored payload carrying a `{file, text}` pair is refused as a write, and a destination under an
/// unrecognized name is not checked. The tool's own schema can say which it is.
///
/// The decision is [`crate::tool_annotations::unannotated_path_properties`], which is per property
/// rather than per tool: annotating one property leaves every other one still guessed at, so the
/// warning names each of them. A schema-root
/// [`crate::tool_annotations::KEYWORD_DESTINATIONS`] list answers for the whole tool and silences
/// it; nothing on the capsule's side can.
///
/// Only the capsule's own installed artifacts are considered. The synthetic manifests the runtime
/// writes (the shell binaries, the peer-handoff tools, `delegate-task`) are not an operator's to
/// annotate.
fn warn_on_unannotated_tool_schemas(installed_manifests: &[(String, String)]) {
    for (tool, manifest_yaml) in installed_manifests {
        let Some(schema) = crate::tool_annotations::schema_from_manifest_yaml(manifest_yaml) else {
            continue;
        };
        let properties = crate::tool_annotations::unannotated_path_properties(&schema);
        if properties.is_empty() {
            continue;
        }
        let named = properties
            .iter()
            .map(|property| format!("'{property}'"))
            .collect::<Vec<_>>()
            .join(", ");
        let (noun, pronoun) = if properties.len() == 1 {
            ("property", "it")
        } else {
            ("properties", "them")
        };
        let link = security_warning_link(W_SEC_018);
        eprintln!(
            "[capsule-runtime] warning[{W_SEC_018}]: capabilities.filesystem.read_only is \
             declared and the tool '{tool}' declares the {noun} {named} with no murmur \
             annotation in effect — calls naming {pronoun} are judged by key name. Annotate a \
             destination property with \"format\": \"{destination}\", any object the tool only \
             stores with \"format\": \"{opaque}\", and a destination derived from another \
             property — or the absence of any — with the schema-root \"{keyword}\" list ({link})",
            destination = crate::tool_annotations::FORMAT_DESTINATION,
            opaque = crate::tool_annotations::FORMAT_OPAQUE,
            keyword = crate::tool_annotations::KEYWORD_DESTINATIONS,
        );
    }
}

/// Warns (non-fatal, once per session) when this host's unprivileged user namespaces are
/// unrestricted because `kernel.apparmor_restrict_unprivileged_userns` is off, rather than because
/// the shipped `mur-sealed` AppArmor profile is confining this binary.
///
/// The two hosts back `sealed` and the capsule network namespace equally well, and neither is
/// refused. They differ in blast radius: the profile grants one binary permission to create a user
/// namespace, while the sysctl grants it to everything on the machine, which is the hardening
/// Ubuntu 23.10+ ships on precisely because unprivileged user namespaces are a recurring local
/// privilege-escalation surface. Both reach the same achieved class, so without this warning a
/// `sealed` result on a weakened host reads in the record exactly like one obtained through the
/// mechanism murmur ships.
///
/// Takes the probed grant rather than probing, so `mur run`'s staging path and `mur doctor` state
/// one warning in one wording, and so the decision is testable without a host that has AppArmor.
/// Every other grant, including [`UsernsGrant::Withheld`], is silent here — `Withheld` is already
/// carried by `E-CAP-003`/`E-CAP-005` where it actually blocks something.
pub fn warn_on_userns_restriction_disabled_host_wide(grant: Option<UsernsGrant>) {
    if grant != Some(UsernsGrant::RestrictionDisabledHostWide) {
        return;
    }
    let link = security_warning_link(W_SEC_013);
    eprintln!(
        "[capsule-runtime] warning[{W_SEC_013}]: kernel.apparmor_restrict_unprivileged_userns is \
         off on this host, so unprivileged user namespaces are unrestricted for every binary on \
         the machine, not just for mur — this is what makes sealed containment and the capsule \
         network namespace work here, and it is not the configuration murmur ships. To get the \
         narrow, mur-only grant instead: restore the knob to 1 (removing any \
         /etc/sysctl.d/*-userns.conf drop-in that sets it to 0), then install and load the shipped \
         profile with `sudo install -m 644 packaging/apparmor/{profile} {path} && sudo \
         apparmor_parser -r {path}`. Nothing is refused because of this ({link})",
        profile = crate::sealed::SEALED_APPARMOR_PROFILE_NAME,
        path = crate::sealed::SEALED_APPARMOR_PROFILE_PATH,
    );
}

/// Warns (non-fatal, once per session) when the capsule's own top-level `capabilities.state` is
/// declared, because that declaration reaches nothing.
///
/// A durable state store is granted per artifact — it is the tool, driver or hook entry that gets
/// the second preopen, and the capsule's own guest is built with no artifact grant at all. So a
/// capsule-wide block creates no directory and opens no `state/` path for anybody. Structurally
/// valid, hence warned rather than refused, on the same terms as `W-SEC-006` and `W-SEC-008`; but
/// stated plainly, because the alternative signal an operator gets is an empty directory that
/// never appears.
///
/// Same seam as [`warn_on_workdir_exec`]: fires at staging, before any session workdir exists, so
/// it goes to stderr only and not to `logs/bootstrap.log`.
fn warn_on_inert_capsule_wide_state(state_declared: bool) {
    if !state_declared {
        return;
    }
    let link = security_warning_link(W_SEC_014);
    eprintln!(
        "[capsule-runtime] warning[{W_SEC_014}]: capsule-wide capabilities.state is declared, but \
         a durable state store is granted per artifact — nothing reads a top-level declaration, \
         so no store was created and no 'state' preopen exists. Move the block onto the tool, \
         driver or hook entry that needs it ({link})"
    );
}

/// Warns (non-fatal, once per session) when the capsule's own top-level
/// `capabilities.conversation` is declared, because that declaration reaches nothing.
///
/// The grant is per artifact, on the `runtime: hook` entry whose component imports
/// `murmur:conversation/read`; the capsule's own guest holds no artifact grant and compiles
/// against a world with no such import. Same seam and same terms as
/// [`warn_on_inert_capsule_wide_state`].
fn warn_on_inert_capsule_wide_conversation(conversation_declared: bool) {
    if !conversation_declared {
        return;
    }
    let link = security_warning_link(W_SEC_016);
    eprintln!(
        "[capsule-runtime] warning[{W_SEC_016}]: capsule-wide capabilities.conversation is \
         declared, but the murmur:conversation/read grant is per artifact — nothing reads a \
         top-level declaration, so no artifact can read the conversation record. Move the block \
         onto the hook entry that needs it ({link})"
    );
}

/// A per-hook `capabilities:` block reuses the whole [`murmur_artifact::Capabilities`]
/// vocabulary, but only `network`, `filesystem`, `state` and `task_io` govern a hook — the rest are
/// capsule-wide concerns nothing reads per-artifact. Warn rather than reject (the block is
/// structurally valid) so an operator who declared, say, `shell.allow` on a hook entry learns
/// it is inert instead of assuming it was applied. Infallible and non-fatal, like
/// [`warn_if_bash_network_bypass`], and carries the same `W-SEC-*` registry code + doc link
/// convention as every other non-fatal capability warning (see `security_warnings.rs`).
///
/// Not written to `logs/bootstrap.log`, unlike [`warn_if_bash_network_bypass`]: this fires
/// during artifact staging in [`stage_session`], before the session workdir
/// `warn_if_bash_network_bypass`/`sandbox::warn_for_enforcement_tier` write into even exists.
fn warn_on_inert_hook_capabilities(
    hook_name: &str,
    capabilities: Option<&murmur_artifact::Capabilities>,
) {
    let inert = inert_capability_sub_blocks(capabilities);
    if !inert.is_empty() {
        let link = security_warning_link(W_SEC_006);
        eprintln!(
            "[capsule-runtime] warning[{W_SEC_006}]: hook '{hook_name}' declares capabilities.{} \
             which the runtime does not apply per-hook — only capabilities.network, \
             capabilities.filesystem, capabilities.state and capabilities.task_io govern a hook \
             ({link})",
            inert.join(", capabilities.")
        );
    }
}

/// The sub-blocks a per-artifact `capabilities:` grant never reads, whichever role declared
/// it. Shared by the hook (`W-SEC-006`) and tool/driver (`W-SEC-008`) warnings, which differ
/// only in code and wording — the hazard, and the set of inert keys, is identical.
fn inert_capability_sub_blocks(
    capabilities: Option<&murmur_artifact::Capabilities>,
) -> Vec<&'static str> {
    let Some(capabilities) = capabilities else {
        return Vec::new();
    };

    [
        ("shell", capabilities.shell.is_some()),
        ("spawn", capabilities.spawn.is_some()),
        ("env", capabilities.env.is_some()),
        ("limits", capabilities.limits.is_some()),
        // Same hazard as its siblings: host-process bounds are session-scoped (one cgroup scope,
        // one workdir guard, one set of rlimits per spawned process), so a per-artifact or
        // per-hook `resources:` block is structurally accepted and silently inert.
        ("resources", capabilities.resources.is_some()),
        // The containment floor is capsule-wide, resolved before staging — a per-artifact
        // declaration of it is read by nothing.
        ("containment", capabilities.containment.is_some()),
    ]
    .into_iter()
    .filter_map(|(name, present)| present.then_some(name))
    .collect()
}

/// Lower one tool's or driver's per-artifact grant and record it, warning about anything the
/// operator declared that narrowing will not honor.
///
/// Called from the WASM-tool and driver staging arms only. Inserting nothing when the entry
/// declares neither `capabilities:` nor `config:` is what makes the absent case a strict no-op:
/// dispatch looks the artifact up by name and falls back to the session's own policy on a miss.
///
/// The two keys are independent, which is why either one alone stages a grant. `config:` on its
/// own narrows nothing and widens nothing — the staged grant equals [`ToolCapabilityGrant`]'s
/// [`Default`] in every field but `config_json`, so the artifact keeps inheriting the capsule
/// ceiling wholesale and simply gains one environment variable.
fn stage_artifact_grant(
    artifact: &ArtifactRequest,
    ceiling_network_allow_rules: &[NetworkAllowRule],
    capsule_name: &str,
    artifact_grants: &mut HashMap<String, ToolCapabilityGrant>,
) -> Result<(), RuntimeError> {
    if artifact.capabilities.is_none() && artifact.config.is_none() {
        return Ok(());
    }
    let capabilities = artifact.capabilities.as_ref();

    // Derived from `artifact` — the operator's own manifest entry — and never from the
    // artifact's bundled `murmur.yaml`, so a tool pulled from a registry cannot scope itself
    // up. `capsule_name` is operator-sourced for the same reason: it is what an undeclared
    // `capabilities.state.store` defaults to, and a registry-pulled tool must not be able to
    // name the store it lands in. Deriving at staging (not at dispatch) means a malformed grant
    // fails the run before any guest starts.
    let mut grant =
        ToolCapabilityGrant::derive(capabilities, ceiling_network_allow_rules, capsule_name)?;
    // The one side effect on this path, and it happens only for an entry that declared a store:
    // `derive` validated the name and left the directory to be made here, so lowering stays pure
    // and a run that never reaches staging creates nothing on disk.
    if let Some(store) = grant.state_store.as_deref() {
        grant.state_dir = Some(crate::state_store::ensure_state_store(store)?);
    }
    // Operator-sourced on the same rule as the grant, and filled here rather than in `derive`
    // because `config:` sits beside `capabilities:` in the entry, not inside it.
    grant.config_json = artifact
        .config
        .as_ref()
        .map(|config| crate::artifact_config::lower_artifact_config(&artifact.name, config))
        .transpose()?;
    warn_on_out_of_ceiling_network_entries(&artifact.name, &grant.dropped_network_entries);
    warn_on_inert_tool_capabilities(&artifact.name, capabilities);
    artifact_grants.insert(artifact.name.clone(), grant);
    Ok(())
}

/// A per-artifact `network.allow` entry the capsule-wide ceiling does not itself allow was
/// dropped rather than granted — narrowing only ever subtracts. Non-fatal on purpose: the
/// resulting posture is strictly *tighter* than the operator asked for, so failing staging
/// would punish a safe mistake, but a silent drop would leave them believing a host is
/// reachable when it is not.
fn warn_on_out_of_ceiling_network_entries(artifact_name: &str, dropped: &[String]) {
    if dropped.is_empty() {
        return;
    }

    let link = security_warning_link(W_SEC_007);
    eprintln!(
        "[capsule-runtime] warning[{W_SEC_007}]: artifact '{artifact_name}' declares \
         capabilities.network.allow entries the capsule-wide ceiling does not allow ({}) — \
         they are dropped, not granted, because per-artifact capabilities can only narrow \
         ({link})",
        dropped.join(", ")
    );
}

/// The tool/driver counterpart of [`warn_on_inert_hook_capabilities`]: a per-artifact grant reads
/// only `network`, `filesystem` and `state`, so any other sub-block is structurally valid and
/// silently inert. Warn rather than reject, matching how every other capability-posture issue
/// is reported.
fn warn_on_inert_tool_capabilities(
    artifact_name: &str,
    capabilities: Option<&murmur_artifact::Capabilities>,
) {
    let inert = inert_capability_sub_blocks(capabilities);
    if !inert.is_empty() {
        let link = security_warning_link(W_SEC_008);
        eprintln!(
            "[capsule-runtime] warning[{W_SEC_008}]: artifact '{artifact_name}' declares \
             capabilities.{} which per-artifact narrowing does not apply — only \
             capabilities.network, capabilities.filesystem and capabilities.state apply to a tool \
             or driver ({link})",
            inert.join(", capabilities.")
        );
    }
}

/// A `runtime: tool` artifact with a native (non-WASM) implementation runs as a host
/// subprocess under the capsule-wide shell/sandbox machinery, never through the WASI tool
/// path per-artifact grants are applied on. Declaring one is therefore wholly inert, which is
/// a sharper hazard than an inert sub-block and gets the same `W-SEC-008` treatment.
fn warn_on_unenforceable_native_capabilities(
    artifact_name: &str,
    capabilities: Option<&murmur_artifact::Capabilities>,
) {
    if capabilities.is_none() {
        return;
    }

    let link = security_warning_link(W_SEC_008);
    eprintln!(
        "[capsule-runtime] warning[{W_SEC_008}]: artifact '{artifact_name}' declares \
         per-artifact 'capabilities:' but ships a native implementation — narrowing applies \
         only to WASM tools and drivers, so this grant is not enforced ({link})"
    );
}

/// A `runtime: tool` artifact with a native (non-WASM) implementation runs as a host subprocess
/// under the capsule-wide shell environment, which is not per-artifact — nothing there would
/// deliver `MURMUR_ARTIFACT_CONFIG`, and the runtime will not write an operator's config block
/// into a capsule-wide environment to fake it. A declared block is therefore wholly inert, and
/// gets the `W-SEC-015` treatment its `capabilities:` sibling above gets.
fn warn_on_inert_native_config(artifact_name: &str, config: Option<&serde_yaml::Value>) {
    if config.is_none() {
        return;
    }

    let link = security_warning_link(W_SEC_015);
    eprintln!(
        "[capsule-runtime] warning[{W_SEC_015}]: artifact '{artifact_name}' declares 'config:' \
         but ships a native implementation — a native tool runs as a host subprocess and reads no \
         per-artifact config, so no MURMUR_ARTIFACT_CONFIG is delivered ({link})"
    );
}

/// Builds the single `Engine` a session runs every guest on.
///
/// `epoch_interruption` compiles a deadline check into wasm loop back-edges and function
/// entries. It only arms the mechanism: a deadline fires solely when some store has called
/// `set_epoch_deadline` *and* an [`EpochTicker`] is advancing this engine's epoch, both of
/// which `stage_session` sets up.
pub(crate) fn build_engine() -> Result<Engine, RuntimeError> {
    let mut config = Config::new();
    config.wasm_component_model(true);
    config.epoch_interruption(true);
    Engine::new(&config).map_err(|err| RuntimeError::Runtime(err.to_string()))
}

/// Map a failed capsule-guest invocation onto the most specific `RuntimeError` available,
/// so a deadline or resource-limit trap is distinguishable from a guest panic rather than
/// collapsing into the generic `CapsuleTrap` bucket.
fn capsule_guest_error(error: &wasmtime::Error, limiter: &ExecutionLimiter) -> RuntimeError {
    match classify_guest_failure(error, limiter) {
        GuestFailure::DeadlineExceeded { seconds } => {
            RuntimeError::CapsuleDeadlineExceeded { seconds }
        }
        GuestFailure::ResourceLimit { message } => RuntimeError::CapsuleResourceLimit { message },
        GuestFailure::Other => RuntimeError::CapsuleTrap(error.to_string()),
    }
}

fn map_registry_error(name: &str, version: &str, error: RegistryError) -> RuntimeError {
    match error {
        RegistryError::NotFound { .. } => RuntimeError::artifact_not_found(name, version),
        RegistryError::IntegrityMismatch { .. } => {
            RuntimeError::artifact_integrity_failed(name, version)
        }
        other => RuntimeError::Runtime(other.to_string()),
    }
}

/// Build a guest's WASI context with a scoped environment: no host inheritance, only what
/// `policy.env_allow` declares (credential-filtered) plus the runtime's own `extra_env`.
///
/// `extra_env` is applied last so a manifest cannot shadow a runtime-owned `MURMUR_*` value
/// by allowlisting its name.
///
/// `filesystem_scope` is a per-artifact narrowing of what gets preopened as `"."`: `None`
/// preopens `workdir` itself, which is what every caller without a per-artifact grant passes —
/// the wide default, and the threat it is and is not chosen against, are recorded on
/// [`crate::network_policy::ToolCapabilityGrant`]. `Some(scope)` preopens `workdir/scope`
/// instead, created if missing — already validated as relative and non-escaping by
/// [`ToolCapabilityGrant::derive`] at staging time.
///
/// `state_dir` is the artifact's durable state store, already created at `0700` by the staging
/// path. `Some(dir)` adds a *second* preopen at the guest path [`STATE_PREOPEN_NAME`], so the
/// guest reaches it as `state/<file>`; it is a host path outside every workdir, and the only one
/// a guest can name. `None` — every caller without a `capabilities.state` grant — adds nothing,
/// leaving the workdir preopen as the guest's only filesystem reach.
///
/// `config_json` is this artifact's `config:` block, already lowered to compact JSON at staging.
/// `Some` sets exactly one variable, [`ARTIFACT_CONFIG_ENV`]; `None` — every caller whose entry
/// declared no `config:` — sets none, so the variable is absent from the guest environment rather
/// than present and empty. It is injected after the host allowlist and before `extra_env`, which
/// is what makes it runtime-owned: `capabilities.env.allow` cannot supply it (the allowlist skips
/// the name outright) and cannot shadow it either.
fn build_wasi_ctx(
    workdir: &Path,
    filesystem_scope: Option<&str>,
    state_dir: Option<&Path>,
    config_json: Option<&str>,
    extra_env: &[(String, String)],
    policy: &CapabilityPolicy,
) -> Result<WasiCtx, RuntimeError> {
    let mut builder = WasiCtxBuilder::new();
    builder.inherit_stdio();
    for (key, value) in build_wasi_env_allowlist(policy) {
        builder.env(key, value);
    }
    if let Some(config_json) = config_json {
        builder.env(ARTIFACT_CONFIG_ENV, config_json);
    }
    for (key, value) in extra_env {
        builder.env(key, value);
    }

    // Hard error rather than a silent fall back to the unscoped workdir (which would widen
    // the grant) or to no preopen at all (which would look like a guest bug).
    let preopen_root = match filesystem_scope {
        None => workdir.to_path_buf(),
        Some(scope) => resolve_scoped_dir(workdir, scope)?,
    };

    builder
        .preopened_dir(&preopen_root, ".", DirPerms::all(), FilePerms::all())
        .map_err(|err| RuntimeError::wasi(preopen_root, err.to_string()))?;

    if let Some(state_dir) = state_dir {
        builder
            .preopened_dir(
                state_dir,
                STATE_PREOPEN_NAME,
                DirPerms::all(),
                FilePerms::all(),
            )
            .map_err(|err| RuntimeError::wasi(state_dir.to_path_buf(), err.to_string()))?;
    }

    Ok(builder.build())
}

/// The `MURMUR_INFERENCE_*` variables every guest of an inference session sees.
///
/// Never the key: under `transport: http` the endpoint is the gateway's, and the runtime attaches
/// the credential itself. `gateway` is `None` for `transport: process`, whose endpoint is empty.
fn inference_env_pairs(
    inference: &murmur_artifact::InferenceConfig,
    gateway: Option<&InferenceGateway>,
) -> Vec<(String, String)> {
    let mut pairs = vec![
        (
            "MURMUR_INFERENCE_TRANSPORT".to_string(),
            inference.transport.clone(),
        ),
        (
            "MURMUR_INFERENCE_ENDPOINT".to_string(),
            gateway
                .map(InferenceGateway::driver_endpoint)
                .unwrap_or_default(),
        ),
        (
            "MURMUR_INFERENCE_MODEL".to_string(),
            inference.model.clone(),
        ),
        (
            "MURMUR_INFERENCE_DRIVER".to_string(),
            inference
                .driver
                .as_ref()
                .map(|d| d.artifact.clone())
                .unwrap_or_default(),
        ),
    ];

    if let Some(config) = inference.driver.as_ref().and_then(|d| d.config.as_ref()) {
        pairs.push(("MURMUR_INFERENCE_DRIVER_CONFIG".to_string(), config.clone()));
    }

    pairs
}

/// Suspend an A2A task in the InputRequired state, await external input, and resume.
///
/// Called from the `murmur:task/task#request-input` host function registered in the tool linker.
/// Emits SSE events for the state transitions. Returns `Err` on timeout (traps the WASM guest).
pub(crate) async fn request_input_impl(
    task_id: String,
    prompt: String,
    task_registry: Arc<Mutex<TaskRegistry>>,
    sse: Option<(SseBroadcast, Arc<Mutex<SseEventBuffer>>)>,
    input_timeout_secs: Option<u64>,
) -> wasmtime::Result<String> {
    use std::time::Duration;
    use tokio::sync::oneshot;

    let (tx, rx) = oneshot::channel::<String>();
    let cancel = {
        let mut reg = task_registry.lock().unwrap();
        reg.set_input_required(&task_id, prompt.clone(), tx)
            .map_err(|e| wasmtime::Error::msg(format!("request-input: {e}")))?;
        reg.cancel_watch(&task_id)
    };

    // Use high IDs to avoid overlapping with agent-loop SSE event IDs (which start at 0).
    let mut sse_event_id: u64 = u64::MAX / 2;
    emit_sse(
        &sse,
        &mut sse_event_id,
        "status",
        &TaskStatusUpdateEvent {
            id: task_id.clone(),
            context_id: None,
            status: StreamStatus {
                state: "input-required".into(),
                message: prompt.clone(),
                response: None,
            },
            r#final: false,
        },
    )
    .await;

    // `input-required` is a wait like any other, so a cancel ends it rather than leaving the task
    // parked until the input timeout. The guest is unwound by the error either way; what differs
    // is which terminal state the task is left in, and who writes it.
    let waited = async {
        match input_timeout_secs {
            Some(secs) => tokio::time::timeout(Duration::from_secs(secs), rx)
                .await
                .map_err(|_| ())
                .and_then(|r| r.map_err(|_| ())),
            None => rx.await.map_err(|_| ()),
        }
    };
    let result = tokio::select! {
        biased;
        () = cancel.canceled() => {
            cancel.note_phase(crate::cancel::PHASE_INPUT);
            Err(InputWaitEnd::Canceled)
        }
        waited = waited => waited.map_err(|()| InputWaitEnd::TimedOut),
    };

    match result {
        Ok(text) => {
            emit_sse(
                &sse,
                &mut sse_event_id,
                "status",
                &TaskStatusUpdateEvent {
                    id: task_id.clone(),
                    context_id: None,
                    status: StreamStatus {
                        state: "working".into(),
                        message: "resumed".into(),
                        response: None,
                    },
                    r#final: false,
                },
            )
            .await;
            Ok(text)
        }
        // The state and the final status event are the agent loop's to write on this path: it
        // takes the cancel at its next boundary and ends the attempt there, with the record, the
        // trace and the residue that go with it.
        Err(InputWaitEnd::Canceled) => Err(wasmtime::Error::msg("task-canceled")),
        Err(InputWaitEnd::TimedOut) => {
            {
                let mut reg = task_registry.lock().unwrap();
                reg.finish_task(TaskState::Failed);
                reg.advance_resource_generation();
            }
            emit_sse(
                &sse,
                &mut sse_event_id,
                "status",
                &TaskStatusUpdateEvent {
                    id: task_id.clone(),
                    context_id: None,
                    status: StreamStatus {
                        state: "failed".into(),
                        message: "input-timeout".into(),
                        response: None,
                    },
                    r#final: true,
                },
            )
            .await;
            Err(wasmtime::Error::msg("input-timeout"))
        }
    }
}

/// Why a `request-input` wait ended without an answer.
///
/// The two are not interchangeable: a timeout is this task failing, and a cancel is a person
/// stopping it — so only one of them writes a terminal state here.
enum InputWaitEnd {
    Canceled,
    TimedOut,
}

pub(crate) struct NetworkPolicyHooks {
    pub(crate) network_allow_rules: Vec<NetworkAllowRule>,
    /// Set only on the configured inference driver's own store. A request addressed to the gateway
    /// authority is then sent to the provider by the runtime, on the runtime's grant — neither
    /// `network_allow_rules` nor the driver's per-artifact narrowing is consulted for it. Every
    /// other request from the same store is checked exactly as it is without a gateway.
    pub(crate) inference_gateway: Option<Arc<InferenceGateway>>,
}

impl WasiHttpHooks for NetworkPolicyHooks {
    fn send_request(
        &mut self,
        request: hyper::Request<HyperOutgoingBody>,
        config: OutgoingRequestConfig,
    ) -> HttpResult<HostFutureIncomingResponse> {
        if let Some(gateway) = self.inference_gateway.as_ref() {
            if InferenceGateway::is_addressed_to_gateway(request.uri()) {
                // Refused before the key is attached unless some admission is open. The check is
                // session-wide, not per-request: it holds only because the gateway is attached to
                // the agent loop's driver dispatch and hooks' `run-inference`, both of which admit
                // first, and never to a driver reached by name through tool dispatch.
                if !gateway.spend.has_open_admission() {
                    return Err(wasmtime_wasi_http::p2::HttpError::from(
                        WasiHttpErrorCode::HttpRequestDenied,
                    ));
                }
                let gateway = Arc::clone(gateway);
                return Ok(HostFutureIncomingResponse::pending(
                    wasmtime_wasi::runtime::spawn(async move {
                        Ok(gateway.send(request, config).await)
                    }),
                ));
            }
        }

        let target =
            RequestTarget::from_request(request.uri(), config.use_tls).ok_or_else(|| {
                wasmtime_wasi_http::p2::HttpError::from(WasiHttpErrorCode::HttpRequestDenied)
            })?;

        if !self
            .network_allow_rules
            .iter()
            .any(|rule| rule.matches(&target))
        {
            return Err(wasmtime_wasi_http::p2::HttpError::from(
                WasiHttpErrorCode::HttpRequestDenied,
            ));
        }

        Ok(wasmtime_wasi_http::p2::default_send_request(
            request, config,
        ))
    }
}

pub(crate) struct CapsuleStoreState {
    /// Resource limiter for this store, registered via `Store::limiter`. Also the record of
    /// any growth request it denied, which `classify_guest_failure` reads to tell a
    /// limit trap apart from a guest panic.
    pub(crate) limits: ExecutionLimiter,
    pub(crate) table: ResourceTable,
    pub(crate) wasi: WasiCtx,
    pub(crate) http: WasiHttpCtx,
    pub(crate) http_hooks: NetworkPolicyHooks,
    pub(crate) network_allow_rules: Vec<NetworkAllowRule>,
    /// `capabilities.peer_fetch.allow`, parsed. Checked **before** `fetch-peer-file` opens any
    /// connection, and never merged with `network_allow_rules`.
    pub(crate) peer_fetch_rules: Vec<NetworkAllowRule>,
    /// The minting side. `None` — no `exports.peer_files` — means no `share-file` tool manifest
    /// was written, so this is the belt to that braces: the dispatch branch refuses rather than
    /// assuming the tool could not have been called.
    pub(crate) peer_plane: Option<Arc<crate::peer_handoff::PeerPlane>>,
    /// This capsule's own audience, asserted on every redeem it issues.
    pub(crate) peer_own_audience: String,
    /// Where the peer-handoff tools write their records. The concurrent `O_APPEND` sink rather
    /// than the loop's `TraceWriter`, which is `&mut`-owned by the loop and out of reach here —
    /// so a mint and a fetch land at the moment of the event rather than at the next task
    /// boundary.
    pub(crate) peer_trace: Option<Arc<crate::trace::ResourceTraceAppender>>,
    /// This session's authority to delegate. `None` — no `capabilities.spawn.allow`, so no
    /// registration and no credential — means no `delegate-task` tool manifest was written. The
    /// dispatch branch still refuses on `None` rather than assuming the tool could not have been
    /// called.
    pub(crate) delegation: Option<Arc<crate::delegation_plane::DelegationPlane>>,
    /// Where a submitted plan's per-step lifecycle records go, or `None` for a session that keeps
    /// no trace. A second handle to the same `trace.jsonl` the agent loop's writer holds, for the
    /// same reason [`Self::peer_trace`] is one: a plan runs on blocking threads that the loop's
    /// writer cannot be lent to.
    pub(crate) plan_trace: Option<Arc<crate::trace::PlanTraceAppender>>,
    /// How many plans this session has submitted. The plan file is named from this and never from
    /// anything the model wrote, so a plan `id` reaches no path.
    pub(crate) plan_counter: AtomicU64,
    pub(crate) inference_env: Vec<(String, String)>,
    /// Moved over from [`StagedSession::inference_gateway`]. Handed only to
    /// [`Self::dispatch_driver_async`], and attached by [`invoke_tool_component`] only to the
    /// configured driver's store.
    pub(crate) inference_gateway: Option<Arc<InferenceGateway>>,
    /// Moved over from [`StagedSession::spend`]. The agent loop admits every driver turn against
    /// it; hooks' `run-inference` and the gateway hold clones of the same account.
    pub(crate) spend: Arc<SpendMeter>,
    pub(crate) engine: Engine,
    pub(crate) workdir: PathBuf,
    pub(crate) accessible_workdir: PathBuf,
    pub(crate) tool_components: HashMap<String, Component>,
    /// Per-artifact narrowing keyed by artifact name, moved over from
    /// [`StagedSession::artifact_grants`]. A name absent here dispatches on the full ceiling.
    pub(crate) artifact_grants: HashMap<String, ToolCapabilityGrant>,
    pub(crate) allowlisted_tools: HashSet<String>,
    pub(crate) installed_artifacts: Vec<InstalledArtifactSummary>,
    pub(crate) session_id: String,
    /// Buffered outgoing A2A send events — drained into trace.jsonl after the capsule run.
    /// (peer_url, message_id, task_id, context_id, traceparent, trust)
    pub(crate) pending_a2a_events:
        Vec<(String, String, String, String, Option<String>, TrustClass)>,
    pub(crate) capability_policy: CapabilityPolicy,
    /// The lowered `capabilities.filesystem.read_only` surface, built and validated once at
    /// staging. Empty for every capsule that declared nothing, and
    /// [`Self::has_protected_paths`] is the single boolean that keeps such a capsule from
    /// resolving a call, walking a JSON input or resolving a path at all.
    pub(crate) protected_paths: ProtectedPaths,
    /// What each staged tool's own `input_schema` declared about where its inputs go. Read only
    /// by [`Self::check_protected_paths`], and only to decide *where* the analyser looks — never
    /// whether it refuses. Empty whenever [`Self::has_protected_paths`] is false.
    pub(crate) tool_annotations: ToolAnnotationMap,
    /// Host-detected kernel enforcement tier + resolved network allowlist IPs for this
    /// session's shell subprocesses. Kept separate from `CapabilityPolicy` (which stays
    /// purely manifest-derived) since this is host-probed data, not manifest data.
    pub(crate) shell_enforcement: sandbox::ShellEnforcement,
    /// W3C traceparent for outgoing murmur:message/send calls — set by the runtime loop
    /// after each begin_session so the active session span propagates to peer capsules.
    pub(crate) current_traceparent: Option<String>,
    /// Why the task now in scope woke this capsule, set by the task loop beside
    /// `current_traceparent`. An outgoing peer message stamps this task's trust class, so the
    /// receiver inherits it instead of reclassifying the message as fresh. `None` on the
    /// script-capsule path, which runs no task loop and so has no task in scope — that stamps
    /// `untrusted`, the safe class.
    pub(crate) current_task_provenance: Option<TaskProvenance>,
    /// The conversation the task now in scope runs under, set beside `current_task_provenance`
    /// at every task-activation site. A demoted command's completion is enqueued under this id,
    /// so the result joins the conversation the command was started from.
    pub(crate) current_context_id: Option<String>,
    /// Every delegation this session started and has not yet closed, by `dlg_` id.
    ///
    /// Filled from the launch notice, read from three places: the completion that arrives as a
    /// task closes its row from the child's own `completion.json`, a cancel names whatever is
    /// still in flight, and the plane's own failure path releases a launch that will never
    /// report. Shared with the A2A door, which snapshots it without taking any other lock.
    pub(crate) live_delegations: Arc<crate::cancel::LiveDelegations>,
    // ── Detached shell ───────────────────────────────────────────────────────────
    /// Where a demoted command registers itself and delivers its completion. `None` is what
    /// keeps a call site foreground-only: the script-capsule path and every test construction
    /// run no task loop, so a completion would have nowhere to land.
    pub(crate) detached: Option<Arc<DetachedRegistry>>,
    /// `lifecycle.shell_grace_secs`: how long a shell command runs in the foreground before it
    /// is demoted. Read from the resolved lifecycle once per launch.
    pub(crate) shell_grace_secs: u64,
    // ── A2A request-input support ────────────────────────────────────────────────
    /// Shared task registry — Some in A2A mode, None for script capsules.
    pub(crate) a2a_task_registry: Option<Arc<Mutex<TaskRegistry>>>,
    /// SSE broadcast channel — Some in A2A mode, None for script capsules.
    pub(crate) a2a_sse: Option<(SseBroadcast, Arc<Mutex<SseEventBuffer>>)>,
    /// Active A2A task ID — set per-task before run_agent_loop, None outside A2A context.
    pub(crate) a2a_task_id: Option<String>,
    /// Optional input timeout from lifecycle config.
    pub(crate) input_timeout_secs: Option<u64>,
    // ── A2A streaming text chunk support ─────────────────────────────────────────
    /// Monotonically increasing event ID counter for text chunk SSE events.
    /// Starts at u64::MAX/4 to avoid overlap with agent-loop status/artifact IDs (from 0).
    pub(crate) a2a_chunk_event_id: Arc<AtomicU64>,
    /// Set to true when any emit-chunk call is made during the current driver dispatch.
    /// Reset to false before each driver dispatch in run_agent_loop.
    pub(crate) a2a_chunks_emitted: Arc<AtomicBool>,
    /// Registry used to resolve additional artifacts requested at runtime via `manage.pull()`.
    pub(crate) registry: Arc<dyn Registry>,
    /// Path to this session's `murmur.lock`, consulted and updated by `manage.pull()`.
    pub(crate) lock_path: PathBuf,
    // ── Stateful-driver continuation ───────────────────────────────────
    /// Continuation id most recently returned by the inference driver via
    /// `tool-result.metadata["continuation_id"]`, held for the current session loop.
    /// `None` means "no continuation held" — every Turn resends the full `messages`
    /// array (the behavior of every driver shipped today, which never sets the key).
    pub(crate) driver_continuation_id: Option<String>,
    /// The `context_id` under which `driver_continuation_id` was established. Used as a
    /// cross-context safety guard: a held continuation is only reused when the current
    /// Turn's `context_id` matches this, so a driver-side continuation from one
    /// conversation is never carried into an unrelated Task within the same session loop.
    pub(crate) driver_continuation_context_id: Option<String>,
    /// Number of leading entries of the logical `messages` array the driver has already
    /// acknowledged. On an incremental Turn the host transmits only `messages[acked_len..]`.
    pub(crate) driver_continuation_acked_len: usize,
}

impl CapsuleStoreState {
    /// This session's cancel flag for the task now in scope, or `None` outside an A2A task.
    ///
    /// Both halves are needed: the registry mints the signal and the task id names which task's.
    /// The script-capsule path has neither and can cancel nothing.
    pub(crate) fn task_cancel_signal(&self) -> Option<crate::cancel::CancelSignal> {
        let registry = self.a2a_task_registry.as_ref()?;
        let task_id = self.a2a_task_id.as_deref()?;
        Some(registry.lock().unwrap().cancel_watch(task_id))
    }

    /// Returns the held continuation `(id, acked_len)` iff a continuation is currently held
    /// **and** was established under `context_id`. The context-id guard is required for
    /// correctness: without it, an incremental send against a driver-side continuation from
    /// an unrelated conversation would silently corrupt the driver's context.
    pub(crate) fn active_continuation(&self, context_id: Option<&str>) -> Option<(&str, usize)> {
        let id = self.driver_continuation_id.as_deref()?;
        if self.driver_continuation_context_id.as_deref() != context_id {
            return None;
        }
        Some((id, self.driver_continuation_acked_len))
    }

    /// Persist the continuation id a driver returned on this Turn, scoped to `context_id`,
    /// recording that the driver now knows the first `acked_len` entries of `messages`.
    pub(crate) fn record_continuation(
        &mut self,
        id: String,
        context_id: Option<String>,
        acked_len: usize,
    ) {
        self.driver_continuation_id = Some(id);
        self.driver_continuation_context_id = context_id;
        self.driver_continuation_acked_len = acked_len;
    }

    /// Drop any held continuation id and its bookkeeping. Called when a driver stops
    /// returning the key ("not continuing") and at every `replace-context` commit.
    pub(crate) fn clear_continuation(&mut self) {
        self.driver_continuation_id = None;
        self.driver_continuation_context_id = None;
        self.driver_continuation_acked_len = 0;
    }

    /// Advance the acked-message count for a currently-held, same-context continuation.
    /// Used when a Task's final `end_turn` persists an extra assistant message into the
    /// context history that the driver already knows (it generated it), so the next
    /// same-context Task sends only its new user message rather than re-including it.
    pub(crate) fn advance_continuation_acked_len(
        &mut self,
        context_id: Option<&str>,
        acked_len: usize,
    ) {
        if self.driver_continuation_id.is_some()
            && self.driver_continuation_context_id.as_deref() == context_id
        {
            self.driver_continuation_acked_len = acked_len;
        }
    }
}

impl WasiView for CapsuleStoreState {
    fn ctx(&mut self) -> WasiCtxView<'_> {
        WasiCtxView {
            ctx: &mut self.wasi,
            table: &mut self.table,
        }
    }
}

impl WasiHttpView for CapsuleStoreState {
    fn http(&mut self) -> WasiHttpCtxView<'_> {
        WasiHttpCtxView {
            ctx: &mut self.http,
            table: &mut self.table,
            hooks: &mut self.http_hooks,
        }
    }
}

impl invoke::Host for CapsuleStoreState {
    fn invoke(
        &mut self,
        name: String,
        input: murmur::tool::run::ToolInput,
    ) -> Result<murmur::tool::run::ToolResult, String> {
        if !self.allowlisted_tools.contains(&name) {
            return Err(format!(
                "tool '{name}' is not declared in manifest allowlist"
            ));
        }
        tokio::task::block_in_place(|| {
            tokio::runtime::Handle::current().block_on(self.dispatch_tool_async(&name, input))
        })
    }
}

impl send::Host for CapsuleStoreState {
    fn send(
        &mut self,
        peer_url: String,
        message: send::Message,
    ) -> Result<send::TaskResult, String> {
        check_destination_allowed(
            &self.network_allow_rules,
            &peer_url,
            "capabilities.network.allow",
        )?;

        let message_id = message.message_id.clone();
        let outgoing_msg = outgoing::OutgoingMessage {
            message_id: message.message_id,
            context_id: message.context_id,
            text: message.text,
        };

        // send_a2a_message is async; use block_in_place so we can call it from this sync
        // host function while inside a multi-thread Tokio runtime (script capsule path).
        let traceparent = self.current_traceparent.clone();
        // The sending runtime's own current task, read off the store state the task loop writes
        // it to. `murmur:message/send` is linked only on the script-capsule path, which runs no
        // task loop, so this is `None` there and stamps `untrusted`.
        let sender_task = self.current_task_provenance;
        let task = tokio::task::block_in_place(|| {
            tokio::runtime::Handle::current().block_on(outgoing::send_a2a_message(
                &peer_url,
                outgoing_msg,
                traceparent.clone(),
                sender_task,
            ))
        })?;

        self.pending_a2a_events.push((
            peer_url.clone(),
            message_id,
            task.id.clone(),
            task.context_id.clone(),
            traceparent,
            stamp_for_peer(sender_task).trust(),
        ));
        Ok(send::TaskResult {
            task_id: task.id,
            context_id: task.context_id,
            state: match task.status.state {
                crate::a2a::TaskState::Submitted => "submitted".to_string(),
                crate::a2a::TaskState::Working => "working".to_string(),
                crate::a2a::TaskState::InputRequired => "input-required".to_string(),
                crate::a2a::TaskState::Completed => "completed".to_string(),
                crate::a2a::TaskState::Failed => "failed".to_string(),
                crate::a2a::TaskState::Rejected => "rejected".to_string(),
                crate::a2a::TaskState::Canceled => "canceled".to_string(),
            },
        })
    }
}

impl manage::Host for CapsuleStoreState {
    fn list(&mut self) -> Vec<manage::ArtifactSummary> {
        let mut result: Vec<manage::ArtifactSummary> = self
            .installed_artifacts
            .iter()
            .filter(|a| a.runtime.is_llm_visible())
            .map(|artifact| manage::ArtifactSummary {
                name: artifact.name.clone(),
                version: artifact.version.clone(),
                runtime: runtime_type_to_wit(&artifact.runtime, artifact.implementation.as_ref()),
            })
            .collect();

        let existing: std::collections::HashSet<String> =
            result.iter().map(|a| a.name.clone()).collect();
        for binary in &self.capability_policy.shell_allow {
            if !existing.contains(binary) {
                result.push(manage::ArtifactSummary {
                    name: binary.clone(),
                    version: "0.0.0".to_string(),
                    runtime: manage::RuntimeType::Native,
                });
            }
        }

        result
    }

    fn describe(&mut self, name: String) -> Result<manage::ArtifactInfo, String> {
        // Check installed artifacts first, then fall back to shell tool manifests on disk.
        let fallback_summary;
        let summary = if let Some(s) = self
            .installed_artifacts
            .iter()
            .find(|artifact| artifact.name == name)
        {
            s
        } else if self
            .capability_policy
            .shell_allow
            .iter()
            .any(|b| b == &name)
        {
            fallback_summary = InstalledArtifactSummary {
                name: name.clone(),
                version: "0.0.0".to_string(),
                runtime: ArtifactRuntime::Tool,
                implementation: Some(ArtifactImplementation::Native),
            };
            &fallback_summary
        } else {
            return Err(format!("artifact '{name}' is not installed"));
        };

        let manifest_path = self
            .workdir
            .join("tools")
            .join(&name)
            .join(PACKED_MANIFEST_ENTRY);

        read_artifact_info_from_manifest(&manifest_path, summary)
    }

    fn search(&mut self, query: String) -> Result<Vec<manage::ArtifactSummary>, String> {
        Err(format!("not implemented (query: {query})"))
    }

    fn pull(&mut self, name: String, version: String) -> Result<manage::ArtifactSummary, String> {
        // 1. Resolve + verify against the registry's own self-reported hash.
        let resolved = self
            .registry
            .resolve_with_platform(&name, &version, Some(current_platform()))
            .map_err(|err| format!("failed to resolve {name}@{version}: {err}"))?;

        verify_sha256(&name, &version, &resolved.bytes, &resolved.sha256).map_err(|_| {
            format!("artifact integrity check failed for {name}@{version}: registry-reported hash does not match downloaded bytes")
        })?;

        // 2. Cross-check against any existing murmur.lock pin — a runtime pull must never
        // silently override what's already pinned for this artifact.
        let mut lock = match read_lockfile(&self.lock_path) {
            Ok(lock) => lock,
            Err(LockfileError::NotFound(_)) => MurmurLock {
                lock_version: LOCK_VERSION,
                artifacts: Vec::new(),
            },
            Err(err) => return Err(format!("failed to read murmur.lock: {err}")),
        };

        // Which shape the pin takes follows the payload: a native binary is pinned under this
        // host's platform, everything else under `any`. An entry that has no key for this
        // platform yet is not a conflict — it is a platform nobody has installed on before.
        let incoming_sha256 = if resolved.meta.runtime == RuntimeType::Native {
            LockedSha256::for_one_platform(current_platform(), resolved.sha256.clone())
        } else {
            LockedSha256::any(resolved.sha256.clone())
        };

        if let Some(existing) = lock.artifact_for(&name) {
            if let Some(conflict) = existing.conflict_with(&version, &incoming_sha256) {
                return Err(format!(
                    "murmur.lock conflict for '{name}': {conflict} — refusing to override a \
                     pinned artifact at runtime"
                ));
            }
        }

        // 3. Extract murmur.yaml, dispatch extraction by runtime type, and write files under
        // <workdir>/tools/<name>/ — no disk writes happen before steps 1-2 succeed.
        let manifest_yaml = extract_manifest_yaml(&name, &version, &resolved.bytes)
            .map_err(|err| err.to_string())?;
        write_tool_manifest(&self.workdir, &name, &manifest_yaml).map_err(|err| err.to_string())?;

        let (artifact_runtime, implementation, wasm_component) = match resolved.meta.runtime {
            RuntimeType::Wasm => {
                let wasm_bytes = extract_root_wasm(&name, &version, &resolved.bytes)
                    .map_err(|err| err.to_string())?;
                let component = Component::new(&self.engine, &wasm_bytes)
                    .map_err(|err| format!("failed to compile pulled component '{name}': {err}"))?;
                (
                    ArtifactRuntime::Tool,
                    Some(ArtifactImplementation::Wasm),
                    Some(component),
                )
            }
            RuntimeType::Native => {
                let binary = extract_native_binary(&name, &version, &resolved.bytes)
                    .map_err(|err| err.to_string())?;
                install_native_binaries(&self.workdir, vec![(name.clone(), binary)])
                    .map_err(|err| err.to_string())?;
                (
                    ArtifactRuntime::Tool,
                    Some(ArtifactImplementation::Native),
                    None,
                )
            }
            RuntimeType::Static => {
                let skill_md = extract_skill_md(&name, &version, &resolved.bytes)
                    .map_err(|err| err.to_string())?;
                install_skill_files(&self.workdir, vec![(name.clone(), skill_md)])
                    .map_err(|err| err.to_string())?;
                (ArtifactRuntime::Skill, None, None)
            }
        };

        // 4. Files are on disk — now, and only now, update murmur.lock.
        lock.upsert(&name, &version, incoming_sha256);
        write_lockfile_atomic(&self.lock_path, &lock)
            .map_err(|err| format!("failed to write murmur.lock: {err}"))?;

        // 5. Reflect the pulled artifact in in-memory session state so list()/describe() (and,
        // for WASM tools, invoke()) see it immediately.
        if let Some(component) = wasm_component {
            self.tool_components.insert(name.clone(), component);
        }

        let summary = InstalledArtifactSummary {
            name: name.clone(),
            version: version.clone(),
            runtime: artifact_runtime,
            implementation,
        };
        if let Some(existing) = self
            .installed_artifacts
            .iter_mut()
            .find(|artifact| artifact.name == name)
        {
            *existing = summary.clone();
        } else {
            self.installed_artifacts.push(summary.clone());
        }

        Ok(manage::ArtifactSummary {
            name,
            version,
            runtime: runtime_type_to_wit(&summary.runtime, summary.implementation.as_ref()),
        })
    }

    fn remove(&mut self, name: String) -> Result<bool, String> {
        Err(format!("not implemented (name: {name})"))
    }

    fn diagnostics(&mut self) -> Result<manage::RuntimeState, String> {
        Ok(manage::RuntimeState {
            capsule_id: self.session_id.clone(),
            installed: self.list(),
            capabilities: "artifact-manager/search and remove are not implemented".to_string(),
        })
    }
}

/// The gateway a store for artifact `name` is built with: the session's, and only when `name` is
/// the driver it was built for. Every other tool, hook and capsule store gets none, so a request
/// they address to the gateway authority is an ordinary allow-list-checked request with no key.
fn gateway_for_store(
    gateway: Option<&Arc<InferenceGateway>>,
    name: &str,
) -> Option<Arc<InferenceGateway>> {
    gateway
        .filter(|gateway| gateway.driver_name == name)
        .cloned()
}

/// Builds the session's inference gateway from the configured driver's bundled `inference_auth:`
/// block, or refuses the launch with [`RuntimeError::DriverDeclaresNoInferenceAuth`].
///
/// `None` for `transport: process`, for no inference, and for a driver that is not among the staged
/// artifacts — dispatch already refuses that one by name. The refusal depends on the declaration
/// alone, never on whether `inference.api_key` is set.
///
/// A `transport: http` `inference.api_key` is resolved first, against `credentials_file` and the
/// environment, so a credential found nowhere refuses the launch with
/// [`RuntimeError::InferenceCredentialNotFound`] even when no gateway would be built.
fn stage_inference_gateway(
    inference: Option<&InferenceConfig>,
    credentials_file: Option<&Path>,
    installed_manifests: &[(String, String)],
    installed_artifacts: &[InstalledArtifactSummary],
    spend: &Arc<SpendMeter>,
) -> Result<Option<Arc<InferenceGateway>>, RuntimeError> {
    let Some(inference) = inference.filter(|inference| inference.transport == "http") else {
        return Ok(None);
    };
    let credential = inference
        .api_key
        .as_ref()
        .map(|reference| InferenceCredential::resolve(reference, credentials_file).map(Arc::new))
        .transpose()?;
    let (Some(driver), Some(endpoint)) = (inference.driver.as_ref(), inference.endpoint.as_deref())
    else {
        return Ok(None);
    };
    let Some((_, manifest_yaml)) = installed_manifests
        .iter()
        .find(|(name, _)| *name == driver.artifact)
    else {
        return Ok(None);
    };
    let refuse = |reason: Option<String>| RuntimeError::DriverDeclaresNoInferenceAuth {
        name: driver.artifact.clone(),
        version: installed_artifacts
            .iter()
            .find(|artifact| artifact.name == driver.artifact)
            .map(|artifact| artifact.version.clone())
            .unwrap_or_default(),
        reason,
    };
    let auth = match murmur_artifact::parse_inference_auth(manifest_yaml) {
        Ok(Some(auth)) => auth,
        Ok(None) => return Err(refuse(None)),
        Err(err) => return Err(refuse(Some(err.to_string()))),
    };
    InferenceGateway::new(
        driver.artifact.clone(),
        endpoint,
        auth,
        credential,
        Arc::clone(spend),
    )
    .map(|gateway| Some(Arc::new(gateway)))
}

/// Builds the session's spend account: `inference.max_session_tokens` as its session ceiling and,
/// for a `transport: http` session with a driver, the shared daily ledger when
/// `machine_tokens_per_day` is set.
///
/// Refuses with [`RuntimeError::SpendLedgerUnavailable`] when that ledger cannot be opened. A
/// `transport: process` session holds no key and makes no call the runtime can meter, so it keeps
/// no ledger whatever the operator set.
fn stage_spend_meter(
    inference: Option<&InferenceConfig>,
    machine_tokens_per_day: Option<u64>,
    session_id: &str,
) -> Result<Arc<SpendMeter>, RuntimeError> {
    let metered = inference.filter(|inference| {
        inference.transport == "http"
            && inference
                .driver
                .as_ref()
                .is_some_and(|driver| !driver.artifact.is_empty())
    });
    let machine = match (metered, machine_tokens_per_day) {
        (Some(_), Some(ceiling)) => Some(MachineLedger::open(session_id, ceiling)?),
        _ => None,
    };
    Ok(Arc::new(SpendMeter::new(
        metered.and_then(|inference| inference.max_session_tokens),
        machine,
    )))
}

/// Borrowed half of a WASM tool invocation environment: everything
/// [`invoke_tool_component`] needs that is neither the component nor the A2A
/// wiring. Grouped into a struct so the hook runtime can assemble one from its
/// own owned copies without a >7-argument function.
pub(crate) struct ToolInvokeEnv<'a> {
    pub(crate) engine: &'a Engine,
    pub(crate) accessible_workdir: &'a Path,
    pub(crate) inference_env: &'a [(String, String)],
    pub(crate) capability_policy: &'a CapabilityPolicy,
    /// The capsule-wide ceiling. What actually gets enforced is this, clamped by
    /// `artifact_grant` when the operator declared one.
    pub(crate) network_allow_rules: &'a [NetworkAllowRule],
    /// This artifact's optional narrowing, from the operator's own manifest entry. `None` —
    /// no `capabilities:` block on the entry — means the ceiling applies untouched and the
    /// whole `accessible_workdir` is preopened, exactly as before narrowing existed.
    pub(crate) artifact_grant: Option<&'a ToolCapabilityGrant>,
    /// The session's inference gateway, attached to this store only when `name` is the driver it
    /// was built for.
    pub(crate) inference_gateway: Option<&'a Arc<InferenceGateway>>,
}

/// Per-session A2A wiring registered on a tool linker.
///
/// The two host interfaces it backs (`murmur:text/chunks`, `murmur:task/task`)
/// are always *defined* — a streaming driver imports them and would fail to
/// instantiate otherwise — but each function is a no-op when its channel is
/// absent. [`ToolA2aWiring::silent`] is that all-absent form, used for a
/// dispatch that is not part of an A2A task turn (a hook's `run-inference`
/// call, which must not stream chunks into the user's SSE stream or ask the
/// user for input).
pub(crate) struct ToolA2aWiring {
    sse: Option<(SseBroadcast, Arc<Mutex<SseEventBuffer>>)>,
    task_id: Option<String>,
    chunk_event_id: Arc<AtomicU64>,
    chunks_emitted: Arc<AtomicBool>,
    task_registry: Option<Arc<Mutex<TaskRegistry>>>,
    input_timeout_secs: Option<u64>,
}

impl ToolA2aWiring {
    pub(crate) fn silent() -> Self {
        Self {
            sse: None,
            task_id: None,
            chunk_event_id: Arc::new(AtomicU64::new(0)),
            chunks_emitted: Arc::new(AtomicBool::new(false)),
            task_registry: None,
            input_timeout_secs: None,
        }
    }
}

/// Instantiate `component` in a fresh `Linker`/`Store` and call its
/// `murmur:tool/run@0.1.0#run` export.
///
/// This is the single WASM-tool (and therefore inference-driver) invocation
/// body in the runtime. [`CapsuleStoreState::dispatch_tool_async`] and
/// [`CapsuleStoreState::dispatch_driver_async`] are thin wrappers that fill `env`/`a2a` from the capsule store; a hook's
/// `run-inference` host import fills them from its own owned copies. Neither
/// duplicates any part of the instantiate/type-check/call sequence below.
pub(crate) async fn invoke_tool_component(
    env: ToolInvokeEnv<'_>,
    a2a: ToolA2aWiring,
    name: &str,
    component: &Component,
    input: murmur::tool::run::ToolInput,
) -> Result<murmur::tool::run::ToolResult, String> {
    let ToolInvokeEnv {
        engine,
        accessible_workdir,
        inference_env,
        capability_policy,
        network_allow_rules,
        artifact_grant,
        inference_gateway,
    } = env;
    let ToolA2aWiring {
        sse: a2a_sse,
        task_id: a2a_task_id,
        chunk_event_id: a2a_chunk_event_id,
        chunks_emitted: a2a_chunks_emitted,
        task_registry: a2a_task_registry,
        input_timeout_secs,
    } = a2a;

    let mut linker = Linker::new(engine);
    wasmtime_wasi::p2::add_to_linker_async(&mut linker)
        .map_err(|err| format!("failed to add WASI linker for tool '{name}': {err}"))?;
    wasmtime_wasi_http::p2::add_only_http_to_linker_sync(&mut linker)
        .map_err(|err| format!("failed to add HTTP linker for tool '{name}': {err}"))?;

    // Register murmur:text/chunks host functions (synchronous).
    // Components that do not import this interface ignore the registrations.
    // Both functions must be defined in a single .instance() call — Wasmtime
    // rejects a second .instance() for the same interface name. Registered
    // under the versioned name only (see WIT_TEXT_CHUNKS_IFACE / wit/VERSIONING.md).
    {
        let chunks_iface = WIT_TEXT_CHUNKS_IFACE;
        let sse_for_chunk = a2a_sse.clone();
        let task_id_for_chunk = a2a_task_id.clone();
        let chunk_event_id = Arc::clone(&a2a_chunk_event_id);
        let chunks_emitted_flag = Arc::clone(&a2a_chunks_emitted);
        let sse_for_thinking = a2a_sse.clone();
        let task_id_for_thinking = a2a_task_id.clone();
        let thinking_event_id = Arc::clone(&a2a_chunk_event_id);

        let mut inst = linker.instance(chunks_iface).map_err(|err| {
            format!("failed to define {chunks_iface} instance for '{name}': {err}")
        })?;

        inst.func_wrap(
            "emit-chunk",
            move |_store: wasmtime::StoreContextMut<'_, ToolStoreState>, (chunk,): (String,)| {
                chunks_emitted_flag.store(true, Ordering::Relaxed);
                if let (Some((ref tx, ref buf)), Some(ref tid)) =
                    (&sse_for_chunk, &task_id_for_chunk)
                {
                    emit_chunk_sse(tx, buf, &chunk_event_id, tid, &chunk);
                }
                Ok(())
            },
        )
        .map_err(|err| format!("failed to register emit-chunk for tool '{name}': {err}"))?;

        inst.func_wrap(
            "emit-thinking-chunk",
            move |_store: wasmtime::StoreContextMut<'_, ToolStoreState>, (chunk,): (String,)| {
                if let (Some((ref tx, ref buf)), Some(ref tid)) =
                    (&sse_for_thinking, &task_id_for_thinking)
                {
                    emit_thinking_chunk_sse(tx, buf, &thinking_event_id, tid, &chunk);
                }
                Ok(())
            },
        )
        .map_err(|err| {
            format!("failed to register emit-thinking-chunk for tool '{name}': {err}")
        })?;
    }

    // Register the murmur:task/task#request-input host function under the
    // versioned name only (see WIT_TASK_IFACE).
    // Components that do not import this interface ignore the registration.
    {
        let task_iface = WIT_TASK_IFACE;
        let ri_task_registry = a2a_task_registry.clone();
        let ri_sse = a2a_sse.clone();
        let ri_task_id = a2a_task_id.clone();
        let ri_timeout = input_timeout_secs;
        linker
            .instance(task_iface)
            .map_err(|err| format!("failed to define {task_iface} instance for '{name}': {err}"))?
            .func_wrap_async(
                "request-input",
                move |_store: wasmtime::StoreContextMut<'_, ToolStoreState>,
                      (prompt,): (String,)| {
                    let reg = ri_task_registry.clone();
                    let sse = ri_sse.clone();
                    let tid = ri_task_id.clone();
                    let fut: std::pin::Pin<
                        Box<dyn std::future::Future<Output = wasmtime::Result<(String,)>> + Send>,
                    > = Box::pin(async move {
                        let result = match (reg, tid) {
                            (Some(reg), Some(tid)) => {
                                request_input_impl(tid, prompt, reg, sse, ri_timeout).await
                            }
                            _ => Err(wasmtime::Error::msg(
                                "request-input is not available outside an A2A task context",
                            )),
                        };
                        result.map(|s| (s,))
                    });
                    Box::new(fut)
                        as Box<
                            dyn std::future::Future<Output = wasmtime::Result<(String,)>>
                                + Send
                                + '_,
                        >
                },
            )
            .map_err(|err| format!("failed to register request-input for tool '{name}': {err}"))?;
    }

    let tool_limits = capability_policy.limits;
    // Both halves of the grant are resolved here, on the one path every WASM tool and the
    // inference driver share, so a driver needs no enforcement code of its own.
    let effective_network_rules = effective_tool_network_rules(artifact_grant, network_allow_rules);
    let filesystem_scope = artifact_grant.and_then(|grant| grant.filesystem_scope.as_deref());
    // Absent for every artifact that declared no `capabilities.state`, so an undeclared tool is
    // built with the workdir preopen and nothing else.
    let state_dir = artifact_grant.and_then(|grant| grant.state_dir.as_deref());
    // Absent for every artifact that declared no `config:`, so an unconfigured tool is built with
    // no `MURMUR_ARTIFACT_CONFIG` in its environment at all. Read off this artifact's own grant,
    // which is what keeps one artifact's config out of every other artifact's guest.
    let config_json = artifact_grant.and_then(|grant| grant.config_json.as_deref());
    let state = ToolStoreState {
        limits: tool_limits.limiter(),
        table: ResourceTable::new(),
        wasi: build_wasi_ctx(
            accessible_workdir,
            filesystem_scope,
            state_dir,
            config_json,
            inference_env,
            capability_policy,
        )
        .map_err(|err| format!("failed to build WASI context for tool '{name}': {err}"))?,
        http: WasiHttpCtx::new(),
        http_hooks: NetworkPolicyHooks {
            network_allow_rules: effective_network_rules.to_vec(),
            inference_gateway: gateway_for_store(inference_gateway, name),
        },
    };

    let mut store = Store::new(engine, state);
    // Registered before instantiation — see the capsule store for why.
    store.limiter(|state| &mut state.limits);

    store.set_epoch_deadline(tool_limits.deadline_ticks());
    let instance = linker
        .instantiate_async(&mut store, component)
        .await
        .map_err(|err| format!("failed to instantiate tool '{name}': {err}"))?;

    let tool_iface = resolve_versioned_iface(&instance, &mut store, WIT_TOOL_IFACE_VERSIONED)
        .ok_or_else(|| {
            RuntimeError::ToolExportMissing {
                name: name.to_string(),
            }
            .to_string()
        })?;
    let tool_run = instance
        .get_export_index(&mut store, Some(&tool_iface), "run")
        .and_then(|idx| instance.get_func(&mut store, idx))
        .ok_or_else(|| {
            RuntimeError::ToolExportMissing {
                name: name.to_string(),
            }
            .to_string()
        })?;

    let run = tool_run
        .typed::<(murmur::tool::run::ToolInput,), (murmur::tool::run::ToolResult,)>(&store)
        .map_err(|err| format!("failed to type-check tool '{name}' run export: {err}"))?;

    // Fresh budget for `run` itself, so instantiation cost cannot eat into it. This is
    // also the driver path (`agent.rs` dispatches the inference driver through here).
    store.set_epoch_deadline(tool_limits.deadline_ticks());
    let called = run.call_async(&mut store, (input,)).await;
    let (result,) = match called {
        Ok(result) => result,
        Err(err) => {
            // Classified rather than folded into the generic "trapped" string, so a
            // deadline or limit trap is distinguishable on a path that reports failures
            // as plain text. `Other` reproduces the pre-slice wording verbatim.
            let failure = classify_guest_failure(&err, &store.data().limits);
            return Err(failure.message(&format!("tool '{name}'"), &err));
        }
    };
    Ok(result)
}

/// Reduce a dispatched tool result to the one string the model will read, and fence it.
///
/// The `data` / `summary` reduction happens here, once, rather than at each model-facing caller,
/// and both fields are consumed: `data` carries the fenced text afterwards and `summary` is left
/// `None`, so the `data.or(summary)` both callers write has nothing unfenced to fall back to.
///
/// `status`, `data_path`, `truncated` and `metadata` are untouched: they are the tool's own
/// declarations about the call, not content shown to the model.
fn fence_tool_result(name: &str, result: &mut murmur::tool::run::ToolResult) {
    let data = result.data.take();
    let summary = result.summary.take();
    let text = data
        .or(summary)
        .unwrap_or_else(|| "tool returned no data".to_string());
    result.data = Some(crate::fence::wrap_untrusted(
        &crate::fence::tool_source(name),
        &text,
    ));
}

impl CapsuleStoreState {
    /// Async WASM tool dispatch for a guest's `invoke` and the model's tool calls. Never carries the
    /// inference gateway: a driver reached by name here gets no keyed route to its provider, and
    /// so cannot spend outside an admission.
    pub(crate) async fn dispatch_tool_async(
        &self,
        name: &str,
        input: murmur::tool::run::ToolInput,
    ) -> Result<murmur::tool::run::ToolResult, String> {
        self.dispatch_component_async(name, input, None).await
    }

    /// The agent loop's driver turn: the one dispatch the inference gateway is attached to, and
    /// only under the spend admission the loop opened for it.
    pub(crate) async fn dispatch_driver_async(
        &self,
        name: &str,
        input: murmur::tool::run::ToolInput,
    ) -> Result<murmur::tool::run::ToolResult, String> {
        self.dispatch_component_async(name, input, self.inference_gateway.as_ref())
            .await
    }

    async fn dispatch_component_async(
        &self,
        name: &str,
        input: murmur::tool::run::ToolInput,
        inference_gateway: Option<&Arc<InferenceGateway>>,
    ) -> Result<murmur::tool::run::ToolResult, String> {
        let Some(component) = self.tool_components.get(name) else {
            return Err(format!("tool '{name}' is not available in this session"));
        };
        invoke_tool_component(
            ToolInvokeEnv {
                engine: &self.engine,
                accessible_workdir: &self.accessible_workdir,
                inference_env: &self.inference_env,
                capability_policy: &self.capability_policy,
                network_allow_rules: &self.network_allow_rules,
                // Absent for every artifact that declared no `capabilities:` block, and for
                // anything pulled in at runtime via `manage.pull()` (which has no operator
                // manifest entry to narrow from) — both keep the full ceiling.
                artifact_grant: self.artifact_grants.get(name),
                inference_gateway,
            },
            ToolA2aWiring {
                sse: self.a2a_sse.clone(),
                task_id: self.a2a_task_id.clone(),
                chunk_event_id: Arc::clone(&self.a2a_chunk_event_id),
                chunks_emitted: Arc::clone(&self.a2a_chunks_emitted),
                task_registry: self.a2a_task_registry.clone(),
                input_timeout_secs: self.input_timeout_secs,
            },
            name,
            component,
            input,
        )
        .await
    }

    /// Resolve what a tool call is about to run, for the policy decision point.
    ///
    /// Routes exactly as [`Self::dispatch_agent_tool_unfenced`] does, in the same order, so the
    /// hook is shown the branch that will actually be taken. Everything that is not a shell
    /// call — a runtime peer-handoff tool, a native artifact binary, a skill, a WASM tool —
    /// resolves to [`ResolvedCall::Tool`] carrying the exact input JSON.
    ///
    /// Read-only and side-effect free: it decides nothing and grants nothing, and the capability
    /// checks it routes past are still performed by the dispatch path itself.
    pub(crate) fn resolve_call(
        &self,
        name: &str,
        input: &murmur::tool::run::ToolInput,
    ) -> ResolvedCall {
        let as_tool = || {
            let json = input.data.clone().unwrap_or_default();
            ResolvedCall::Tool {
                tool_name: name.to_string(),
                input_bytes: json.len() as u64,
                input: json,
            }
        };
        if name == SHARE_FILE_TOOL
            || name == FETCH_PEER_FILE_TOOL
            || name == DELEGATE_TASK_TOOL
            || name == SUBMIT_PLAN_TOOL
        {
            return as_tool();
        }
        let native_bin = self.workdir.join("tools").join(name).join(name);
        if native_bin.exists() && !self.tool_components.contains_key(name) {
            return as_tool();
        }
        match resolve_shell_call(
            name,
            input,
            &self.accessible_workdir,
            &self.capability_policy,
        ) {
            Some(ResolvedShellCall {
                binary,
                command,
                argv,
                script,
                recipe,
            }) => ResolvedCall::Shell {
                binary,
                command,
                argv,
                script,
                recipe,
            },
            None => as_tool(),
        }
    }

    /// Whether this capsule declared any `capabilities.filesystem.read_only` entry.
    ///
    /// The one branch the dispatch path takes on: `false` means no call is resolved, no path is
    /// resolved, no JSON input is walked and no analyser pass runs, so a capsule that declared
    /// nothing pays nothing.
    pub(crate) fn has_protected_paths(&self) -> bool {
        !self.protected_paths.is_empty()
    }

    /// The manifest's own answer to "does this call write a declared read-only path?".
    ///
    /// Grants nothing and widens nothing: the only outcome it can produce is that a call does not
    /// happen. Runs on this session's own workdir, which is the root every declared entry is
    /// relative to.
    pub(crate) fn check_protected_paths(
        &self,
        call: &ResolvedCall,
    ) -> Option<ProtectedPathRefusal> {
        self.protected_paths
            .check_call(&self.accessible_workdir, call, &self.tool_annotations)
    }

    /// Dispatch a tool call from the agent loop: native binary, shell, or WASM, and fence
    /// whatever comes back.
    ///
    /// The single convergence point of every agent-facing tool call, on both invocation paths
    /// (WASM component and native subprocess), which is why the fence is applied here rather
    /// than at either of the two callers that turn a [`DispatchOutcome`] into model-facing text.
    /// The reduction from `data`/`summary` to one string happens here too, so no unfenced tool
    /// text is left on the outcome for a caller to reach for.
    pub(crate) async fn dispatch_agent_tool_async(
        &self,
        name: &str,
        input: murmur::tool::run::ToolInput,
        gate: Option<&mut crate::agent::CallGate<'_>>,
    ) -> Result<DispatchOutcome, String> {
        let mut outcome = self.dispatch_agent_tool_unfenced(name, input, gate).await?;
        // Every branch is fenced except the skill branch. A skill result is `skill.md`, read off
        // disk from inside the capsule, staged at install and fixed for the whole run: it is the
        // capsule author's own guidance and its entire purpose is to be followed as instruction,
        // so fencing it as data would make a declared skill inert. Every other branch returns
        // bytes produced at call time by something outside the capsule, and the runtime has no
        // notion of a trusted tool, so the rule for them needs no judgement: all of them are
        // fenced, unconditionally.
        if !outcome.is_skill {
            fence_tool_result(name, &mut outcome.result);
        }
        Ok(outcome)
    }

    /// [`Self::dispatch_agent_tool_async`]'s branches, before the fence. Private: whatever this
    /// returns reaches the model unfenced unless the caller fences it.
    ///
    /// Two callers. [`Self::dispatch_agent_tool_async`] fences the result and is the agent loop's
    /// route. [`Self::dispatch_submit_plan`] deliberately does not, because a plan step's output
    /// becomes one field of a report that is fenced as a whole.
    ///
    /// `gate` is carried through rather than consulted here: this is the branch table, and the
    /// decision point is applied by whoever is about to dispatch a call — the agent loop for its
    /// own turn, and [`crate::plan`] for each step of a submitted plan.
    async fn dispatch_agent_tool_unfenced(
        &self,
        name: &str,
        input: murmur::tool::run::ToolInput,
        gate: Option<&mut crate::agent::CallGate<'_>>,
    ) -> Result<DispatchOutcome, String> {
        // The two runtime-provided peer-handoff tools, intercepted ahead of every other path.
        // They have no artifact, no binary and no component: the manifests under
        // `workdir/tools/` exist so `build_tool_inventory` shows them to the model, and this is
        // where the call actually lands.
        if name == SHARE_FILE_TOOL {
            return self
                .dispatch_share_file(input)
                .await
                .map(DispatchOutcome::tool);
        }
        if name == FETCH_PEER_FILE_TOOL {
            return self
                .dispatch_fetch_peer_file(input)
                .await
                .map(DispatchOutcome::tool);
        }
        if name == DELEGATE_TASK_TOOL {
            return self
                .dispatch_delegate_task(input)
                .await
                .map(DispatchOutcome::tool);
        }
        if name == SUBMIT_PLAN_TOOL {
            return self
                .dispatch_submit_plan(input, gate)
                .await
                .map(DispatchOutcome::tool);
        }

        // Native artifact: packaged binary in workdir/tools/<name>/<name>
        let native_bin = self.workdir.join("tools").join(name).join(name);
        if native_bin.exists() && !self.tool_components.contains_key(name) {
            return enforce_allowlist(&self.allowlisted_tools, name, || {
                dispatch_native_tool(
                    name,
                    input,
                    &native_bin,
                    &self.accessible_workdir,
                    &self.workdir,
                    &self.capability_policy,
                    &self.shell_enforcement,
                )
            })
            .map(DispatchOutcome::tool);
        }

        // Shell tool — run on a blocking thread so the LocalSet stays free to handle
        // incoming HTTP requests (e.g. curl POSTing back to the same capsule's server).
        if self
            .capability_policy
            .shell_allow
            .iter()
            .any(|allowed| allowed == name)
        {
            let name = name.to_string();
            let accessible_workdir = self.accessible_workdir.clone();
            let session_workdir = self.workdir.clone();
            let env_overrides = self.inference_env.clone();
            let policy = self.capability_policy.clone();
            let enforcement = self.shell_enforcement.clone();
            // Both halves are required. Without a registry there is no task loop to deliver a
            // completion to; without a context id there is no conversation for the completion to
            // join, and a completion that opened its own would be a result nobody asked for.
            // `command` is filled in by `dispatch_shell_tool`, which is where it is parsed.
            let detach = match (&self.detached, &self.current_context_id) {
                (Some(registry), Some(context_id)) => Some(DetachPolicy {
                    grace: std::time::Duration::from_secs(self.shell_grace_secs),
                    registry: Arc::clone(registry),
                    command: String::new(),
                    context_id: context_id.clone(),
                    provenance: self.current_task_provenance,
                }),
                _ => None,
            };
            return tokio::task::spawn_blocking(move || {
                dispatch_shell_tool(
                    &name,
                    input,
                    &accessible_workdir,
                    &session_workdir,
                    &env_overrides,
                    &policy,
                    &enforcement,
                    detach,
                )
            })
            .await
            .map_err(|e| format!("shell tool panicked: {e}"));
        }

        // Skill artifact: return skill.md content as the tool result (no WASM dispatch).
        // Works in capsules with no shell/file capabilities — the runtime reads the file.
        let skill_md_path = self.workdir.join("tools").join(name).join("skill.md");
        if skill_md_path.exists() {
            let content = fs::read_to_string(&skill_md_path)
                .map_err(|e| format!("failed to read skill '{name}': {e}"))?;
            return Ok(DispatchOutcome::skill(murmur::tool::run::ToolResult {
                status: murmur::tool::run::Status::Passed,
                summary: Some(format!("Skill {name} guidance")),
                data: Some(content),
                data_path: None,
                truncated: false,
                metadata: Vec::new(),
            }));
        }

        // WASM tool
        if !self.allowlisted_tools.contains(name) {
            return Err(format!(
                "tool '{name}' is not declared in manifest allowlist"
            ));
        }
        self.dispatch_tool_async(name, input)
            .await
            .map(DispatchOutcome::tool)
    }

    /// `share-file`: mint one handle for one file, for one named peer.
    ///
    /// The audience is derived from the peer's own agent card, fetched here. That fetch is an
    /// ordinary outbound request and is enforced against `capabilities.network.allow` — the same
    /// rule `send::Host::send` applies — so **minting grants no new outbound authority**.
    ///
    /// Returns no filesystem path in any field. The agent asked for the path; echoing it back as
    /// a fact of the handle would make the handle look like an address, which is the one thing it
    /// is not.
    async fn dispatch_share_file(
        &self,
        input: murmur::tool::run::ToolInput,
    ) -> Result<murmur::tool::run::ToolResult, String> {
        let args = parse_tool_json_input(SHARE_FILE_TOOL, &input)?;
        let path = required_string_arg(SHARE_FILE_TOOL, &args, "path")?;
        let peer = required_string_arg(SHARE_FILE_TOOL, &args, "peer")?;
        let ttl = args.get("ttl").and_then(serde_json::Value::as_str);

        let Some(plane) = self.peer_plane.as_ref().filter(|plane| plane.is_declared()) else {
            return Err(format!(
                "'{SHARE_FILE_TOOL}' needs an exports.peer_files block in murmur.yaml; \
                 this capsule declares none"
            ));
        };

        let ttl_secs =
            match ttl {
                None => None,
                Some(text) => Some(murmur_artifact::parse_duration_secs(text).map_err(
                    |message| format!("'{SHARE_FILE_TOOL}' was given an unusable ttl: {message}"),
                )?),
            };

        let audience = match self.peer_audience_for(&peer).await {
            Ok(audience) => audience,
            Err(reason) => {
                self.trace_mint(
                    None,
                    &path,
                    "",
                    None,
                    "peer_unreachable",
                    Some(reason.clone()),
                )
                .await;
                return Err(reason);
            }
        };

        match plane.mint_handle(&path, &audience, ttl_secs) {
            Ok(minted) => {
                self.trace_mint(
                    Some(minted.handle_id.clone()),
                    &minted.path,
                    &minted.audience,
                    Some(minted.expires_at_ms),
                    "ok",
                    None,
                )
                .await;
                Ok(json_tool_result(
                    format!("Minted a handle for '{}' addressed to {}", path, audience),
                    serde_json::json!({
                        "handle": minted.handle,
                        "handle_id": minted.handle_id,
                        "expires_at_ms": minted.expires_at_ms,
                        "audience": minted.audience,
                    }),
                ))
            }
            Err(error) => {
                let reason = error.message();
                self.trace_mint(
                    None,
                    &path,
                    &audience,
                    None,
                    error.code(),
                    Some(reason.clone()),
                )
                .await;
                // Names the authoriser and nothing else: not the host path it resolved to, not
                // what it found there. A refused mint must not become a probe.
                Err(format!(
                    "'{SHARE_FILE_TOOL}' refused '{path}': {reason}. Only files under the \
                     declared exports.peer_files.root may be shared."
                ))
            }
        }
    }

    /// Records one launched child in this session's trace, before its delegation has ended.
    ///
    /// The registration into [`Self::live_delegations`] happens on the launching thread, in the
    /// plane's own launch callback, rather than here: this write is `async` and its wait can be
    /// cancelled, and a delegation that is up must be nameable whether or not the call that
    /// started it ever returned.
    async fn write_delegation_start(&self, notice: &crate::delegation_plane::DelegationLaunch) {
        if let Some(trace) = &self.peer_trace {
            trace
                .write_delegation_start(
                    &notice.delegation_id,
                    &notice.capsule,
                    &notice.version,
                    &notice.child_session_id,
                    &notice.child_workdir,
                )
                .await;
        }
    }

    /// Close the `delegation_start` this completion belongs to, as the task carrying it begins.
    ///
    /// A delegation that returns on start has not ended when its tool call returns, so this is
    /// where its terminal `delegation` line is written — one line per delegation still, joined to
    /// the start by the `dlg_` id both carry, and to the completion task by the same id on its
    /// `task_start`.
    ///
    /// `outcome` and `reason` come out of the child's own `completion.json`, never out of the
    /// completion's message text: both reporters write that file before they post, so the
    /// structured record is on disk by the time this task exists. A file that cannot be read still
    /// closes the row — a delegation left permanently in flight in the trace is a worse record
    /// than one whose outcome is stated as unknown.
    async fn close_started_delegation(&self, delegation_id: &str) {
        let Some(started) = self.live_delegations.finish(delegation_id) else {
            // A completion for a delegation this session did not start: another session's, or one
            // whose start was never recorded. `mur trace show` renders the terminal line on its
            // own row, which is the honest reading of it.
            return;
        };
        let Some(trace) = &self.peer_trace else {
            return;
        };
        let recorded = crate::delegation::read_completion(&started.workdir);
        let (outcome, reason, child_session_id, duration_ms) = match recorded {
            Some(outcome) => (
                outcome.status.as_str().to_string(),
                outcome.detail.clone(),
                Some(outcome.session_id.clone()).filter(|id| !id.is_empty()),
                outcome.duration_ms,
            ),
            None => (
                "unknown".to_string(),
                Some(format!(
                    "a completion arrived for this delegation, but no readable {} was left in {}",
                    crate::delegation::COMPLETION_FILE,
                    started.workdir.display()
                )),
                None,
                started
                    .started
                    .elapsed()
                    .as_millis()
                    .try_into()
                    .unwrap_or(u64::MAX),
            ),
        };
        trace
            .write_delegation(
                &started.capsule,
                &started.version,
                Some(delegation_id.to_string()),
                child_session_id,
                duration_ms,
                &outcome,
                reason,
            )
            .await;
    }

    /// `delegate-task`: hand one task to one sub-capsule and return as soon as it holds it.
    ///
    /// The agent names a capsule, a version and a task. Everything else — the daemon's address,
    /// this session's credential, the approval, the child's directory, the child's process and the
    /// A2A conversation with it — is composed by [`crate::delegation_plane::DelegationPlane`] and
    /// never enters the model's context. That is why a delegating capsule needs no
    /// `capabilities.network.allow` entry for the daemon: it never addresses it.
    ///
    /// **The call returns when the child starts, not when it finishes.** What the child did
    /// arrives afterwards as a `completion`-origin task in the background lane, carrying this
    /// delegation's `dlg_` id — so one turn can issue several delegations and carry on while all
    /// of them run. The `data` this returns therefore names a delegation in flight and carries no
    /// answer: `output` and `result_path` are absent, and `child_workdir` is where the child's
    /// own trace and, later, its result will be.
    ///
    /// Still run on a blocking thread, exactly as the shell branch is, because the plane's three
    /// steps — the daemon, the launch and the delivery — are blocking calls; it is now the length
    /// of a launch rather than the length of a child's run.
    async fn dispatch_delegate_task(
        &self,
        input: murmur::tool::run::ToolInput,
    ) -> Result<murmur::tool::run::ToolResult, String> {
        let args = parse_tool_json_input(DELEGATE_TASK_TOOL, &input)?;
        let request = crate::delegation_plane::DelegationRequest {
            capsule: required_string_arg(DELEGATE_TASK_TOOL, &args, "capsule")?,
            version: required_string_arg(DELEGATE_TASK_TOOL, &args, "version")?,
            task: required_string_arg(DELEGATE_TASK_TOOL, &args, "task")?,
        };

        let Some(plane) = self.delegation.as_ref() else {
            return Err(format!(
                "'{DELEGATE_TASK_TOOL}' needs a capabilities.spawn.allow list in murmur.yaml; \
                 this capsule declares none"
            ));
        };

        // Which capsules may be delegated to is the daemon's question, not this runtime's: the
        // referee holds the parent's envelope and answers with a sentence naming the manifest key
        // and the entry that failed. Pre-empting it here would replace that sentence with a
        // weaker one and let a capsule self-authorise its own spawn rights.
        let plane = Arc::clone(plane);
        let started = std::time::Instant::now();
        // The launch notice leaves the blocking call on a channel whose `send` is synchronous, so
        // the parent's `delegation_start` reaches disk while the launch is still finishing rather
        // than after it returns — which is the whole point of the record, for a child that is
        // about to be handed a task and may then hang or crash. This side of the plane's callback
        // is a channel because the write is `async`: the notice has to cross back to the task
        // loop below to be written at all.
        let (launch_tx, mut launch_rx) = tokio::sync::mpsc::unbounded_channel();
        let live = Arc::clone(&self.live_delegations);
        let child_root = self.accessible_workdir.clone();
        let origin = crate::delegation_plane::DelegationOrigin {
            context_id: self.current_context_id.clone().unwrap_or_default(),
            launched: Some(Arc::new(
                move |notice: crate::delegation_plane::DelegationLaunch| {
                    // Registered here, synchronously on the launching thread, so a child that is up is
                    // in the live set before anything can wait on it — including when the wait below
                    // is cancelled and the trace write never happens.
                    live.register(
                        notice.delegation_id.clone(),
                        crate::cancel::LiveDelegation {
                            workdir: child_root.join(&notice.child_workdir),
                            capsule: notice.capsule.clone(),
                            version: notice.version.clone(),
                            child_session_id: notice.child_session_id.clone(),
                            child_workdir: notice.child_workdir.clone(),
                            started: std::time::Instant::now(),
                        },
                    );
                    let _ = launch_tx.send(notice);
                },
            )),
            // The completion this delegation posts inherits the delegating task's class, the same
            // derivation a demoted shell command's completion uses. `None` — the script-capsule
            // path — is read as untrusted by the plane.
            trust: self.current_task_provenance.map(|task| task.trust()),
        };
        // A cancel that lands mid-launch must not queue behind it: the child is already the live
        // set's problem, and the person who stopped the task is waiting on an answer.
        let cancel = self.task_cancel_signal();
        let mut starting = tokio::task::spawn_blocking(move || plane.start(&request, &origin));
        let mut notices_open = true;
        let joined = loop {
            tokio::select! {
                biased;
                () = async {
                    match &cancel {
                        Some(signal) => signal.canceled().await,
                        None => std::future::pending().await,
                    }
                } => {
                    if let Some(signal) = &cancel {
                        signal.note_phase(crate::cancel::PHASE_DELEGATION);
                    }
                    // Whatever the launch is doing continues on its own thread; nothing here kills
                    // it. A child that came up is in the live set and is named as residue.
                    while let Ok(notice) = launch_rx.try_recv() {
                        self.write_delegation_start(&notice).await;
                    }
                    return Err(format!(
                        "'{DELEGATE_TASK_TOOL}' was canceled while the sub-capsule was starting; \
                         any child that came up is still running and is named in the cancel's \
                         residue"
                    ));
                }
                notice = launch_rx.recv(), if notices_open => match notice {
                    Some(notice) => self.write_delegation_start(&notice).await,
                    // The sender lives in the blocking closure, so this is that closure ending.
                    None => notices_open = false,
                },
                joined = &mut starting => break joined,
            }
        };
        // A launch that finished between the arms being polled leaves its notice behind, and it
        // still has to be recorded.
        while let Ok(notice) = launch_rx.try_recv() {
            self.write_delegation_start(&notice).await;
        }
        let result = joined.map_err(|error| format!("'{DELEGATE_TASK_TOOL}' panicked: {error}"))?;

        let duration_ms = started.elapsed().as_millis().try_into().unwrap_or(u64::MAX);
        let status = result.status;
        // A delegation that started has not ended, so its terminal `delegation` line is not
        // written here: it is written when the completion arrives, by
        // [`Self::close_started_delegation`]. Only a delegation that will never produce a
        // completion — the daemon refused it, or the child never took its task — is closed now.
        if status != crate::delegation_plane::DelegationStatus::Started {
            // A launch that got far enough to be announced but not far enough to be started is
            // closed here, so the row it opened is not also waiting for a completion that will
            // never come.
            self.live_delegations.release(&result.delegation_id);
            if let Some(trace) = &self.peer_trace {
                trace
                    .write_delegation(
                        &result.capsule,
                        &result.version,
                        Some(result.delegation_id.clone()).filter(|id| !id.is_empty()),
                        Some(result.session_id.clone()).filter(|id| !id.is_empty()),
                        duration_ms,
                        status.as_str(),
                        Some(result.output.clone()),
                    )
                    .await;
            }
        }

        // A refusal is the referee's own sentence and nothing else. The operator reading it has to
        // see which manifest key and which entry to edit, not the HTTP transcript that carried it,
        // and not this runtime's opinion wrapped around it.
        if status == crate::delegation_plane::DelegationStatus::Refused {
            return Err(result.output);
        }

        let summary = format!(
            "Delegated to {}@{}: {}",
            result.capsule,
            result.version,
            status.as_str()
        );
        let mut data = serde_json::json!({
            "delegation_id": result.delegation_id,
            "session_id": result.session_id,
            "capsule": result.capsule,
            "version": result.version,
            "status": status.as_str(),
        });
        match &result.child_workdir {
            // Present only on a started delegation, and the only path there is to the child's own
            // trace: joined to this capsule's workdir, it is a directory the parent's ordinary
            // file tools can already address.
            Some(workdir) => {
                data["child_workdir"] = serde_json::Value::String(workdir.clone());
            }
            // A failed start produced no child worth naming, so what the agent gets is why.
            None => {
                data["output"] = serde_json::Value::String(result.output.clone());
            }
        }
        Ok(murmur::tool::run::ToolResult {
            status: if status == crate::delegation_plane::DelegationStatus::Started {
                murmur::tool::run::Status::Passed
            } else {
                murmur::tool::run::Status::Failed
            },
            summary: Some(summary),
            data: Some(data.to_string()),
            data_path: None,
            truncated: result.truncated,
            metadata: Vec::new(),
        })
    }

    /// `submit-plan`: run one plan of steps to completion and return every step's result.
    ///
    /// The scheduler is `crate::plan`, and every `tool` step it runs comes back through
    /// [`Self::dispatch_agent_tool_unfenced`] — this session's own dispatch, with this session's
    /// own allowlist and shell grant. Every `tool` and `shell` step is put to `gate` first, which
    /// is the same decision point the agent loop applies to its own calls, so a plan step is
    /// subject to `capabilities.filesystem.read_only` and to a `commit_policy: deny` policy hook
    /// exactly as the equivalent direct call is. A plan therefore reaches exactly what the model
    /// could already call one turn at a time, and nothing else. `submit-plan` itself is refused
    /// as a step by `plan::validate_plan`, so a plan cannot submit a plan.
    ///
    /// The scheduler is blocking and thread-scoped, so it runs on `spawn_blocking` while this
    /// side services its tool calls over a channel — the shape [`Self::dispatch_delegate_task`]
    /// uses for its launch notices, for the same reason: the blocking side has no runtime handle
    /// and the `!Send` WASI state it needs lives on this `LocalSet`.
    async fn dispatch_submit_plan(
        &self,
        input: murmur::tool::run::ToolInput,
        mut gate: Option<&mut crate::agent::CallGate<'_>>,
    ) -> Result<murmur::tool::run::ToolResult, String> {
        if !self.capability_policy.plan_submit {
            return Err(format!(
                "'{SUBMIT_PLAN_TOOL}' needs a capabilities.plan.submit: true declaration in \
                 murmur.yaml; this capsule declares none"
            ));
        }

        let args = parse_tool_json_input(SUBMIT_PLAN_TOOL, &input)?;
        let Some(serde_json::Value::Object(plan)) = args.get("plan") else {
            return Err(format!(
                "'{SUBMIT_PLAN_TOOL}' requires a 'plan' argument holding a JSON object with an \
                 'id' and a 'steps' array"
            ));
        };
        let plan_id = plan
            .get("id")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default()
            .to_string();
        let plan_path = self.write_plan_file(plan)?;

        // Every directory under `tools/` is a tool this session can dispatch, which is what
        // `validate_plan` checks a `tool` step against. `submit-plan` is left out so a plan
        // naming it is refused for what it is rather than for the tool being absent.
        let installed_tools: HashSet<String> = fs::read_dir(self.workdir.join("tools"))
            .into_iter()
            .flatten()
            .flatten()
            .filter(|entry| entry.path().is_dir())
            .filter_map(|entry| entry.file_name().into_string().ok())
            .filter(|name| name != SUBMIT_PLAN_TOOL)
            .collect();

        // The blocking side asks for a decision or a tool call and waits; this side answers it.
        // Unbounded because a plan's fan-out is its own bound: every request in flight is one
        // scheduler thread already parked on its reply.
        let (request_tx, mut request_rx) = tokio::sync::mpsc::unbounded_channel::<PlanRequest>();

        // The same short-circuit the agent loop applies to its own calls: with neither a policy
        // hook nor a `read_only` declaration there is nothing that can refuse a step, so no step
        // resolves a call and no step crosses the channel to ask.
        let gates = gate.as_ref().is_some_and(|gate| gate.gates(self));

        let capability_policy = self.capability_policy.clone();
        let scheduler_workdir = self.accessible_workdir.clone();
        let scheduler_session_workdir = self.workdir.clone();
        let session_id = self.session_id.clone();
        // The conversation this plan was submitted from, named on the `MURMUR_SPAWNER` handle
        // every `capsule` step injects into its child — the same value `delegate-task` names.
        let current_context_id = self.current_context_id.clone();
        // Cloned off the plane rather than held a second time on this state: one registration's
        // authority stays in one place.
        let spawn_credential = self.delegation.as_ref().map(|plane| plane.credential());
        let plan_trace = self.plan_trace.clone();
        let registry = Arc::clone(&self.registry);
        let gate_tx = request_tx.clone();
        let mut scheduling = tokio::task::spawn_blocking(move || {
            let gate_step = move |call: &crate::plan::PlannedCall<'_>| -> Option<String> {
                if !gates {
                    return None;
                }
                let (reply_tx, reply_rx) = tokio::sync::oneshot::channel();
                // Fail closed on both arms: a decision point that cannot be reached refuses, so
                // a session shutting down mid-plan cannot let a step through ungated.
                if gate_tx
                    .send(PlanRequest::Gate(
                        GatedStepCall::from_planned(call),
                        reply_tx,
                    ))
                    .is_err()
                {
                    return Some(PLAN_GATE_UNREACHABLE.to_string());
                }
                reply_rx
                    .blocking_recv()
                    .unwrap_or_else(|_| Some(PLAN_GATE_UNREACHABLE.to_string()))
            };
            let invoke_tool = move |name: &str, input: murmur::tool::run::ToolInput| {
                let (reply_tx, reply_rx) = tokio::sync::oneshot::channel();
                request_tx
                    .send(PlanRequest::Invoke(name.to_string(), input, reply_tx))
                    .map_err(|_| "the session stopped answering plan tool calls".to_string())?;
                reply_rx
                    .blocking_recv()
                    .map_err(|_| "the session stopped answering plan tool calls".to_string())?
            };
            let ctx = crate::plan::SchedulerContext {
                accessible_workdir: scheduler_workdir,
                session_workdir: scheduler_session_workdir,
                capability_policy,
                installed_tools,
                // A `capsule` step's version is the daemon's question, not this session's: the
                // scheduler falls back to `0.1.0` for a name it holds no version for, and a
                // session holds none for any of them.
                capsule_versions: HashMap::new(),
                current_session_id: Some(session_id),
                current_context_id,
                registry,
                spawn_credential,
                trace: plan_trace.as_deref(),
                gate_step: &gate_step,
                invoke_tool: &invoke_tool,
            };
            crate::plan::execute(&plan_path, &ctx)
        });

        let mut requests_open = true;
        let joined = loop {
            tokio::select! {
                request = request_rx.recv(), if requests_open => match request {
                    Some(request) => self.answer_plan_request(request, gate.as_deref_mut()).await,
                    // The senders live in the blocking closure, so this is that closure ending.
                    None => requests_open = false,
                },
                joined = &mut scheduling => break joined,
            }
        };
        // A request that arrived between the two arms being polled still has a scheduler thread
        // parked on its reply, and the join above only means the outer closure returned.
        while let Ok(request) = request_rx.try_recv() {
            self.answer_plan_request(request, gate.as_deref_mut()).await;
        }
        let report = joined.map_err(|error| format!("'{SUBMIT_PLAN_TOOL}' panicked: {error}"))?;

        let mut succeeded = 0usize;
        let mut failed = 0usize;
        let mut skipped = 0usize;
        let steps: Vec<serde_json::Value> = report
            .results
            .iter()
            .map(|result| {
                match result.status {
                    crate::plan::StepStatus::Success => succeeded += 1,
                    crate::plan::StepStatus::Failed => failed += 1,
                    crate::plan::StepStatus::Skipped => skipped += 1,
                }
                serde_json::json!({
                    "step_id": result.step_id,
                    "status": result.status.as_str(),
                    "output": result.output,
                    "error": result.error,
                })
            })
            .collect();
        let data = serde_json::json!({
            "plan_id": plan_id,
            "completed": report.completed,
            "failed_step": report.failed_step,
            "steps": steps,
        });
        let summary = format!(
            "Plan '{plan_id}': {} steps, {succeeded} succeeded, {failed} failed, {skipped} skipped",
            report.results.len()
        );

        Ok(murmur::tool::run::ToolResult {
            // The status carries the plan's outcome so the model is told the plan did not
            // complete, rather than having to read the report to notice.
            status: if report.completed {
                murmur::tool::run::Status::Passed
            } else {
                murmur::tool::run::Status::Failed
            },
            summary: Some(summary),
            data: Some(data.to_string()),
            data_path: None,
            truncated: false,
            metadata: Vec::new(),
        })
    }

    /// Answer one request from a running plan: a decision point, or a `tool` step's call.
    ///
    /// Split out of the servicing loop because the loop asks twice — once while the scheduler is
    /// still running and once to drain what arrived as it joined — and a request answered on one
    /// path but not the other would leave a scheduler thread parked forever.
    async fn answer_plan_request(
        &self,
        request: PlanRequest,
        gate: Option<&mut crate::agent::CallGate<'_>>,
    ) {
        match request {
            PlanRequest::Gate(call, reply) => {
                let verdict = match gate {
                    Some(gate) => {
                        let resolved = call.resolve(&self.accessible_workdir);
                        // A refusal that could not be recorded refuses anyway: an unaudited call
                        // is the thing the decision point exists to prevent.
                        match gate.check(self, &resolved).await {
                            Ok(verdict) => verdict,
                            Err(error) => Some(error.to_string()),
                        }
                    }
                    None => None,
                };
                let _ = reply.send(verdict);
            }
            PlanRequest::Invoke(name, input, reply) => {
                // Unfenced deliberately: this result becomes one field of the plan report, and
                // `dispatch_agent_tool_async` fences that report once on its way to the model.
                // Fencing here would wrap every step's output a second time.
                //
                // Boxed because this reaches back into the dispatcher that called it: the two
                // futures are mutually recursive and one of them has to be behind a pointer for
                // either to have a size. `validate_plan` refuses a `submit-plan` step, so the
                // recursion is one level deep in practice.
                let outcome = Box::pin(self.dispatch_agent_tool_unfenced(&name, input, gate))
                    .await
                    .map(|outcome| outcome.result);
                let _ = reply.send(outcome);
            }
        }
    }

    /// Write one submitted plan into `<workdir>/plans/plan-<n>.json` and return its path.
    ///
    /// `n` is this session's own counter and the plan's `id` reaches no part of the name: the id
    /// is model-supplied, and a file named from it could collide or traverse.
    fn write_plan_file(
        &self,
        plan: &serde_json::Map<String, serde_json::Value>,
    ) -> Result<PathBuf, String> {
        let plans_dir = self.workdir.join("plans");
        fs::create_dir_all(&plans_dir)
            .map_err(|error| format!("'{SUBMIT_PLAN_TOOL}' could not create plans/: {error}"))?;
        let ordinal = self.plan_counter.fetch_add(1, Ordering::Relaxed) + 1;
        let plan_path = plans_dir.join(format!("plan-{ordinal}.json"));
        let body = serde_json::Value::Object(plan.clone()).to_string();
        fs::write(&plan_path, body).map_err(|error| {
            format!(
                "'{SUBMIT_PLAN_TOOL}' could not write {}: {error}",
                plan_path.display()
            )
        })?;
        Ok(plan_path)
    }

    /// The audience a handle for `peer` must be minted for, read off that peer's own agent card.
    async fn peer_audience_for(&self, peer: &str) -> Result<String, String> {
        check_destination_allowed(
            &self.network_allow_rules,
            peer,
            "capabilities.network.allow",
        )?;
        let card = crate::outgoing::fetch_agent_card(peer)
            .await
            .map_err(|error| format!("peer_unreachable: {error}"))?;
        crate::peer_handoff::audience_from_card(&card)
            .map_err(|error| format!("peer_unreachable: {error}"))
    }

    #[allow(clippy::too_many_arguments)]
    async fn trace_mint(
        &self,
        handle_id: Option<String>,
        path: &str,
        audience: &str,
        expires_at_ms: Option<u64>,
        outcome: &str,
        reason: Option<String>,
    ) {
        if let Some(trace) = &self.peer_trace {
            trace
                .write_peer_handle_mint(handle_id, path, audience, expires_at_ms, outcome, reason)
                .await;
        }
    }

    /// `fetch-peer-file`: redeem a handle a peer sent and land the bytes as a file.
    ///
    /// The bytes are never placed in the result and never returned as text. Ingestion is a file
    /// the agent must decide to read, not context it is handed — a peer that can put arbitrary
    /// content in front of this model would otherwise have a prompt-injection channel that costs
    /// it nothing.
    async fn dispatch_fetch_peer_file(
        &self,
        input: murmur::tool::run::ToolInput,
    ) -> Result<murmur::tool::run::ToolResult, String> {
        let args = parse_tool_json_input(FETCH_PEER_FILE_TOOL, &input)?;
        let peer = required_string_arg(FETCH_PEER_FILE_TOOL, &args, "peer")?;
        let handle = required_string_arg(FETCH_PEER_FILE_TOOL, &args, "handle")?;
        let handle_id = crate::peer_handoff::handle_id(&handle);

        // Before any connection is opened, so a refused destination is never contacted at all.
        if let Err(reason) = check_destination_allowed(
            &self.peer_fetch_rules,
            &peer,
            "capabilities.peer_fetch.allow",
        ) {
            self.trace_fetch(
                &peer,
                &handle_id,
                None,
                "peer_not_allowed",
                Some(reason.clone()),
            )
            .await;
            return Err(reason);
        }

        let response = match crate::outgoing::redeem_peer_handle(
            &peer,
            &handle,
            &self.peer_own_audience,
        )
        .await
        {
            Ok(response) => response,
            Err(error) => {
                self.trace_fetch(
                    &peer,
                    &handle_id,
                    None,
                    "peer_unreachable",
                    Some(error.clone()),
                )
                .await;
                return Err(format!(
                    "'{FETCH_PEER_FILE_TOOL}' could not reach {peer}: {error}"
                ));
            }
        };

        if response.status != 200 {
            // The peer's own refusal code, restated rather than flattened: `handle_expired` and
            // `handle_not_valid` mean different things to whoever reads the trace.
            let code = serde_json::from_slice::<serde_json::Value>(&response.body)
                .ok()
                .and_then(|body| {
                    body.get("error")
                        .and_then(serde_json::Value::as_str)
                        .map(str::to_string)
                })
                .unwrap_or_else(|| format!("http_{}", response.status));
            let reason = format!("{peer} refused the handle: {code}");
            self.trace_fetch(&peer, &handle_id, None, &code, Some(reason.clone()))
                .await;
            return Err(format!("'{FETCH_PEER_FILE_TOOL}' failed: {reason}"));
        }

        let sha256 = murmur_artifact::sha256_hex(&response.body);
        // The validator the peer served describes the body it accompanies, so disagreeing with it
        // means the bytes were not the ones that were hashed. Refuse rather than store.
        if let Some(etag) = response.header("etag") {
            let expected = format!("\"sha256:{sha256}\"");
            if etag != expected {
                let reason = format!("{peer} served an etag that does not describe its own body");
                self.trace_fetch(
                    &peer,
                    &handle_id,
                    None,
                    "etag_mismatch",
                    Some(reason.clone()),
                )
                .await;
                return Err(format!("'{FETCH_PEER_FILE_TOOL}' failed: {reason}"));
            }
        }
        let generation = response
            .header("x-murmur-generation")
            .and_then(|value| value.parse::<u64>().ok());

        // Runtime-chosen, never peer-chosen: the peer discloses no path, and the basename is only
        // a hint read out of the token's own unverified payload.
        let basename = crate::peer_handoff::decode_payload_unverified(&handle).map(|p| p.p);
        let stored_path = crate::peer_handoff::stored_path_for(&handle_id, basename.as_deref());
        let absolute = self.accessible_workdir.join(&stored_path);
        if let Some(parent) = absolute.parent() {
            if let Err(error) = fs::create_dir_all(parent) {
                let reason = format!("failed to create {}: {error}", parent.display());
                self.trace_fetch(&peer, &handle_id, None, "io_error", Some(reason.clone()))
                    .await;
                return Err(format!("'{FETCH_PEER_FILE_TOOL}' failed: {reason}"));
            }
        }
        if let Err(error) = fs::write(&absolute, &response.body) {
            let reason = format!("failed to write {stored_path}: {error}");
            self.trace_fetch(&peer, &handle_id, None, "io_error", Some(reason.clone()))
                .await;
            return Err(format!("'{FETCH_PEER_FILE_TOOL}' failed: {reason}"));
        }

        if let Some(trace) = &self.peer_trace {
            trace
                .write_peer_file_fetch(
                    &peer,
                    &handle_id,
                    Some(stored_path.clone()),
                    Some(response.body.len() as u64),
                    Some(sha256.clone()),
                    "ok",
                    None,
                )
                .await;
        }

        let mut data = serde_json::json!({
            "path": stored_path,
            "bytes": response.body.len(),
            "sha256": sha256,
            "peer": peer,
        });
        if let Some(generation) = generation {
            data["generation"] = serde_json::json!(generation);
        }
        Ok(json_tool_result(
            format!(
                "Stored {} bytes from {peer} at {stored_path}",
                response.body.len()
            ),
            data,
        ))
    }

    async fn trace_fetch(
        &self,
        peer: &str,
        handle_id: &str,
        stored_path: Option<String>,
        outcome: &str,
        reason: Option<String>,
    ) {
        if let Some(trace) = &self.peer_trace {
            trace
                .write_peer_file_fetch(peer, handle_id, stored_path, None, None, outcome, reason)
                .await;
        }
    }
}

/// Refuses a destination that no rule in `rules` covers, naming the manifest key that would have
/// to allow it.
///
/// The same `RequestTarget`/`NetworkAllowRule` pair `send::Host::send` uses, applied to a second,
/// separate list — so `capabilities.peer_fetch.allow` and `capabilities.network.allow` are
/// enforced by one matcher and can never drift into two dialects.
fn check_destination_allowed(
    rules: &[NetworkAllowRule],
    peer_url: &str,
    field: &str,
) -> Result<(), String> {
    let for_parse = if peer_url.contains("://") {
        peer_url.to_string()
    } else {
        format!("http://{peer_url}")
    };
    let uri: http::Uri = for_parse
        .parse()
        .map_err(|e| format!("invalid peer URL '{peer_url}': {e}"))?;
    let target = RequestTarget::from_request(&uri, false)
        .ok_or_else(|| format!("invalid peer URL '{peer_url}'"))?;
    if rules.iter().any(|rule| rule.matches(&target)) {
        return Ok(());
    }
    Err(format!("network policy: '{peer_url}' not in {field}"))
}

/// One tool call's `data` field, parsed as a JSON object.
fn parse_tool_json_input(
    tool: &str,
    input: &murmur::tool::run::ToolInput,
) -> Result<serde_json::Map<String, serde_json::Value>, String> {
    let raw = input.data.as_deref().unwrap_or("{}");
    let raw = if raw.trim().is_empty() { "{}" } else { raw };
    match serde_json::from_str::<serde_json::Value>(raw) {
        Ok(serde_json::Value::Object(map)) => Ok(map),
        _ => Err(format!("'{tool}' expects a JSON object as its input")),
    }
}

fn required_string_arg(
    tool: &str,
    args: &serde_json::Map<String, serde_json::Value>,
    key: &str,
) -> Result<String, String> {
    args.get(key)
        .and_then(serde_json::Value::as_str)
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(str::to_string)
        .ok_or_else(|| format!("'{tool}' requires a non-empty '{key}'"))
}

/// A passing tool result whose `data` is a JSON object. The agent loop sends `data || summary` to
/// the model, so the object is what the model reads back.
fn json_tool_result(summary: String, data: serde_json::Value) -> murmur::tool::run::ToolResult {
    murmur::tool::run::ToolResult {
        status: murmur::tool::run::Status::Passed,
        summary: Some(summary),
        data: Some(data.to_string()),
        data_path: None,
        truncated: false,
        metadata: Vec::new(),
    }
}

fn read_artifact_info_from_manifest(
    manifest_path: &Path,
    fallback: &InstalledArtifactSummary,
) -> Result<manage::ArtifactInfo, String> {
    let manifest_content = fs::read_to_string(manifest_path)
        .map_err(|err| format!("failed to read {}: {err}", manifest_path.display()))?;

    let value: Value = serde_yaml::from_str(&manifest_content)
        .map_err(|err| format!("failed to parse {}: {err}", manifest_path.display()))?;

    let root = value.as_mapping();

    let description = root
        .and_then(|mapping| mapping.get(Value::String("description".to_string())))
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string();

    let tags = root
        .and_then(|mapping| mapping.get(Value::String("tags".to_string())))
        .and_then(Value::as_sequence)
        .map(|items| {
            items
                .iter()
                .filter_map(Value::as_str)
                .map(ToString::to_string)
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();

    let input_schema = root
        .and_then(|mapping| mapping.get(Value::String("input_schema".to_string())))
        .map(yaml_to_json_string)
        .transpose()?;
    let output_schema = root
        .and_then(|mapping| mapping.get(Value::String("output_schema".to_string())))
        .map(yaml_to_json_string)
        .transpose()?;

    Ok(manage::ArtifactInfo {
        name: fallback.name.clone(),
        version: fallback.version.clone(),
        description,
        tags,
        runtime: runtime_type_to_wit(&fallback.runtime, fallback.implementation.as_ref()),
        input_schema,
        output_schema,
    })
}

fn yaml_to_json_string(value: &Value) -> Result<String, String> {
    if let Value::String(s) = value {
        if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(s) {
            return serde_json::to_string(&parsed)
                .map_err(|err| format!("failed to convert schema to JSON: {err}"));
        }
    }
    serde_json::to_string(value).map_err(|err| format!("failed to convert schema to JSON: {err}"))
}

fn runtime_type_to_wit(
    runtime: &ArtifactRuntime,
    implementation: Option<&ArtifactImplementation>,
) -> manage::RuntimeType {
    match (runtime, implementation) {
        (ArtifactRuntime::Tool, Some(ArtifactImplementation::Native)) => {
            manage::RuntimeType::Native
        }
        _ => manage::RuntimeType::Wasm,
    }
}

struct ToolStoreState {
    /// Resource limiter for this store — see [`CapsuleStoreState::limits`].
    limits: ExecutionLimiter,
    table: ResourceTable,
    wasi: WasiCtx,
    http: WasiHttpCtx,
    http_hooks: NetworkPolicyHooks,
}

impl WasiView for ToolStoreState {
    fn ctx(&mut self) -> WasiCtxView<'_> {
        WasiCtxView {
            ctx: &mut self.wasi,
            table: &mut self.table,
        }
    }
}

impl WasiHttpView for ToolStoreState {
    fn http(&mut self) -> WasiHttpCtxView<'_> {
        WasiHttpCtxView {
            ctx: &mut self.http,
            table: &mut self.table,
            hooks: &mut self.http_hooks,
        }
    }
}

/// The tool names the runtime answers itself, and which therefore no artifact may claim.
///
/// This is the single definition of the set. Each member is answered inside
/// `dispatch_agent_tool_unfenced` before any allowlist check is reached, so an artifact installed
/// under one of these names would be shadowed at dispatch no matter what the allowlist said — and
/// its `tools/<name>/murmur.yaml` would in any case be overwritten by the synthetic write that
/// follows the staging loop.
///
/// Shell binary names are deliberately absent: they are operator-chosen through
/// `capabilities.shell.allow`, so there is no fixed set to reserve, and
/// `write_shell_tool_manifests` already yields to an artifact manifest that is already on disk.
pub(crate) const RESERVED_TOOL_NAMES: [&str; 4] = [
    SHARE_FILE_TOOL,
    FETCH_PEER_FILE_TOOL,
    DELEGATE_TASK_TOOL,
    SUBMIT_PLAN_TOOL,
];

/// Whether `name` is answered by the runtime itself rather than by an artifact.
///
/// Matched exactly rather than case-insensitively: artifact names are case-sensitive everywhere
/// else in this codebase, so a name differing only in case is a different artifact.
#[must_use]
pub(crate) fn is_reserved_tool_name(name: &str) -> bool {
    RESERVED_TOOL_NAMES.contains(&name)
}

/// Refuses the first declared artifact name that collides with a runtime-provided tool.
///
/// Called from `stage_session` ahead of the artifact loop, and from `mur run` ahead of its
/// installed-artifact pre-flight, so the operator is told about the collision rather than about a
/// missing artifact they were never going to be allowed to install under that name.
pub fn check_no_reserved_tool_names<'a, I>(names: I) -> Result<(), RuntimeError>
where
    I: IntoIterator<Item = &'a str>,
{
    for name in names {
        if is_reserved_tool_name(name) {
            return Err(RuntimeError::ReservedToolName {
                name: name.to_string(),
            });
        }
    }
    Ok(())
}

/// A `capabilities.env.allow` entry the credential backstop removes from every guest environment,
/// with the pattern that removes it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StrippedEnvAllowEntry {
    /// The declared variable name, verbatim. Never its value.
    pub name: String,
    /// The matching backstop pattern, verbatim.
    pub pattern: String,
    /// The list the pattern came from.
    pub source: crate::shell::BackstopPatternSource,
}

/// Every distinct `policy.env_allow` name the credential backstop drops, in first-declaration
/// order, each attributed through [`crate::credential_backstop_match`] against
/// `policy.shell_strip_env`. Empty when every declared name reaches the guest, including when
/// `env_allow` is empty. Judged from names alone.
pub fn stripped_env_allow_entries(policy: &CapabilityPolicy) -> Vec<StrippedEnvAllowEntry> {
    let mut entries: Vec<StrippedEnvAllowEntry> = Vec::new();
    for name in &policy.env_allow {
        if entries.iter().any(|entry| &entry.name == name) {
            continue;
        }
        if let Some(matched) =
            crate::shell::credential_backstop_match(name, &policy.shell_strip_env)
        {
            entries.push(StrippedEnvAllowEntry {
                name: name.clone(),
                pattern: matched.pattern,
                source: matched.source,
            });
        }
    }
    entries
}

/// Refuses a capsule whose `capabilities.env.allow` names a variable the credential backstop
/// strips, naming every such entry at once.
///
/// [`crate::shell::build_wasi_env_allowlist`] drops those names whatever the manifest says, so the
/// grant would deliver nothing. Called from `stage_session` ahead of every registry resolve, from
/// `mur run` ahead of `--explain-scope`, and from `mur doctor` as a warning, so all three judge
/// one set of manifests.
pub fn check_env_allow_reaches_guests(policy: &CapabilityPolicy) -> Result<(), RuntimeError> {
    let entries = stripped_env_allow_entries(policy);
    if entries.is_empty() {
        return Ok(());
    }
    Err(RuntimeError::EnvAllowStrippedByBackstop { entries })
}

/// The `E-CAP-016` entry list: `'NAME' (<source> pattern 'PATTERN')`, comma-joined.
pub(crate) fn describe_stripped_env_allow_entries(entries: &[StrippedEnvAllowEntry]) -> String {
    entries
        .iter()
        .map(|entry| {
            let source = match entry.source {
                crate::shell::BackstopPatternSource::Builtin => "credential backstop",
                crate::shell::BackstopPatternSource::StripEnv => "capabilities.shell.strip_env",
            };
            format!("'{}' ({source} pattern '{}')", entry.name, entry.pattern)
        })
        .collect::<Vec<_>>()
        .join(", ")
}

/// Write a single artifact's `murmur.yaml` under `<workdir>/tools/<name>/`.
///
/// Used both by `stage_session` (for every artifact declared in the manifest) and by
/// `manage.pull()` (for the single artifact it just fetched at runtime). It is the only function
/// that writes an *artifact's* tool manifest, which is why the reserved-name guard sits here: the
/// pull path has no staging check ahead of it, and a capsule that pulled `delegate-task` at
/// runtime would otherwise overwrite the synthetic manifest and lose every call to the
/// interception in `dispatch_agent_tool_unfenced`.
fn write_tool_manifest(
    workdir: &Path,
    name: &str,
    manifest_yaml: &str,
) -> Result<(), RuntimeError> {
    if is_reserved_tool_name(name) {
        return Err(RuntimeError::ReservedToolName {
            name: name.to_string(),
        });
    }
    write_tool_manifest_unchecked(workdir, name, manifest_yaml)
}

/// Write one runtime-provided tool's synthetic `murmur.yaml`, carrying the inverse guard.
///
/// A name absent from [`RESERVED_TOOL_NAMES`] is refused, so a further runtime-provided tool
/// routed through here without being added to the list fails loudly instead of shipping shadowable
/// by an artifact of the same name.
fn write_runtime_provided_tool_manifest(
    workdir: &Path,
    name: &str,
    manifest_yaml: &str,
) -> Result<(), RuntimeError> {
    if !is_reserved_tool_name(name) {
        return Err(RuntimeError::RuntimeProvidedToolNotReserved {
            name: name.to_string(),
        });
    }
    write_tool_manifest_unchecked(workdir, name, manifest_yaml)
}

/// The write both guarded entry points share, once their opposite name checks have passed.
fn write_tool_manifest_unchecked(
    workdir: &Path,
    name: &str,
    manifest_yaml: &str,
) -> Result<(), RuntimeError> {
    let manifest_path = workdir.join("tools").join(name).join(PACKED_MANIFEST_ENTRY);
    let Some(parent) = manifest_path.parent() else {
        return Err(RuntimeError::Runtime(format!(
            "failed to derive parent for tool manifest path {}",
            manifest_path.display()
        )));
    };

    fs::create_dir_all(parent).map_err(|source| RuntimeError::WriteToolManifest {
        path: manifest_path.display().to_string(),
        source,
    })?;
    fs::write(&manifest_path, manifest_yaml).map_err(|source| RuntimeError::WriteToolManifest {
        path: manifest_path.display().to_string(),
        source,
    })
}

/// Write each native tool's binary to `<workdir>/tools/<name>/<name>`, executable.
///
/// Every image is classified against this host before the first one is written. A batch holding
/// one unrunnable binary installs none of them: a refusal that had already written two of three
/// tools would leave a workdir that is neither the state before staging nor the state after it.
fn install_native_binaries(
    workdir: &Path,
    native_binaries: Vec<(String, Vec<u8>)>,
) -> Result<(), RuntimeError> {
    let host_platform = current_platform();
    for (name, bytes) in &native_binaries {
        if let NativeBinaryVerdict::Mismatch { binary_platform } =
            native_binary_verdict(bytes, host_platform)
        {
            return Err(RuntimeError::NativeBinaryPlatformMismatch {
                name: name.clone(),
                binary_platform: binary_platform.to_string(),
                host_platform: host_platform.to_string(),
            });
        }
    }

    for (name, bytes) in native_binaries {
        let binary_path = workdir.join("tools").join(&name).join(&name);
        let Some(parent) = binary_path.parent() else {
            return Err(RuntimeError::Runtime(format!(
                "failed to derive parent for native binary path {}",
                binary_path.display()
            )));
        };
        fs::create_dir_all(parent).map_err(|source| RuntimeError::WriteToolManifest {
            path: binary_path.display().to_string(),
            source,
        })?;
        fs::write(&binary_path, &bytes).map_err(|source| RuntimeError::WriteToolManifest {
            path: binary_path.display().to_string(),
            source,
        })?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = fs::metadata(&binary_path)
                .map_err(|source| RuntimeError::WriteToolManifest {
                    path: binary_path.display().to_string(),
                    source,
                })?
                .permissions();
            perms.set_mode(0o755);
            fs::set_permissions(&binary_path, perms).map_err(|source| {
                RuntimeError::WriteToolManifest {
                    path: binary_path.display().to_string(),
                    source,
                }
            })?;
        }
    }
    Ok(())
}

/// Resolve and read a local-source skill's `skill.md` bytes.
///
/// `source` may be a relative or absolute path. Relative paths resolve against `manifest_dir`
/// (the directory containing `murmur.yaml`). The resolved path may be:
///   - a file (assumed to be `skill.md` itself), read directly, or
///   - a directory, in which case `skill.md` is located case-insensitively within it.
///
/// Errors before the workdir is created so that failures exit non-zero with no side effects.
fn load_local_skill_md(manifest_dir: &Path, source: &str) -> Result<Vec<u8>, RuntimeError> {
    let raw = Path::new(source);
    let path = if raw.is_absolute() {
        raw.to_path_buf()
    } else {
        manifest_dir.join(raw)
    };

    if !path.exists() {
        return Err(RuntimeError::SkillSourceNotFound {
            path: path.display().to_string(),
        });
    }

    let skill_md_path = if path.is_dir() {
        find_skill_md_in_dir(&path)?.ok_or_else(|| RuntimeError::SkillSourceMissingSkillMd {
            path: path.display().to_string(),
        })?
    } else {
        path.clone()
    };

    fs::read(&skill_md_path).map_err(|source| RuntimeError::SkillSourceRead {
        path: skill_md_path.display().to_string(),
        source,
    })
}

/// Locate `skill.md` in a directory, matching the filename case-insensitively. First match wins.
fn find_skill_md_in_dir(dir: &Path) -> Result<Option<std::path::PathBuf>, RuntimeError> {
    let entries = fs::read_dir(dir).map_err(|source| RuntimeError::SkillSourceRead {
        path: dir.display().to_string(),
        source,
    })?;
    for entry in entries {
        let entry = entry.map_err(|source| RuntimeError::SkillSourceRead {
            path: dir.display().to_string(),
            source,
        })?;
        if entry.file_name().to_string_lossy().to_lowercase() == "skill.md" {
            return Ok(Some(entry.path()));
        }
    }
    Ok(None)
}

fn install_skill_files(
    workdir: &Path,
    skill_files: Vec<(String, Vec<u8>)>,
) -> Result<(), RuntimeError> {
    for (name, bytes) in skill_files {
        let skill_path = workdir.join("tools").join(&name).join("skill.md");
        let Some(parent) = skill_path.parent() else {
            return Err(RuntimeError::Runtime(format!(
                "failed to derive parent for skill.md path {}",
                skill_path.display()
            )));
        };
        fs::create_dir_all(parent).map_err(|source| RuntimeError::WriteToolManifest {
            path: skill_path.display().to_string(),
            source,
        })?;
        fs::write(&skill_path, &bytes).map_err(|source| RuntimeError::WriteToolManifest {
            path: skill_path.display().to_string(),
            source,
        })?;
    }
    Ok(())
}

/// Refuses a persistent capsule that declares `exports.peer_files` without a short enough
/// `max_ttl`.
///
/// The rule keys on `lifecycle.after_task`, which is the manifest's ephemerality axis. `exit` —
/// the default — is ephemeral: the capsule dies with the task and teardown destroys the minting
/// key, so every outstanding handle stops verifying at once and the declared lifetime can never
/// be the real bound. `sleep` is the operator's opt-out: the capsule stays alive, its instance
/// key stays alive, and a handle sitting in persisted A2A message history stays redeemable — so
/// there the declared lifetime *is* the bound, and it must be declared and capped.
fn check_persistent_handle_ttl(
    peer_files: Option<&murmur_artifact::PeerFilesExport>,
    lifecycle: &LifecycleConfig,
) -> Result<(), RuntimeError> {
    let Some(export) = peer_files else {
        return Ok(());
    };
    if lifecycle.after_task != murmur_artifact::AfterTask::Sleep {
        return Ok(());
    }
    let ceiling = murmur_artifact::PERSISTENT_PEER_HANDLE_TTL_CEILING_SECS;
    match export.max_ttl_secs {
        Some(declared) if declared <= ceiling => Ok(()),
        declared => Err(RuntimeError::PersistentCapsuleNeedsHandleTtl {
            declared_secs: declared,
            ceiling_secs: ceiling,
        }),
    }
}

/// Writes the synthetic tool manifests for the two peer-handoff tools, each only when its own
/// grant is declared.
fn write_peer_handoff_tool_manifests(
    workdir: &Path,
    can_mint: bool,
    can_fetch: bool,
) -> Result<(), RuntimeError> {
    if can_mint {
        write_runtime_provided_tool_manifest(workdir, SHARE_FILE_TOOL, SHARE_FILE_TOOL_MANIFEST)?;
    }
    if can_fetch {
        write_runtime_provided_tool_manifest(
            workdir,
            FETCH_PEER_FILE_TOOL,
            FETCH_PEER_FILE_TOOL_MANIFEST,
        )?;
    }
    Ok(())
}

/// Tool the minting side gains from `exports.peer_files`.
pub(crate) const SHARE_FILE_TOOL: &str = "share-file";

/// Tool the ingesting side gains from `capabilities.peer_fetch`.
pub(crate) const FETCH_PEER_FILE_TOOL: &str = "fetch-peer-file";

/// `share-file`'s manifest. The description tells the model the two things it cannot work out
/// from the schema: that the returned handle is what goes into the message, and that the path is
/// relative to the declared export root rather than to the workdir.
const SHARE_FILE_TOOL_MANIFEST: &str = concat!(
    "name: share-file\n",
    "version: 0.0.0\n",
    "runtime: tool\n",
    "implementation: native\n",
    "description: \"Mint an opaque handle a named peer can use to fetch one file from this ",
    "capsule's declared peer export. `path` is relative to exports.peer_files.root; `peer` is ",
    "the peer's address. Returns a handle to put in a message to that peer — it names no ",
    "filesystem path and is redeemable only by that peer.\"\n",
    "input_schema: '",
    r#"{"type":"object","properties":{"path":{"type":"string"},"peer":{"type":"string"},"ttl":{"type":"string"}},"required":["path","peer"]}"#,
    "'\n",
);

/// `fetch-peer-file`'s manifest. It states plainly that the bytes arrive as a file, because a
/// model that expects them inline will otherwise ask for them again.
const FETCH_PEER_FILE_TOOL_MANIFEST: &str = concat!(
    "name: fetch-peer-file\n",
    "version: 0.0.0\n",
    "runtime: tool\n",
    "implementation: native\n",
    "description: \"Redeem a handle a peer sent and store the file it names in this capsule's ",
    "workdir. Returns the stored path, size and SHA-256 — never the file's contents. Read the ",
    "stored path if you need what is in it.\"\n",
    "input_schema: '",
    r#"{"type":"object","properties":{"peer":{"type":"string"},"handle":{"type":"string"}},"required":["peer","handle"]}"#,
    "'\n",
);

/// Writes the delegation tool's synthetic manifest, only for a capsule that declares at least one
/// name in `capabilities.spawn.allow`.
///
/// A capsule that declares none gets no file, so `delegate-task` is absent from its tool inventory
/// and from `session_start`'s `tools_declared` — the grant governs the tool's existence rather
/// than its success.
fn write_delegate_task_tool_manifest(
    workdir: &Path,
    spawn_allow: &[String],
) -> Result<(), RuntimeError> {
    if spawn_allow.is_empty() {
        return Ok(());
    }
    write_runtime_provided_tool_manifest(
        workdir,
        DELEGATE_TASK_TOOL,
        &delegate_task_tool_manifest(spawn_allow),
    )
}

/// Tool a capsule gains from `capabilities.spawn.allow`.
pub(crate) const DELEGATE_TASK_TOOL: &str = "delegate-task";

/// `delegate-task`'s manifest, with the granted capsule names built into its schema.
///
/// The description tells the model the three things the schema cannot: that the call does not
/// return until the sub-capsule has finished, that `version` is exact because there is no `latest`
/// anywhere in this system, and that the task text is the whole of what the sub-capsule is told.
fn delegate_task_tool_manifest(spawn_allow: &[String]) -> String {
    let allowed = serde_json::to_string(spawn_allow).unwrap_or_else(|_| "[]".to_string());
    let schema = format!(
        r#"{{"type":"object","properties":{{"capsule":{{"type":"string","enum":{allowed}}},"version":{{"type":"string"}},"task":{{"type":"string"}}}},"required":["capsule","version","task"]}}"#
    );
    format!(
        "name: {DELEGATE_TASK_TOOL}\n\
         version: 0.0.0\n\
         runtime: tool\n\
         implementation: native\n\
         description: \"Hand one task to one sub-capsule and wait for its answer. `capsule` must \
         be one of the names this capsule is allowed to delegate to; `version` is that capsule's \
         exact version, because there is no latest or stable alias; `task` is the whole of what \
         the sub-capsule is told, so state the objective in full. The sub-capsule runs as its own \
         process with its own workdir and this call does not return until it has finished. \
         Returns its answer text.\"\n\
         input_schema: '{schema}'\n",
    )
}

/// Writes the plan tool's synthetic manifest, only for a capsule that declares
/// `capabilities.plan.submit: true`.
///
/// A capsule that declares nothing gets no file, so `submit-plan` is absent from its tool
/// inventory and from `session_start`'s `tools_declared` — the grant governs the tool's existence
/// rather than its success, exactly as [`write_delegate_task_tool_manifest`] does.
fn write_submit_plan_tool_manifest(workdir: &Path, plan_submit: bool) -> Result<(), RuntimeError> {
    if !plan_submit {
        return Ok(());
    }
    write_runtime_provided_tool_manifest(workdir, SUBMIT_PLAN_TOOL, SUBMIT_PLAN_TOOL_MANIFEST)
}

/// What a running plan asks of the session that was handed it. The scheduler thread that sent
/// one is parked on its `oneshot` until this session replies.
enum PlanRequest {
    /// A step about to be dispatched, reaching the session's decision point first. The answer is
    /// the refusal text, or `None` to let the step run.
    Gate(GatedStepCall, tokio::sync::oneshot::Sender<Option<String>>),
    /// A `tool` step's call: the tool's name, the step's input, and where the answer goes.
    Invoke(
        String,
        murmur::tool::run::ToolInput,
        tokio::sync::oneshot::Sender<Result<murmur::tool::run::ToolResult, String>>,
    ),
}

/// An owned [`crate::plan::PlannedCall`], because the gate's answer comes from another thread.
enum GatedStepCall {
    Tool {
        name: String,
        input_json: String,
    },
    Shell {
        binary: String,
        command: String,
        argv: Vec<String>,
    },
}

impl GatedStepCall {
    fn from_planned(call: &crate::plan::PlannedCall<'_>) -> Self {
        match call {
            crate::plan::PlannedCall::Tool { name, input_json } => Self::Tool {
                name: (*name).to_string(),
                input_json: (*input_json).to_string(),
            },
            crate::plan::PlannedCall::Shell {
                binary,
                command,
                argv,
            } => Self::Shell {
                binary: (*binary).to_string(),
                command: (*command).to_string(),
                argv: argv.to_vec(),
            },
        }
    }

    /// The same [`ResolvedCall`] the decision point is shown for the equivalent call made
    /// directly, so a plan step and an agent turn are judged on the same values.
    ///
    /// The shell arm is resolved here rather than through [`resolve_shell_call`] because the two
    /// forms differ: a shell *tool* call carries a `command` string the runtime always hands to
    /// the interpreter as `-c`, while a plan step carries a whole argv the scheduler execs
    /// directly. `script` is therefore set only for the `-c` form that actually reaches a shell —
    /// which is exactly the distinction `ProtectedPaths::check_shell` draws between a body whose
    /// redirections are live and an argv where `>` is a literal argument.
    fn resolve(&self, workdir: &Path) -> ResolvedCall {
        match self {
            Self::Tool { name, input_json } => ResolvedCall::Tool {
                tool_name: name.clone(),
                input_bytes: input_json.len() as u64,
                input: input_json.clone(),
            },
            Self::Shell {
                binary,
                command,
                argv,
            } => {
                let script = (is_shell_interpreter(binary)
                    && argv.first().is_some_and(|first| first == "-c"))
                .then(|| argv.get(1).cloned().unwrap_or_default());
                let recipe = match script {
                    Some(_) => None,
                    None => crate::recipes::resolve_recipe(workdir, binary, argv),
                };
                ResolvedCall::Shell {
                    binary: crate::sandbox::resolve_invoked_binary_path(binary),
                    command: command.clone(),
                    argv: argv.clone(),
                    script,
                    recipe,
                }
            }
        }
    }
}

/// Tool a capsule gains from `capabilities.plan.submit`.
pub(crate) const SUBMIT_PLAN_TOOL: &str = "submit-plan";

/// What a plan step is refused with when the session's decision point cannot be reached at all.
///
/// Fail closed: the alternative is a step running because the thing that would have refused it
/// went away.
const PLAN_GATE_UNREACHABLE: &str =
    "Refused: the session stopped answering policy checks, so this step was not dispatched.";

/// `submit-plan`'s manifest. Its schema names one argument and says nothing about a step, because
/// the plan format is documented rather than schema-checked here; the description carries the
/// three things the schema cannot — that the call blocks until the whole plan has settled, which
/// independent steps overlap and which do not, and how a later step reads an earlier one's
/// output.
const SUBMIT_PLAN_TOOL_MANIFEST: &str = concat!(
    "name: submit-plan\n",
    "version: 0.0.0\n",
    "runtime: tool\n",
    "implementation: native\n",
    "description: \"Hand one plan to the runtime and get back every step's result. `plan` is an ",
    "object with an `id` and a `steps` array; each step has an `id` and exactly one of `tool`, ",
    "`shell` or `capsule`, plus optional `input`, `depends_on`, `if`, `on_error` and `retries`. ",
    "The call does not return until every step has finished. Independent `shell` and `capsule` ",
    "steps run at the same time; `tool` steps are dispatched one at a time even when nothing ",
    "orders them. A step's output is reachable from a later step as ",
    "$<step id>.output and its status as $<step id>.status, anywhere in that step's input.\"\n",
    "input_schema: '",
    r#"{"type":"object","properties":{"plan":{"type":"object"}},"required":["plan"]}"#,
    "'\n",
);

fn write_shell_tool_manifests(workdir: &Path, shell_allow: &[String]) -> Result<(), RuntimeError> {
    for binary in shell_allow {
        let manifest_path = workdir
            .join("tools")
            .join(binary)
            .join(PACKED_MANIFEST_ENTRY);

        if manifest_path.exists() {
            continue;
        }

        let Some(parent) = manifest_path.parent() else {
            return Err(RuntimeError::Runtime(format!(
                "failed to derive parent for shell manifest path {}",
                manifest_path.display()
            )));
        };

        fs::create_dir_all(parent).map_err(|source| RuntimeError::WriteToolManifest {
            path: manifest_path.display().to_string(),
            source,
        })?;

        fs::write(&manifest_path, shell_tool_manifest_yaml(binary)).map_err(|source| {
            RuntimeError::WriteToolManifest {
                path: manifest_path.display().to_string(),
                source,
            }
        })?;
    }

    Ok(())
}

/// Execute a native artifact binary.
///
/// The binary receives the serialized ToolInput JSON on stdin and must write a valid
/// ToolResult JSON object to stdout. The binary's working directory is the capsule workdir.
fn dispatch_native_tool(
    name: &str,
    input: murmur::tool::run::ToolInput,
    binary_path: &Path,
    accessible_workdir: &Path,
    session_workdir: &Path,
    policy: &CapabilityPolicy,
    enforcement: &sandbox::ShellEnforcement,
) -> Result<murmur::tool::run::ToolResult, String> {
    use std::{
        io::Write,
        process::{Command, Stdio},
    };

    let input_json = serde_json::to_string(&serde_json::json!({
        "data": input.data,
        "log_path": input.log_path,
    }))
    .map_err(|e| format!("failed to serialize input for native tool '{name}': {e}"))?;

    enforcement.check_workdir_budget()?;

    let env = build_shell_env(policy, &[], session_workdir)?;

    // Bound to a local before spawning (rather than chained straight into `.spawn()`) so a
    // `pre_exec` step can be attached to it, mirroring `execute_shell`'s shape.
    let mut command = Command::new(binary_path);
    command
        .current_dir(accessible_workdir)
        .env_clear()
        .envs(env)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());

    // This path carries the same hard rlimits and the same cgroup membership as `execute_shell`,
    // but installs no seccomp filter and no Landlock scope. That asymmetry is deliberate and
    // open: a native-implementation artifact is bounded but not confined.
    sandbox::attach_process_limits(&mut command, enforcement);
    // Mark every fd >= 3 close-on-exec in the forked child, so this subprocess inherits only the
    // stdio pipes configured just above and nothing that merely happened to be open in the
    // runtime process. Fds 0/1/2 are deliberately excluded: this function writes the tool's
    // `ToolInput` JSON to the child's stdin and parses its `ToolResult` JSON back off stdout, so
    // stdio inheritance across `execve` is the point, not a leak — see
    // `sandbox::FD_HYGIENE_FIRST_FD` for the full recorded decision.
    //
    // This is the shared helper `execute_shell`'s path also runs (as the first step of
    // `sandbox::linux_enforce::child_install_enforcement`), so the two spawn paths cannot drift
    // apart on this dimension. It takes no policy input — fd hygiene is unconditional — and it
    // deliberately does not bring seccomp/Landlock enforcement with it; kernel sandboxing of
    // native tool subprocesses remains the documented gap it was.
    crate::sandbox::apply_fd_hygiene(&mut command);

    let mut child = command
        .spawn()
        .map_err(|e| format!("failed to spawn native tool '{name}': {e}"))?;

    if let Some(mut stdin) = child.stdin.take() {
        let _ = stdin.write_all(input_json.as_bytes());
        // stdin closes when dropped, signalling EOF to the child
    }

    let output = child
        .wait_with_output()
        .map_err(|e| format!("native tool '{name}' failed to complete: {e}"))?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    if stdout.trim().is_empty() {
        return Ok(murmur::tool::run::ToolResult {
            status: if output.status.success() {
                murmur::tool::run::Status::Passed
            } else {
                murmur::tool::run::Status::Error
            },
            summary: Some(format!(
                "native tool '{}' exited with {}",
                name, output.status
            )),
            data: if stderr.is_empty() {
                None
            } else {
                Some(stderr.to_string())
            },
            data_path: None,
            truncated: false,
            metadata: Vec::new(),
        });
    }

    match serde_json::from_str::<serde_json::Value>(stdout.trim()) {
        Ok(json) => {
            let status = match json.get("status").and_then(|s| s.as_str()) {
                Some("passed") => murmur::tool::run::Status::Passed,
                Some("failed") => murmur::tool::run::Status::Failed,
                _ => murmur::tool::run::Status::Error,
            };
            let summary = json
                .get("summary")
                .and_then(|s| s.as_str())
                .map(|s| s.to_string());
            let data = json
                .get("data")
                .and_then(|d| d.as_str())
                .map(|s| s.to_string())
                .or_else(|| {
                    json.get("data")
                        .filter(|d| !d.is_null())
                        .map(|d| d.to_string())
                });
            Ok(murmur::tool::run::ToolResult {
                status,
                summary,
                data,
                data_path: None,
                truncated: false,
                metadata: Vec::new(),
            })
        }
        Err(_) => Ok(murmur::tool::run::ToolResult {
            status: if output.status.success() {
                murmur::tool::run::Status::Passed
            } else {
                murmur::tool::run::Status::Error
            },
            summary: Some(format!("native tool '{}' completed", name)),
            data: Some(stdout.to_string()),
            data_path: None,
            truncated: false,
            metadata: Vec::new(),
        }),
    }
}

/// What a shell tool call will actually run, resolved from the tool name and its input.
///
/// One value produced by one function, handed to both the policy decision point and the spawn,
/// so what a hook is asked to approve and what `execute_shell` is given cannot drift apart.
pub(crate) struct ResolvedShellCall {
    /// The program that will be invoked, canonicalized against the host `PATH` where that
    /// resolves and the bare name otherwise — the same value the post-call `shell-event`
    /// carries.
    pub binary: String,
    /// The `command` string as the tool received it, untruncated. A display value; `argv` and
    /// `script` are what identify the call.
    pub command: String,
    /// The exact argument list handed to the executable.
    pub argv: Vec<String>,
    /// The `-c` body for the interpreter form, `None` for every other form.
    pub script: Option<String>,
    /// The body of the recipe this call names, read out of `workdir` by
    /// [`crate::recipes::resolve_recipe`], and `None` for every call that names none the
    /// runtime can resolve.
    pub recipe: Option<String>,
}

/// Resolve what a shell tool call will run, or `None` when `name` is not a declared shell
/// binary or its input carries no usable `command`.
///
/// The decision point's view of a call. It performs no capability decision of its own: the
/// `shell_allow` test here is the routing question "is this name a shell tool at all"; the
/// enforcing check is at the top of `execute_shell`.
///
/// `workdir` is the directory the subprocess will run in, and is where a build-tool recipe is
/// read from and confined to.
pub(crate) fn resolve_shell_call(
    name: &str,
    input: &murmur::tool::run::ToolInput,
    workdir: &Path,
    policy: &CapabilityPolicy,
) -> Option<ResolvedShellCall> {
    resolve_shell_call_inner(name, input, workdir, policy).ok()
}

/// [`resolve_shell_call`] keeping the diagnostic, for the dispatch path that reports it to the
/// model. The two must stay one function: an argv computed twice is an argv that can be
/// approved in one form and executed in another.
fn resolve_shell_call_inner(
    name: &str,
    input: &murmur::tool::run::ToolInput,
    workdir: &Path,
    policy: &CapabilityPolicy,
) -> Result<ResolvedShellCall, String> {
    if !policy.shell_allow.iter().any(|allowed| allowed == name) {
        return Err(format!(
            "binary '{name}' is not in capabilities.shell.allow"
        ));
    }
    let command = extract_shell_command(input)?;
    let (argv, script) = if is_shell_interpreter(name) {
        (
            vec!["-c".to_string(), command.clone()],
            Some(command.clone()),
        )
    } else {
        (split_shell_words(&command), None)
    };
    // An interpreter form is never a recipe invocation: what it names is its own `-c` body, and
    // reading a build tool out of that body would be guessing.
    let recipe = match script {
        Some(_) => None,
        None => crate::recipes::resolve_recipe(workdir, name, &argv),
    };
    Ok(ResolvedShellCall {
        binary: crate::sandbox::resolve_invoked_binary_path(name),
        command,
        argv,
        script,
        recipe,
    })
}

/// `detach` is what decides whether a slow command can be demoted. `None` runs it to completion
/// in the foreground — the only shape available to a caller with no task loop to deliver a
/// completion to.
#[allow(clippy::too_many_arguments)]
fn dispatch_shell_tool(
    name: &str,
    input: murmur::tool::run::ToolInput,
    accessible_workdir: &Path,
    session_workdir: &Path,
    env_overrides: &[(String, String)],
    policy: &CapabilityPolicy,
    enforcement: &sandbox::ShellEnforcement,
    detach: Option<DetachPolicy>,
) -> DispatchOutcome {
    let resolved = match resolve_shell_call_inner(name, &input, accessible_workdir, policy) {
        Ok(resolved) => resolved,
        Err(error) => {
            return DispatchOutcome::tool(murmur::tool::run::ToolResult {
                status: murmur::tool::run::Status::Error,
                summary: Some("shell command parsing failed".to_string()),
                data: Some(error),
                data_path: None,
                truncated: false,
                metadata: Vec::new(),
            });
        }
    };
    let ResolvedShellCall {
        command,
        argv,
        script,
        recipe,
        ..
    } = resolved;
    let args: Vec<&str> = argv.iter().map(String::as_str).collect();

    let detach = detach.map(|detach| DetachPolicy {
        command: command.clone(),
        ..detach
    });

    match run_shell(
        name,
        &args,
        env_overrides,
        accessible_workdir,
        session_workdir,
        policy,
        enforcement,
        detach,
    ) {
        Ok(ShellOutcome::Finished(result)) => {
            let shell = ShellDispatchInfo {
                // `name` is the invoked binary (each `capabilities.shell.allow` entry is
                // exposed as its own tool), resolved to a path by `execute_shell`.
                binary: result.binary.clone(),
                command: command.clone(),
                argv: argv.clone(),
                script: script.clone(),
                recipe: recipe.clone(),
                exit_code: result.exit_code,
                stdout: result.stdout.clone(),
                stderr: result.stderr.clone(),
                stdout_bytes: result.stdout.len() as u64,
                stderr_bytes: result.stderr.len() as u64,
                duration_ms: result.duration_ms,
                resource_limit: result.resource_limit_hit.clone(),
            };
            DispatchOutcome {
                result: shell_result_to_tool_result(name, &command, result),
                shell: Some(shell),
                detached: None,
                is_skill: false,
                fatal: None,
            }
        }
        // A demoted command has no exit code, no output and no duration yet, so it fills none of
        // the fields `ShellDispatchInfo` exists to carry — hence `shell: None`, and hence no
        // `HookEvent::Shell`. What it did produce is the handle.
        Ok(ShellOutcome::Detached(info)) => DispatchOutcome {
            result: demotion_tool_result(&info.work_id),
            shell: None,
            detached: Some(info),
            is_skill: false,
            fatal: None,
        },
        Err(error) => DispatchOutcome {
            // The tool result is filled in either way, so the trace records the call that was
            // attempted; `fatal` is what tells the agent turn loop that this particular failure
            // is not one the capsule gets another turn to react to.
            result: murmur::tool::run::ToolResult {
                status: murmur::tool::run::Status::Error,
                summary: Some("shell execution failed".to_string()),
                data: Some(error.to_string()),
                data_path: None,
                truncated: false,
                metadata: Vec::new(),
            },
            shell: None,
            detached: None,
            is_skill: false,
            fatal: error.session_fatal(),
        },
    }
}

fn extract_shell_command(input: &murmur::tool::run::ToolInput) -> Result<String, String> {
    let data = input
        .data
        .as_deref()
        .ok_or_else(|| "shell tool input.data is required".to_string())?;

    let json: serde_json::Value = serde_json::from_str(data)
        .map_err(|error| format!("shell tool input must be valid JSON: {error}"))?;

    let command = json
        .get("command")
        .and_then(serde_json::Value::as_str)
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| "shell tool input must include a non-empty 'command' string".to_string())?;

    Ok(command.to_string())
}

/// The command line a person would type at a shell prompt to run this call.
///
/// An interpreter's `command` is already a whole shell line — it becomes the `-c` body — so it
/// stands alone. Every other allowlisted binary receives the argument list alone, because
/// `shell_tool_manifest_yaml` tells the model to omit the binary name, so the name goes back in
/// front of it here.
///
/// `name` is the declared short name, the `capabilities.shell.allow` entry, not
/// `ShellResult::binary`: that field is the resolved absolute path and would render
/// `$ /usr/bin/ls .`.
fn shell_command_line(name: &str, command: &str) -> String {
    if is_shell_interpreter(name) {
        format!("$ {command}")
    } else {
        format!("$ {name} {command}")
    }
}

fn shell_result_to_tool_result(
    name: &str,
    command: &str,
    result: ShellResult,
) -> murmur::tool::run::ToolResult {
    let mut data = format!(
        "{}\nExit code: {}\nStdout:\n{}\nStderr:\n{}",
        shell_command_line(name, command),
        result.exit_code,
        result.stdout,
        result.stderr
    );

    let mut metadata = Vec::new();
    if result.truncated {
        if let Some(path) = result.full_output_path.as_ref() {
            data.push_str(&format!(
                "\n\nOutput truncated. Full output written to {path}"
            ));
            metadata.push(("full_output_path".to_string(), path.clone()));
        } else {
            data.push_str("\n\nOutput truncated.");
        }
    }

    murmur::tool::run::ToolResult {
        status: murmur::tool::run::Status::Passed,
        summary: Some(format!(
            "Shell command exited with code {}",
            result.exit_code
        )),
        data: Some(data),
        data_path: None,
        truncated: result.truncated,
        metadata,
    }
}

/// The context id one `task.md` task runs under: the operator's `--context` value when they gave
/// one, or a fresh id.
///
/// A supplied id is what makes a record reachable outside A2A: it is the same id the A2A path
/// gets from its client, so the two produce the same record path for the same conversation.
fn task_context_id(supplied: Option<&str>) -> String {
    supplied
        .map(str::to_string)
        .unwrap_or_else(|| format!("ctx_{}", uuid::Uuid::now_v7().simple()))
}

/// `~/.murmur/conversations/<record>` for this launch, or `None` when it keeps no record.
///
/// Three ways to have none, and all three are ordinary: `context.record: off`, a
/// `process`-transport capsule (whose CLI owns its own conversation and whose loop never builds a
/// message list), and a host whose home directory cannot be resolved. The last is reported and
/// survived rather than refused — the record is on by default for every `http` capsule, so a host
/// with no usable `HOME` must not become one where nothing launches.
fn resolve_conversation_root(
    context: Option<&ContextConfig>,
    capsule_name: &str,
    inference: &murmur_artifact::InferenceConfig,
    workdir: &Path,
) -> Option<PathBuf> {
    if inference.transport == "process" {
        return None;
    }
    let record = crate::conversation::resolve_record_name(context, capsule_name)?;
    match crate::conversation::record_root(&record) {
        Ok(root) => Some(root),
        Err(reason) => {
            let message = format!(
                "[conversation] the record for '{record}' could not be located ({reason}); \
                 this session runs unrecorded"
            );
            eprintln!("[capsule-runtime] {message}");
            agent::append_bootstrap_log(workdir, &message);
            None
        }
    }
}

/// Enforce both `retain:` blocks and record every deletion in this session's own trace.
///
/// Called once per launch, immediately after `session_start`. Nothing here can fail a launch: a
/// store that cannot be read, a directory that cannot be removed and a trace line that cannot be
/// written are each survived, on the same terms as an unresolvable `HOME` in
/// [`resolve_conversation_root`] — a capsule whose retention cannot run must still do its work.
///
/// Session pruning is computed from `workdir.parent()`, the directory holding every sibling
/// session, and never considers an id at or after this session's own. Record pruning needs the
/// resolved conversation root, the capsule name — records this capsule does not own are never
/// touched — and the launch's context id, which is never removed and is the one record
/// `max_messages` truncates.
#[allow(clippy::too_many_arguments)]
async fn apply_retention(
    trace: &mut TraceWriter,
    workdir: &Path,
    session_id: &str,
    trace_retain: Option<&murmur_artifact::TraceRetainConfig>,
    context_retain: Option<&murmur_artifact::ContextRetainConfig>,
    conversation_root: Option<&Path>,
    capsule_name: &str,
    context_id: Option<&str>,
) {
    use crate::trace::{
        RETENTION_REASON_MAX_MESSAGES, RETENTION_STORE_RECORDS, RETENTION_STORE_SESSIONS,
    };

    let now_ms = crate::retention::now_ms();

    if let (Some(policy), Some(sessions_root)) = (trace_retain, workdir.parent()) {
        let pruned = crate::retention::prune_sessions(sessions_root, session_id, policy, now_ms);
        for reason in [
            crate::trace::RETENTION_REASON_MAX_SESSIONS,
            crate::trace::RETENTION_REASON_MAX_AGE,
        ] {
            let targets: Vec<String> = pruned
                .iter()
                .filter(|session| session.reason == reason)
                .map(|session| session.name.clone())
                .collect();
            if targets.is_empty() {
                continue;
            }
            let _ = trace
                .write_retention(RETENTION_STORE_SESSIONS, reason, targets, None)
                .await;
        }
    }

    let (Some(policy), Some(root)) = (context_retain, conversation_root) else {
        return;
    };

    let pruned = crate::retention::prune_records(root, capsule_name, context_id, policy, now_ms);
    if !pruned.is_empty() {
        let targets: Vec<String> = pruned
            .iter()
            .map(|record| record.context_id.clone())
            .collect();
        let _ = trace
            .write_retention(
                RETENTION_STORE_RECORDS,
                crate::trace::RETENTION_REASON_MAX_AGE,
                targets,
                None,
            )
            .await;
    }

    // `max_messages` truncates the one record this launch opens, at the point it is opened: that
    // is where the growth is, it is O(one record) rather than O(every conversation), and it never
    // rewrites a conversation this capsule is not touching. A launch that mints a context per
    // task opens no record here, so it has nothing to truncate.
    let (Some(keep), Some(context_id)) = (policy.max_messages, context_id) else {
        return;
    };
    let path = crate::conversation::record_file(root, context_id);
    match crate::conversation::read_header(&path) {
        // A header naming another capsule is that capsule's record, whatever context id this
        // launch was handed. An unowned record on this launch's own context is one this launch
        // is about to append to and adopt, so the truncation adopts it in the same rewrite.
        Some(header) if header.capsule != capsule_name => return,
        _ => {}
    }
    match crate::retention::truncate_record(&path, keep, capsule_name) {
        Ok(outcome) if outcome.dropped > 0 => {
            let _ = trace
                .write_retention(
                    RETENTION_STORE_RECORDS,
                    RETENTION_REASON_MAX_MESSAGES,
                    vec![context_id.to_string()],
                    Some(outcome.dropped),
                )
                .await;
        }
        Ok(_) => {}
        Err(reason) => {
            let message = format!(
                "[retention] {} could not be truncated ({reason}); this record keeps growing",
                path.display()
            );
            eprintln!("[capsule-runtime] {message}");
            agent::append_bootstrap_log(workdir, &message);
        }
    }
}

fn resolve_context_window(context: Option<&ContextConfig>) -> u32 {
    context.and_then(|c| c.max_tokens).unwrap_or(0)
}

fn validate_capability_policy(policy: &CapabilityPolicy) -> Result<(), RuntimeError> {
    parse_network_allow_rules(&policy.network_allow)?;
    if let Some(scope) = policy.filesystem_scope.as_deref() {
        validate_filesystem_scope(scope)?;
    }

    Ok(())
}

fn enforce_allowlist<T, F>(
    allowlisted_tools: &HashSet<String>,
    name: &str,
    dispatch: F,
) -> Result<T, String>
where
    F: FnOnce() -> Result<T, String>,
{
    if !allowlisted_tools.contains(name) {
        return Err(format!(
            "tool '{name}' is not declared in manifest allowlist"
        ));
    }

    dispatch()
}

/// What ended the task loop's bounded wait: a task arriving (or its channel closing) or a report
/// on work this runtime started.
enum Woke {
    Task(Option<IncomingTask>),
    Report(DetachedReport),
    /// The session received `SIGTERM`.
    Terminating,
}

/// Say that a task was cancelled while it was still `submitted`, which is all such a task gets: no
/// `task_start`, no `on-task-start`, no request to the provider, and no `task_end`, because it
/// never ran. The `PHASE_QUEUED` record is its ending.
///
/// The final status event is the only thing that closes a `message/stream` connection on this
/// task: it never reaches an agent loop, so nothing else would.
async fn record_canceled_before_start(
    task: &IncomingTask,
    trace: &mut TraceWriter,
    detached: &Arc<DetachedRegistry>,
    live_delegations: &crate::cancel::LiveDelegations,
    sse: &Option<(SseBroadcast, Arc<Mutex<SseEventBuffer>>)>,
    event_id: &mut u64,
) {
    let residue = crate::cancel::Residue::snapshot(Some(detached), live_delegations);
    let _ = trace
        .write_task_canceled(
            &task.task_id,
            None,
            crate::cancel::PHASE_QUEUED,
            residue.detached_work_ids(),
            residue.delegation_ids(),
        )
        .await;
    let _ = trace.flush().await;
    emit_sse(
        sse,
        event_id,
        "status",
        &crate::streaming::TaskStatusUpdateEvent {
            id: task.task_id.clone(),
            context_id: Some(task.context_id.clone()),
            status: crate::streaming::StreamStatus {
                state: "canceled".into(),
                message: "task canceled before it started".into(),
                response: None,
            },
            r#final: true,
        },
    )
    .await;
}

/// Empty every lane on the way out of a terminating session, starting nothing.
///
/// A task the `SIGTERM` handler cancelled is recorded as cancelled before it started, exactly as
/// the activation step records one. A task the door accepted after the handler ran is not
/// `Canceled` and is dropped without a record.
async fn close_lanes_on_termination(
    lanes: &mut LaneQueue,
    task_registry: &Arc<Mutex<TaskRegistry>>,
    trace: &mut TraceWriter,
    detached: &Arc<DetachedRegistry>,
    live_delegations: &crate::cancel::LiveDelegations,
    sse: &Option<(SseBroadcast, Arc<Mutex<SseEventBuffer>>)>,
    event_id: &mut u64,
) {
    // `None` for the active lane is safe only because nothing taken here is started.
    while let Some((_, task)) = lanes.next(None) {
        if task_registry.lock().unwrap().is_canceled(&task.task_id) {
            record_canceled_before_start(&task, trace, detached, live_delegations, sse, event_id)
                .await;
        }
    }
}

/// Turn a report about work this runtime started into a queued `completion`-origin task, and
/// record whatever join the report needs in the trace.
///
/// Two kinds of report, one path: a demoted shell command finishing, and a prior session's
/// demoted commands going unaccounted. Both are [`TaskOrigin::Completion`] and land in the `bg`
/// lane by [`TaskLane::for_origin`]'s rule; neither declares a lane. A delegation's outcome is
/// not one of these — it arrives at the door as an ordinary inbound completion, posted by the
/// child or by the watcher behind it.
///
/// `can_accept` is not consulted, on either arm. A completion is work the capsule already
/// admitted when it admitted the task that started the command, and a loss report is the only
/// account anything will ever give of that work; refusing either would drop the result this path
/// exists to deliver. The `enqueue` is not optional either: `start_task` asserts a positive
/// pending count, so a task pushed onto the queue without one would trip that assertion. An
/// outstanding report therefore counts against `queue_depth`, and a capsule with detached work in
/// flight has less room for new inbound requests. A loss report costs exactly one pending item
/// however many work ids it names, and the drain loop clears it on its first pass.
async fn enqueue_detached_report(
    report: DetachedReport,
    task_registry: &Arc<Mutex<TaskRegistry>>,
    lanes: &mut LaneQueue,
    trace: &mut TraceWriter,
) {
    let task = match report {
        DetachedReport::Completed(completion) => {
            let task = IncomingTask {
                task_id: format!("tsk_{}", uuid::Uuid::now_v7().simple()),
                context_id: completion.context_id.clone(),
                message_id: format!("msg_{}", uuid::Uuid::now_v7().simple()),
                message_text: completion.message_text(),
                provenance: completion.provenance,
                // Nothing propagated a trace context to a background command: the turn that
                // started it is over, and inventing a parent span would attribute the completion
                // to it.
                traceparent: None,
                source: crate::a2a::SOURCE_DETACHED_SHELL,
                // A demoted shell command reports on a work id, not on a delegation: no
                // sub-capsule was launched, so there is no delegation for the trace to join this
                // task to.
                delegation_id: None,
            };
            let _ = trace
                .write_shell_completed(
                    &completion.work_id,
                    &completion.binary,
                    &completion.command,
                    completion.exit_code,
                    completion.duration_ms,
                    &completion.output_path,
                    completion.output_bytes,
                    completion.resource_limit.clone(),
                    completion.status(),
                    &task.task_id,
                )
                .await;
            task
        }
        // Nothing is written to this session's trace beyond the `task_start` the loop writes when
        // it starts the task: the `shell_lost` markers are already in the trace of the session
        // that started the work, which is the file that has to hold them for the marker to clear.
        DetachedReport::Lost(report) => IncomingTask {
            task_id: report.task_id.clone(),
            context_id: report.context_id.clone(),
            message_id: format!("msg_{}", uuid::Uuid::now_v7().simple()),
            message_text: report.message_text(),
            provenance: report.provenance,
            traceparent: None,
            source: crate::a2a::SOURCE_DETACHED_LOST,
            delegation_id: None,
        },
    };

    task_registry
        .lock()
        .unwrap()
        .enqueue(&task.task_id, &task.context_id);
    lanes.push(task);
}

fn generate_session_id() -> String {
    format!("ses_{}", uuid::Uuid::now_v7().simple())
}

fn resolve_lifecycle(
    base: Option<LifecycleConfig>,
    override_: Option<&murmur_artifact::LifecycleOverride>,
) -> LifecycleConfig {
    let mut config = base.unwrap_or_default();
    if let Some(ov) = override_ {
        if let Some(ta) = &ov.task_acceptance {
            config.task_acceptance = ta.clone();
        }
        if let Some(at) = &ov.after_task {
            config.after_task = at.clone();
        }
    }
    config
}

#[cfg(test)]
mod tests {
    use murmur_artifact::LockedArtifact;

    // ── delegate-task's synthetic manifest ───────────────────────────────────

    /// The tool's contract, pinned: the model reads this manifest, and the `enum` is the whole of
    /// what stops it naming a capsule the operator never granted.
    #[test]
    fn the_delegation_manifest_carries_the_granted_names_and_nothing_else() {
        let manifest =
            super::delegate_task_tool_manifest(&["worker".to_string(), "reviewer".to_string()]);
        let parsed: serde_yaml::Value =
            serde_yaml::from_str(&manifest).expect("the generated manifest is YAML");
        assert_eq!(parsed["name"].as_str(), Some("delegate-task"));
        assert_eq!(parsed["runtime"].as_str(), Some("tool"));
        assert_eq!(parsed["implementation"].as_str(), Some("native"));

        let schema: serde_json::Value =
            serde_json::from_str(parsed["input_schema"].as_str().expect("a schema string"))
                .expect("the schema is JSON");
        assert_eq!(
            schema["required"],
            serde_json::json!(["capsule", "version", "task"])
        );
        assert_eq!(
            schema["properties"]["capsule"]["enum"],
            serde_json::json!(["worker", "reviewer"]),
            "the enum is the capsule's own spawn.allow, in declaration order"
        );
        // No URL, no credential, no workdir, no capability: the runtime composes all four.
        for absent in ["roost", "url", "credential", "approval", "workdir"] {
            assert!(
                !schema["properties"]
                    .as_object()
                    .expect("an object")
                    .contains_key(absent),
                "'{absent}' must not be an argument the agent supplies"
            );
        }
    }

    /// A capsule that declares no `capabilities.spawn.allow` gets no file, so the tool is absent
    /// from its inventory rather than present and failing.
    #[test]
    fn an_ungranted_capsule_is_written_no_delegation_tool() {
        let dir = tempfile::tempdir().unwrap();
        super::write_delegate_task_tool_manifest(dir.path(), &[]).unwrap();
        assert!(!dir.path().join("tools").join("delegate-task").exists());

        super::write_delegate_task_tool_manifest(dir.path(), &["worker".to_string()]).unwrap();
        assert!(dir
            .path()
            .join("tools")
            .join("delegate-task")
            .join(PACKED_MANIFEST_ENTRY)
            .exists());
    }

    // ── submit-plan's synthetic manifest ─────────────────────────────────────

    /// The plan tool's contract, pinned: one object argument, and a description carrying the
    /// three things the schema cannot say.
    #[test]
    fn the_plan_manifest_declares_one_object_argument() {
        let parsed: serde_yaml::Value =
            serde_yaml::from_str(super::SUBMIT_PLAN_TOOL_MANIFEST).expect("the manifest is YAML");
        assert_eq!(parsed["name"].as_str(), Some("submit-plan"));
        assert_eq!(parsed["version"].as_str(), Some("0.0.0"));
        assert_eq!(parsed["runtime"].as_str(), Some("tool"));
        assert_eq!(parsed["implementation"].as_str(), Some("native"));

        let schema: serde_json::Value =
            serde_json::from_str(parsed["input_schema"].as_str().expect("a schema string"))
                .expect("the schema is JSON");
        assert_eq!(schema["required"], serde_json::json!(["plan"]));
        assert_eq!(schema["properties"]["plan"]["type"], "object");

        let description = parsed["description"].as_str().expect("a description");
        assert!(description.contains("does not return until every step has finished"));
        assert!(description.contains("at the same time"));
        assert!(description.contains("$<step id>.output"));
    }

    /// A capsule that declares no `capabilities.plan.submit` gets no file, so the tool is absent
    /// from its inventory rather than present and failing.
    #[test]
    fn an_ungranted_capsule_is_written_no_plan_tool() {
        let dir = tempfile::tempdir().unwrap();
        super::write_submit_plan_tool_manifest(dir.path(), false).unwrap();
        assert!(!dir.path().join("tools").join("submit-plan").exists());

        super::write_submit_plan_tool_manifest(dir.path(), true).unwrap();
        assert!(dir
            .path()
            .join("tools")
            .join("submit-plan")
            .join(PACKED_MANIFEST_ENTRY)
            .exists());
    }

    // ── reserved tool names ──────────────────────────────────────────────────

    /// The list is what every runtime-provided writer is routed through, so a further synthetic
    /// tool added without extending it has to fail here rather than ship shadowed by an artifact
    /// of the same name. The arity assertion is the part that catches that.
    #[test]
    fn the_reserved_set_covers_every_runtime_provided_tool() {
        assert_eq!(
            super::RESERVED_TOOL_NAMES.len(),
            4,
            "a new runtime-provided tool must be added to RESERVED_TOOL_NAMES, and this arity \
             raised, before its writer can succeed"
        );
        for name in [
            super::SHARE_FILE_TOOL,
            super::FETCH_PEER_FILE_TOOL,
            super::DELEGATE_TASK_TOOL,
            super::SUBMIT_PLAN_TOOL,
        ] {
            assert!(
                super::is_reserved_tool_name(name),
                "'{name}' is answered by the runtime and must be reserved"
            );
        }
        // Operator-chosen shell binary names are deliberately not members.
        assert!(!super::is_reserved_tool_name("bash"));
        // Case-sensitive, because artifact names are.
        assert!(!super::is_reserved_tool_name("Delegate-Task"));
    }

    /// The funnel guard on the artifact side. `manage.pull()` writes through this function with no
    /// staging check ahead of it, so a capsule that pulls `delegate-task` mid-session must be
    /// refused here — and must leave the synthetic manifest untouched.
    #[test]
    fn an_artifact_manifest_write_refuses_a_reserved_name() {
        let dir = tempfile::tempdir().unwrap();
        super::write_delegate_task_tool_manifest(dir.path(), &["worker".to_string()]).unwrap();
        let synthetic = dir
            .path()
            .join("tools")
            .join(super::DELEGATE_TASK_TOOL)
            .join(PACKED_MANIFEST_ENTRY);
        let before = std::fs::read_to_string(&synthetic).unwrap();

        for name in super::RESERVED_TOOL_NAMES {
            let error = super::write_tool_manifest(dir.path(), name, "name: impostor\n")
                .expect_err("a reserved name must not be written as an artifact manifest");
            assert!(
                matches!(error, RuntimeError::ReservedToolName { .. }),
                "got {error:?}"
            );
            assert!(
                error.to_string().contains(name),
                "the refusal names the collision: {error}"
            );
        }

        assert_eq!(
            std::fs::read_to_string(&synthetic).unwrap(),
            before,
            "the synthetic manifest survives the refused write byte for byte"
        );
        assert!(
            !dir.path()
                .join("tools")
                .join(super::SHARE_FILE_TOOL)
                .exists(),
            "a refused write creates no directory"
        );
    }

    /// The inverse guard on the synthetic side.
    #[test]
    fn a_runtime_provided_write_refuses_an_unreserved_name() {
        let dir = tempfile::tempdir().unwrap();
        let error =
            super::write_runtime_provided_tool_manifest(dir.path(), "summon-task", "name: x\n")
                .expect_err("an unreserved name must not be written as a runtime-provided tool");
        assert!(
            matches!(error, RuntimeError::RuntimeProvidedToolNotReserved { .. }),
            "got {error:?}"
        );
        assert!(
            error.to_string().contains("RESERVED_TOOL_NAMES"),
            "the refusal says where to add the name: {error}"
        );
        assert!(!dir.path().join("tools").exists(), "and writes no file");
    }

    /// The operator-facing half: every reserved name is refused as an artifact, and the message
    /// carries the whole set so the operator sees what else is off-limits.
    #[test]
    fn a_declared_artifact_under_a_reserved_name_is_refused() {
        for name in super::RESERVED_TOOL_NAMES {
            let error = super::check_no_reserved_tool_names([name, "corpus"])
                .expect_err("a reserved name must be refused as an artifact name");
            let rendered = error.to_string();
            assert!(rendered.contains(name), "{rendered}");
            for reserved in super::RESERVED_TOOL_NAMES {
                assert!(
                    rendered.contains(reserved),
                    "the refusal lists the whole reserved set: {rendered}"
                );
            }
        }
        super::check_no_reserved_tool_names(["corpus", "bash", "share_file"])
            .expect("a capsule with no collision is untouched");
    }

    // ── task-start-event.context-window ──────────────────────────────────────

    /// The manifest body every `context:` case below shares, minus the `context:` block.
    const CONTEXT_WINDOW_MANIFEST: &str = r#"name: windowed
version: 0.1.0
runtime: capsule
artifacts: []
inference:
  transport: http
  endpoint: https://api.anthropic.com
  model: claude-opus-4-5
  max_tokens: 4096
  driver:
    artifact: murmur-driver-anthropic
"#;

    /// The `context-window` the three `HookEvent::TaskStart` sites in `launch_session`
    /// send, computed the way they compute it: from the parsed manifest's `context:`
    /// block, through [`resolve_context_window`], widened to the WIT `u64`.
    fn dispatched_context_window(manifest_yaml: &str) -> u64 {
        let manifest = murmur_artifact::RuntimeManifest::from_yaml_str(manifest_yaml)
            .expect("the manifest under test parses");
        u64::from(resolve_context_window(manifest.context.as_ref()))
    }

    /// A capsule declaring `context.max_tokens` puts that number on every
    /// `on-task-start`, so a seeding hook never has to know the model or its window.
    #[test]
    fn a_declared_context_window_reaches_on_task_start() {
        let yaml = format!("{CONTEXT_WINDOW_MANIFEST}context:\n  max_tokens: 200000\n");
        assert_eq!(dispatched_context_window(&yaml), 200_000);
    }

    /// A capsule with no `context:` block sends `0` — the WIT contract's "the host has
    /// not computed this", never a guessed default window.
    #[test]
    fn no_context_block_sends_a_zero_context_window() {
        assert_eq!(dispatched_context_window(CONTEXT_WINDOW_MANIFEST), 0);
    }

    // ── The persistent-capsule handle-TTL rule ───────────────────────────────

    fn peer_export(max_ttl_secs: Option<u64>) -> murmur_artifact::PeerFilesExport {
        murmur_artifact::PeerFilesExport {
            root: "out/".to_string(),
            max_ttl_secs,
            max_bytes: 10 * 1024 * 1024,
        }
    }

    fn lifecycle_with(after_task: murmur_artifact::AfterTask) -> LifecycleConfig {
        LifecycleConfig {
            after_task,
            ..Default::default()
        }
    }

    /// An ephemeral capsule needs no ceiling at all: teardown destroys the key, so the declared
    /// lifetime can never be the real bound however long it is.
    #[test]
    fn an_ephemeral_capsule_may_declare_any_handle_ttl_or_none() {
        for declared in [None, Some(1), Some(900), Some(86_400), Some(u64::MAX)] {
            assert!(
                check_persistent_handle_ttl(
                    Some(&peer_export(declared)),
                    &lifecycle_with(murmur_artifact::AfterTask::Exit),
                )
                .is_ok(),
                "exit + max_ttl {declared:?} must launch"
            );
        }
    }

    #[test]
    fn a_persistent_capsule_must_declare_a_handle_ttl_at_or_under_the_ceiling() {
        for declared in [Some(1), Some(600), Some(900)] {
            assert!(
                check_persistent_handle_ttl(
                    Some(&peer_export(declared)),
                    &lifecycle_with(murmur_artifact::AfterTask::Sleep),
                )
                .is_ok(),
                "sleep + max_ttl {declared:?} must launch"
            );
        }
        for declared in [None, Some(901), Some(1800), Some(3600)] {
            let error = check_persistent_handle_ttl(
                Some(&peer_export(declared)),
                &lifecycle_with(murmur_artifact::AfterTask::Sleep),
            )
            .expect_err("sleep + max_ttl {declared:?} must refuse");
            assert!(matches!(
                error,
                RuntimeError::PersistentCapsuleNeedsHandleTtl { .. }
            ));
            let rendered = error.to_string();
            assert!(
                rendered.contains("exports.peer_files.max_ttl"),
                "{rendered}"
            );
            assert!(
                rendered.contains("lifecycle.after_task: sleep"),
                "{rendered}"
            );
            assert!(rendered.contains("900s"), "{rendered}");
            assert!(rendered.contains("durability"), "{rendered}");
        }
    }

    /// The rule is about handles, so a capsule that declares no peer export is never asked.
    #[test]
    fn a_capsule_without_peer_files_is_unaffected_by_the_ttl_rule() {
        for after_task in [
            murmur_artifact::AfterTask::Exit,
            murmur_artifact::AfterTask::Sleep,
        ] {
            assert!(check_persistent_handle_ttl(None, &lifecycle_with(after_task)).is_ok());
        }
    }
    use murmur_artifact::{ArtifactMeta, ArtifactRuntime, Registry, ResolvedArtifact, RuntimeType};
    use tempfile::TempDir;

    use super::*;

    fn bootstrap_log_contents(workdir: &Path) -> String {
        fs::read_to_string(workdir.join("logs").join("bootstrap.log")).unwrap_or_default()
    }

    fn lifecycle(task_acceptance: TaskAcceptance, after_task: AfterTask) -> LifecycleConfig {
        LifecycleConfig {
            task_acceptance,
            after_task,
            ..LifecycleConfig::default()
        }
    }

    /// A capsule that can delegate and leaves `lifecycle` at its defaults is warned, because
    /// `after_task: exit` ends the session before any outcome can arrive.
    #[test]
    fn warn_for_unreachable_delegation_outcomes_writes_the_code_and_link_to_bootstrap_log() {
        let temp = TempDir::new().unwrap();
        warn_for_unreachable_delegation_outcomes(temp.path(), true, &LifecycleConfig::default());
        let log = bootstrap_log_contents(temp.path());

        assert!(log.contains(W_SEC_020), "log was: {log}");
        assert!(
            log.contains(&security_warning_link(W_SEC_020)),
            "log was: {log}"
        );
        assert!(log.contains("lifecycle.task_acceptance"), "log was: {log}");
        assert!(log.contains("lifecycle.after_task"), "log was: {log}");
    }

    /// The only lifecycle a completion can reach is `queue` + `sleep`; a capsule that declares no
    /// `capabilities.spawn.allow` is never warned whatever it declares.
    #[test]
    fn only_a_delegating_capsule_that_cannot_be_told_is_warned() {
        assert!(unreachable_delegation_outcomes_warning(
            true,
            &lifecycle(TaskAcceptance::Queue, AfterTask::Sleep)
        )
        .is_none());
        for lifecycle in [
            lifecycle(TaskAcceptance::Queue, AfterTask::Exit),
            lifecycle(TaskAcceptance::Single, AfterTask::Sleep),
            lifecycle(TaskAcceptance::None, AfterTask::Sleep),
        ] {
            assert!(
                unreachable_delegation_outcomes_warning(true, &lifecycle).is_some(),
                "{lifecycle:?} cannot receive a completion"
            );
            assert!(
                unreachable_delegation_outcomes_warning(false, &lifecycle).is_none(),
                "a capsule that cannot delegate is not warned about delegating"
            );
        }
    }

    /// A capsule that can run shell commands and leaves `lifecycle` at its defaults is warned,
    /// because `after_task: exit` ends the session before any demoted command's completion can
    /// arrive.
    #[test]
    fn warn_for_unreachable_shell_completions_writes_the_code_and_link_to_bootstrap_log() {
        let temp = TempDir::new().unwrap();
        warn_for_unreachable_shell_completions(temp.path(), true, &LifecycleConfig::default());
        let log = bootstrap_log_contents(temp.path());

        assert!(log.contains(W_SEC_022), "log was: {log}");
        assert!(
            log.contains(&security_warning_link(W_SEC_022)),
            "log was: {log}"
        );
        assert!(log.contains("lifecycle.shell_grace_secs"), "log was: {log}");
        assert!(log.contains("lifecycle.task_acceptance"), "log was: {log}");
        assert!(log.contains("lifecycle.after_task"), "log was: {log}");
    }

    /// The only lifecycle a completion can reach is `queue` + `sleep`; a capsule that declares no
    /// `capabilities.shell.allow` is never warned whatever it declares.
    #[test]
    fn only_a_shell_running_capsule_that_cannot_be_told_is_warned() {
        assert!(unreachable_shell_completions_warning(
            true,
            &lifecycle(TaskAcceptance::Queue, AfterTask::Sleep)
        )
        .is_none());
        for lifecycle in [
            lifecycle(TaskAcceptance::Queue, AfterTask::Exit),
            lifecycle(TaskAcceptance::Single, AfterTask::Sleep),
            lifecycle(TaskAcceptance::None, AfterTask::Sleep),
        ] {
            assert_eq!(
                unreachable_shell_completions_warning(true, &lifecycle).map(|(code, _)| code),
                Some(W_SEC_022),
                "{lifecycle:?} cannot receive a completion"
            );
            assert!(
                unreachable_shell_completions_warning(false, &lifecycle).is_none(),
                "a capsule that cannot run shell commands is not warned about them"
            );
        }
    }

    /// `lifecycle.shell_grace_secs` is not part of the decision. `0` demotes on the first check
    /// after the spawn, so a low grace makes the discard more likely rather than less, and no
    /// value of it turns demotion off.
    #[test]
    fn the_shell_completion_warning_ignores_the_grace_period() {
        for shell_grace_secs in [0, 1, 10, 3_600] {
            let receiving = LifecycleConfig {
                task_acceptance: TaskAcceptance::Queue,
                after_task: AfterTask::Sleep,
                shell_grace_secs,
                ..LifecycleConfig::default()
            };
            assert!(
                unreachable_shell_completions_warning(true, &receiving).is_none(),
                "queue+sleep is silent at every grace period, including {shell_grace_secs}"
            );
            let discarding = LifecycleConfig {
                after_task: AfterTask::Exit,
                ..receiving
            };
            assert!(
                unreachable_shell_completions_warning(true, &discarding).is_some(),
                "exit warns at every grace period, including {shell_grace_secs}"
            );
        }
    }

    // ── capabilities.env.allow secret grants ─────────────────────────────────

    fn env_allow_policy(names: &[&str], strip: &[&str]) -> CapabilityPolicy {
        CapabilityPolicy {
            env_allow: names.iter().map(|name| (*name).to_string()).collect(),
            shell_strip_env: strip.iter().map(|name| (*name).to_string()).collect(),
            ..CapabilityPolicy::default()
        }
    }

    /// The held arm: a credential-shaped name the backstop's fixed list does not cover reaches
    /// every guest, and the default lifecycle does not keep the capsule past its task.
    #[test]
    fn a_credential_shaped_name_the_backstop_keeps_is_reported_as_reaching_the_guest() {
        let grants = secret_shaped_env_grants(
            &env_allow_policy(&["DATABASE_PASSWORD"], &[]),
            &LifecycleConfig::default(),
        );

        assert_eq!(
            grants,
            vec![SecretShapedEnvGrant {
                name: "DATABASE_PASSWORD".to_string(),
                outlives_launcher: false,
            }]
        );
        let message = secret_shaped_env_grant_message(&grants[0]);
        assert!(message.contains("the capsule holds it"), "{message}");
        assert!(!message.contains("lifecycle.after_task"), "{message}");
    }

    /// The escalated arm: `after_task: sleep` alone, without `task_acceptance: queue`, still keeps
    /// the capsule alive past the task that launched it, so the sentence is added. Read directly
    /// off `after_task` rather than through `can_receive_background_tasks`, which would stay
    /// silent here.
    #[test]
    fn sleep_escalates_a_held_grant_even_without_a_queue() {
        for acceptance in [
            TaskAcceptance::Single,
            TaskAcceptance::Queue,
            TaskAcceptance::None,
        ] {
            let grants = secret_shaped_env_grants(
                &env_allow_policy(&["DATABASE_PASSWORD"], &[]),
                &lifecycle(acceptance.clone(), AfterTask::Sleep),
            );
            assert!(
                grants[0].outlives_launcher,
                "{acceptance:?} + sleep outlives the launching task"
            );
            let message = secret_shaped_env_grant_message(&grants[0]);
            assert!(message.contains("lifecycle.after_task: sleep"), "{message}");
            assert!(
                message.contains("with nothing left waiting on it"),
                "{message}"
            );
        }
    }

    /// `GITHUB_TOKEN` is credential-shaped *and* on the backstop's list, so no guest holds it and
    /// there is no grant to report; `E-CAP-016` refuses the declaration instead.
    #[test]
    fn a_name_the_backstop_drops_produces_no_grant() {
        assert!(secret_shaped_env_grants(
            &env_allow_policy(&["GITHUB_TOKEN"], &[]),
            &lifecycle(TaskAcceptance::Queue, AfterTask::Sleep),
        )
        .is_empty());
    }

    /// A manifest's own `capabilities.shell.strip_env` pattern takes a credential-shaped name out
    /// of the warning, because the backstop consults that list too.
    #[test]
    fn a_strip_matched_credential_shaped_name_produces_no_grant() {
        assert!(secret_shaped_env_grants(
            &env_allow_policy(&["MY_SERVICE_SECRET"], &["*_SERVICE_SECRET"]),
            &LifecycleConfig::default(),
        )
        .is_empty());
    }

    /// Names only the segment rule of `is_credential_shaped_env_name` catches still reach every
    /// guest, so each is reported.
    #[test]
    fn segment_matched_credential_names_each_produce_a_grant() {
        let grants = secret_shaped_env_grants(
            &env_allow_policy(
                &["PRIVATE_KEY", "SSH_KEY", "CREDENTIALS", "SENTRY_DSN"],
                &[],
            ),
            &LifecycleConfig::default(),
        );

        assert_eq!(
            grants
                .iter()
                .map(|grant| grant.name.as_str())
                .collect::<Vec<_>>(),
            vec!["PRIVATE_KEY", "SSH_KEY", "CREDENTIALS", "SENTRY_DSN"]
        );
    }

    /// `after_task: sleep` is not itself a trigger: with no credential-shaped name declared there
    /// is nothing to hold, and a name that is not credential-shaped is not judged.
    #[test]
    fn sleep_without_a_credential_shaped_name_decides_nothing() {
        assert!(secret_shaped_env_grants(
            &env_allow_policy(&["HOME", "TZ", "LANG", "BUILD_NUMBER"], &[]),
            &lifecycle(TaskAcceptance::Queue, AfterTask::Sleep),
        )
        .is_empty());
        assert!(secret_shaped_env_grants(
            &CapabilityPolicy::default(),
            &lifecycle(TaskAcceptance::Queue, AfterTask::Sleep),
        )
        .is_empty());
    }

    /// One judgment per distinct name, in declaration order, with non-credential names and names
    /// the backstop drops passed over rather than counted.
    #[test]
    fn every_distinct_credential_shaped_name_is_judged_once_in_declaration_order() {
        let grants = secret_shaped_env_grants(
            &env_allow_policy(
                &[
                    "DATABASE_PASSWORD",
                    "HOME",
                    "GITHUB_TOKEN",
                    "SIGNING_KEY",
                    "DATABASE_PASSWORD",
                ],
                &[],
            ),
            &LifecycleConfig::default(),
        );

        assert_eq!(
            grants
                .iter()
                .map(|grant| grant.name.as_str())
                .collect::<Vec<_>>(),
            vec!["DATABASE_PASSWORD", "SIGNING_KEY"]
        );
    }

    // ── E-CAP-016: env.allow entries the credential backstop strips ─────────

    #[test]
    fn stripped_env_allow_entries_are_distinct_ordered_and_attributed() {
        let entries = super::stripped_env_allow_entries(&env_allow_policy(
            &[
                "NPM_TOKEN",
                "TZ",
                "MY_SERVICE_SECRET",
                "NPM_TOKEN",
                "AWS_REGION",
            ],
            &["*_SERVICE_SECRET"],
        ));

        assert_eq!(
            entries,
            vec![
                super::StrippedEnvAllowEntry {
                    name: "NPM_TOKEN".to_string(),
                    pattern: "NPM_TOKEN".to_string(),
                    source: crate::shell::BackstopPatternSource::Builtin,
                },
                super::StrippedEnvAllowEntry {
                    name: "MY_SERVICE_SECRET".to_string(),
                    pattern: "*_SERVICE_SECRET".to_string(),
                    source: crate::shell::BackstopPatternSource::StripEnv,
                },
                super::StrippedEnvAllowEntry {
                    name: "AWS_REGION".to_string(),
                    pattern: "AWS_*".to_string(),
                    source: crate::shell::BackstopPatternSource::Builtin,
                },
            ]
        );
    }

    #[test]
    fn env_allow_names_the_backstop_keeps_pass_the_check() {
        assert!(super::check_env_allow_reaches_guests(&env_allow_policy(
            &["TZ", "PRIVATE_KEY", "DATABASE_PASSWORD"],
            &[],
        ))
        .is_ok());
        assert!(super::check_env_allow_reaches_guests(&CapabilityPolicy::default()).is_ok());
    }

    /// The message names every entry with its pattern and that pattern's source.
    #[test]
    fn the_refusal_names_each_entry_its_pattern_and_the_patterns_source() {
        let error = super::check_env_allow_reaches_guests(&env_allow_policy(
            &["GITHUB_TOKEN", "MY_SERVICE_SECRET"],
            &["*_SERVICE_SECRET"],
        ))
        .unwrap_err();
        let message = error.to_string();

        assert!(message.contains("capabilities.env.allow"), "{message}");
        assert!(
            message.contains(
                "'GITHUB_TOKEN' (credential backstop pattern 'GITHUB_TOKEN'), 'MY_SERVICE_SECRET' \
                 (capabilities.shell.strip_env pattern '*_SERVICE_SECRET')"
            ),
            "{message}"
        );
    }

    /// An `InferenceConfig` with every system-prompt field empty, for the prompt-resolution
    /// tests below to fill in one at a time.
    fn inference_without_prompt() -> murmur_artifact::InferenceConfig {
        murmur_artifact::InferenceConfig {
            transport: "http".to_string(),
            endpoint: Some("http://127.0.0.1:1".to_string()),
            model: "test-model".to_string(),
            api_key: None,
            driver: None,
            command: None,
            compaction: None,
            system_prompt: None,
            system_prompt_file: None,
            system_prompt_artifact: None,
            max_turns: 10,
            max_tokens: None,
            max_session_tokens: None,
        }
    }

    #[test]
    fn resolve_system_prompt_returns_none_when_nothing_is_declared() {
        let tmp = TempDir::new().unwrap();
        let resolved =
            resolve_system_prompt(tmp.path(), tmp.path(), &inference_without_prompt()).unwrap();
        assert_eq!(resolved, None);
    }

    #[test]
    fn resolve_system_prompt_returns_the_inline_prompt_verbatim() {
        let tmp = TempDir::new().unwrap();
        let inference = murmur_artifact::InferenceConfig {
            system_prompt: Some("Be terse.".to_string()),
            ..inference_without_prompt()
        };
        let resolved = resolve_system_prompt(tmp.path(), tmp.path(), &inference).unwrap();
        assert_eq!(resolved.as_deref(), Some("Be terse."));
    }

    /// File contents are used exactly as they sit on disk — trailing newline included. The
    /// trimming that applies to the inline form happens at manifest parse time and has no
    /// counterpart here.
    #[test]
    fn resolve_system_prompt_reads_the_prompt_file_verbatim_relative_to_the_manifest_dir() {
        let manifest_dir = TempDir::new().unwrap();
        let workdir = TempDir::new().unwrap();
        fs::write(manifest_dir.path().join("conventions.md"), "  Be terse.\n").unwrap();

        let inference = murmur_artifact::InferenceConfig {
            system_prompt_file: Some("conventions.md".to_string()),
            ..inference_without_prompt()
        };
        let resolved =
            resolve_system_prompt(manifest_dir.path(), workdir.path(), &inference).unwrap();
        assert_eq!(resolved.as_deref(), Some("  Be terse.\n"));
    }

    #[test]
    fn resolve_system_prompt_errors_when_the_prompt_file_is_missing() {
        let tmp = TempDir::new().unwrap();
        let inference = murmur_artifact::InferenceConfig {
            system_prompt_file: Some("missing-conventions.md".to_string()),
            ..inference_without_prompt()
        };
        match resolve_system_prompt(tmp.path(), tmp.path(), &inference) {
            Err(RuntimeError::SystemPromptFileRead { path, .. }) => {
                assert!(path.ends_with("missing-conventions.md"), "got {path}");
            }
            other => panic!("expected SystemPromptFileRead, got {other:?}"),
        }
    }

    /// The artifact branch reads the staged skill's `skill.md` out of the *workdir*, not the
    /// manifest directory — it is a resolved artifact, not a file the author wrote beside
    /// murmur.yaml.
    #[test]
    fn resolve_system_prompt_reads_skill_md_from_the_staged_artifact() {
        let manifest_dir = TempDir::new().unwrap();
        let workdir = TempDir::new().unwrap();
        let skill_dir = workdir.path().join("tools").join("house-style");
        fs::create_dir_all(&skill_dir).unwrap();
        fs::write(skill_dir.join("skill.md"), "# House style\nBe terse.").unwrap();

        let inference = murmur_artifact::InferenceConfig {
            system_prompt_artifact: Some("house-style".to_string()),
            ..inference_without_prompt()
        };
        let resolved =
            resolve_system_prompt(manifest_dir.path(), workdir.path(), &inference).unwrap();
        assert_eq!(resolved.as_deref(), Some("# House style\nBe terse."));
    }

    #[test]
    fn resolve_system_prompt_errors_when_the_prompt_artifact_has_no_skill_md() {
        let tmp = TempDir::new().unwrap();
        let inference = murmur_artifact::InferenceConfig {
            system_prompt_artifact: Some("house-style".to_string()),
            ..inference_without_prompt()
        };
        match resolve_system_prompt(tmp.path(), tmp.path(), &inference) {
            Err(RuntimeError::SystemPromptArtifactRead { name, .. }) => {
                assert_eq!(name, "house-style");
            }
            other => panic!("expected SystemPromptArtifactRead, got {other:?}"),
        }
    }

    /// `mur run --system-prompt` overrides by clearing the other two fields and setting the
    /// inline one, so resolution never reaches a declaration the operator replaced — including
    /// a `system_prompt_file` pointing at a file that does not exist.
    #[test]
    fn resolve_system_prompt_ignores_cleared_declarations() {
        let tmp = TempDir::new().unwrap();
        let inference = murmur_artifact::InferenceConfig {
            system_prompt: Some("CLI prompt".to_string()),
            system_prompt_file: None,
            system_prompt_artifact: None,
            ..inference_without_prompt()
        };
        let resolved = resolve_system_prompt(tmp.path(), tmp.path(), &inference).unwrap();
        assert_eq!(resolved.as_deref(), Some("CLI prompt"));
    }

    #[test]
    fn bash_and_network_together_trigger_warning() {
        let tmp = TempDir::new().unwrap();
        let policy = CapabilityPolicy {
            shell_allow: vec!["bash".to_string()],
            network_allow: vec!["https://api.example.com".to_string()],
            ..Default::default()
        };
        warn_if_bash_network_bypass(tmp.path(), &policy);
        let log = bootstrap_log_contents(tmp.path());
        assert!(log.contains("bash"), "log should mention bash: {log}");
        assert!(log.contains("network"), "log should mention network: {log}");
        assert!(
            log.contains(W_SEC_003),
            "log should carry its warning code: {log}"
        );
        assert!(
            log.contains(&security_warning_link(W_SEC_003)),
            "log should link to the diagnostics doc page: {log}"
        );
    }

    fn compaction_config(
        system_prompt: Option<&str>,
        system_prompt_file: Option<&str>,
    ) -> murmur_artifact::CompactionConfig {
        murmur_artifact::CompactionConfig {
            threshold: None,
            model: Some("compaction-model".to_string()),
            system_prompt: system_prompt.map(str::to_string),
            system_prompt_file: system_prompt_file.map(str::to_string),
            dump_summaries: None,
        }
    }

    /// `system_prompt_file` is read relative to the manifest directory — not the process
    /// cwd — and its contents reach the hook verbatim, newlines and all.
    #[test]
    fn compaction_system_prompt_file_resolves_relative_to_manifest_dir() {
        let manifest_dir = TempDir::new().unwrap();
        let body = "Summarize aggressively.\nKeep file paths.\n";
        fs::write(manifest_dir.path().join("compaction-instructions.md"), body).unwrap();

        let resolved = resolve_compaction_system_prompt(
            manifest_dir.path(),
            Some(&compaction_config(None, Some("compaction-instructions.md"))),
        )
        .expect("file resolves");

        assert_eq!(resolved, Some(body.to_string()));
    }

    /// The inline field keeps its pre-existing behavior: returned as-is, no file touched.
    #[test]
    fn compaction_inline_system_prompt_resolves_without_reading_a_file() {
        let manifest_dir = TempDir::new().unwrap();

        let resolved = resolve_compaction_system_prompt(
            manifest_dir.path(),
            Some(&compaction_config(Some("inline prompt"), None)),
        )
        .expect("inline prompt resolves");

        assert_eq!(resolved, Some("inline prompt".to_string()));
    }

    /// Neither prompt source set — and no `compaction:` block at all — both stay `None`;
    /// nothing on this path substitutes a default prompt.
    #[test]
    fn compaction_system_prompt_absent_resolves_to_none() {
        let manifest_dir = TempDir::new().unwrap();

        assert_eq!(
            resolve_compaction_system_prompt(
                manifest_dir.path(),
                Some(&compaction_config(None, None))
            )
            .unwrap(),
            None
        );
        assert_eq!(
            resolve_compaction_system_prompt(manifest_dir.path(), None).unwrap(),
            None
        );
    }

    /// A missing file fails with the compaction-specific variant — distinguishable by
    /// variant, not just message text, from the primary prompt's `SystemPromptFileRead` —
    /// and names the resolved path.
    #[test]
    fn compaction_system_prompt_file_missing_reports_compaction_variant() {
        let manifest_dir = TempDir::new().unwrap();

        let err = resolve_compaction_system_prompt(
            manifest_dir.path(),
            Some(&compaction_config(None, Some("nope.md"))),
        )
        .expect_err("missing file must fail");

        match &err {
            RuntimeError::CompactionSystemPromptFileRead { path, .. } => {
                assert!(
                    path.ends_with("nope.md"),
                    "error should name the resolved path, got {path}"
                );
                assert!(
                    path.starts_with(&manifest_dir.path().display().to_string()),
                    "path should be manifest-dir relative, got {path}"
                );
            }
            other => panic!("expected CompactionSystemPromptFileRead, got {other:?}"),
        }
        assert!(err
            .to_string()
            .contains("inference.compaction.system_prompt_file"));
    }

    #[test]
    fn network_without_bash_does_not_warn() {
        let tmp = TempDir::new().unwrap();
        let policy = CapabilityPolicy {
            shell_allow: vec!["cargo".to_string(), "git".to_string()],
            network_allow: vec!["https://api.example.com".to_string()],
            ..Default::default()
        };
        warn_if_bash_network_bypass(tmp.path(), &policy);
        assert!(bootstrap_log_contents(tmp.path()).is_empty());
    }

    #[test]
    fn bash_without_network_does_not_warn() {
        let tmp = TempDir::new().unwrap();
        let policy = CapabilityPolicy {
            shell_allow: vec!["bash".to_string()],
            network_allow: Vec::new(),
            ..Default::default()
        };
        warn_if_bash_network_bypass(tmp.path(), &policy);
        assert!(bootstrap_log_contents(tmp.path()).is_empty());
    }

    #[test]
    fn neither_declared_does_not_warn() {
        let tmp = TempDir::new().unwrap();
        warn_if_bash_network_bypass(tmp.path(), &CapabilityPolicy::default());
        assert!(bootstrap_log_contents(tmp.path()).is_empty());
    }

    #[test]
    fn non_bash_shell_interpreter_does_not_warn() {
        let tmp = TempDir::new().unwrap();
        let policy = CapabilityPolicy {
            shell_allow: vec!["sh".to_string()],
            network_allow: vec!["https://api.example.com".to_string()],
            ..Default::default()
        };
        warn_if_bash_network_bypass(tmp.path(), &policy);
        assert!(
            bootstrap_log_contents(tmp.path()).is_empty(),
            "exact match on \"bash\" literal must not fire for other shell interpreters like sh"
        );
    }

    #[test]
    fn allowlist_blocks_unlisted_before_dispatch() {
        let allowlist = HashSet::from(["echo-tool".to_string()]);
        let mut dispatched = false;

        let result = enforce_allowlist(&allowlist, "missing-tool", || {
            dispatched = true;
            Ok::<_, String>(())
        });

        assert!(!dispatched);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .contains("not declared in manifest allowlist"));
    }

    #[test]
    fn allowlist_dispatches_listed_tool() {
        let allowlist = HashSet::from(["echo-tool".to_string()]);
        let result = enforce_allowlist(&allowlist, "echo-tool", || Ok::<_, String>("ok")).unwrap();
        assert_eq!(result, "ok");
    }

    /// Builds a component that exports a single empty instance under `iface`.
    /// `resolve_versioned_iface` only looks up the export index by instance
    /// name — it never inspects the instance's contents — so an empty instance
    /// is sufficient to exercise its versioned-name probe.
    fn iface_double(engine: &wasmtime::Engine, iface: &str) -> wasmtime::component::Component {
        let wat = format!(
            "(component\n\
             (instance $i)\n\
             (export \"{iface}\" (instance $i))\n\
             )"
        );
        let bytes = wat::parse_str(&wat).expect("component WAT parses");
        wasmtime::component::Component::new(engine, bytes).expect("component compiles")
    }

    fn iface_test_engine() -> wasmtime::Engine {
        let mut config = wasmtime::Config::new();
        config.wasm_component_model(true);
        wasmtime::Engine::new(&config).expect("engine builds")
    }

    fn instantiate_iface_double(
        engine: &wasmtime::Engine,
        iface: &str,
    ) -> (wasmtime::component::Instance, Store<()>) {
        let component = iface_double(engine, iface);
        let linker = wasmtime::component::Linker::new(engine);
        let mut store = Store::new(engine, ());
        let instance = linker
            .instantiate(&mut store, &component)
            .expect("component with no imports instantiates");
        (instance, store)
    }

    /// A component exporting the versioned instance name (the shape a guest
    /// built against the semver'd WIT carries) resolves via the versioned probe.
    #[test]
    fn resolve_versioned_iface_finds_versioned_name() {
        let engine = iface_test_engine();
        let (instance, mut store) = instantiate_iface_double(&engine, WIT_CAPSULE_IFACE_VERSIONED);
        let found = resolve_versioned_iface(&instance, &mut store, WIT_CAPSULE_IFACE_VERSIONED);
        assert!(
            found.is_some(),
            "a component exporting the versioned name must resolve"
        );
    }

    /// A component exporting only the legacy unversioned instance name no longer
    /// resolves — the fallback probe was removed, so the versioned-only lookup
    /// returns `None` and the call site surfaces a hard missing-export error.
    #[test]
    fn resolve_versioned_iface_rejects_unversioned_only_name() {
        let engine = iface_test_engine();
        let (instance, mut store) = instantiate_iface_double(&engine, "murmur:tool/run");
        let found = resolve_versioned_iface(&instance, &mut store, WIT_TOOL_IFACE_VERSIONED);
        assert!(
            found.is_none(),
            "a component exporting only the legacy unversioned name must no longer resolve"
        );
    }

    /// A component exporting neither the versioned name nor any recognizable
    /// name resolves to `None` — the probe must not silently swallow a genuinely
    /// absent interface.
    #[test]
    fn resolve_versioned_iface_returns_none_when_neither_name_matches() {
        let engine = iface_test_engine();
        let (instance, mut store) = instantiate_iface_double(&engine, "murmur:capsule/nonexistent");
        let found = resolve_versioned_iface(&instance, &mut store, WIT_CAPSULE_IFACE_VERSIONED);
        assert!(
            found.is_none(),
            "a component exporting neither probed name must not resolve"
        );
    }

    #[test]
    fn generate_session_id_is_unique() {
        let first = generate_session_id();
        let second = generate_session_id();

        assert_ne!(first, second);
        assert!(first.starts_with("ses_"), "session id must start with ses_");
        assert_eq!(
            first.len(),
            36,
            "session id must be 36 chars (ses_ + 32 hex)"
        );
        uuid::Uuid::parse_str(&first[4..]).expect("session id suffix should be a valid UUID");
    }

    #[test]
    fn sha_verification_happens_before_component_compile() {
        struct FakeRegistry;

        impl Registry for FakeRegistry {
            fn resolve(
                &self,
                name: &str,
                version: &str,
            ) -> Result<ResolvedArtifact, RegistryError> {
                Ok(ResolvedArtifact {
                    meta: ArtifactMeta {
                        name: name.to_string(),
                        version: version.to_string(),
                        runtime: RuntimeType::Wasm,
                        artifact_runtime: "wasm".to_string(),
                        platforms: Vec::new(),
                        description: None,
                        tags: Vec::new(),
                        wit_contracts: None,
                    },
                    bytes: b"not-a-real-zip".to_vec().into(),
                    sha256: "definitely-wrong".to_string(),
                    platform_match: murmur_artifact::PlatformMatch::NotApplicable,
                })
            }

            fn publish(
                &self,
                _meta: ArtifactMeta,
                _bytes: &[u8],
            ) -> Result<murmur_artifact::PublishResult, RegistryError> {
                unreachable!()
            }

            fn list_index(&self) -> Result<Vec<ArtifactMeta>, RegistryError> {
                unreachable!()
            }
        }

        let tempdir = tempfile::tempdir().unwrap();
        let request = StageRequest {
            credentials_file: None,
            manifest_dir: tempdir.path().to_path_buf(),
            capsule_name: "test".to_string(),
            capsule_version: String::new(),
            capsule_component_bytes: b"not-a-component".to_vec(),
            artifacts: vec![crate::types::ArtifactRequest {
                name: "echo-tool".to_string(),
                version: "0.0.1".to_string(),
                runtime: ArtifactRuntime::Tool,
                source: None,
                on_overflow: Default::default(),
                capabilities: None,
                config: None,
            }],
            allowlisted_tools: HashSet::from(["echo-tool".to_string()]),
            lock_expectations: None,
            capability_policy: CapabilityPolicy::default(),
            inference: None,
            system_prompt_overridden: false,
            context: None,
            context_id: None,
            resume: None,
            otel_endpoint: None,
            eval_config_json: None,
            case_id: None,
            dataset_id: None,
            lifecycle: None,
            lifecycle_override: None,
            trace: None,
            workdir: None,
            bind_addr: "127.0.0.1".to_string(),
            internal_port: None,
            declared_containment_floor: murmur_artifact::ContainmentClass::Advisory,
            exports: None,
            spawn_grant: None,
            machine_tokens_per_day: None,
        };

        let err = match stage_session(Arc::new(FakeRegistry), request) {
            Ok(_) => panic!("expected stage_session to fail"),
            Err(err) => err,
        };
        assert!(matches!(
            err,
            RuntimeError::ArtifactIntegrityFailed { name, version }
                if name == "echo-tool" && version == "0.0.1"
        ));
    }

    #[test]
    fn lock_expectation_mismatch_returns_integrity_failure() {
        struct FakeRegistry;

        impl Registry for FakeRegistry {
            fn resolve(
                &self,
                name: &str,
                version: &str,
            ) -> Result<ResolvedArtifact, RegistryError> {
                Ok(ResolvedArtifact {
                    meta: ArtifactMeta {
                        name: name.to_string(),
                        version: version.to_string(),
                        runtime: RuntimeType::Wasm,
                        artifact_runtime: "wasm".to_string(),
                        platforms: Vec::new(),
                        description: None,
                        tags: Vec::new(),
                        wit_contracts: None,
                    },
                    bytes: b"not-a-real-zip".to_vec().into(),
                    sha256: murmur_artifact::sha256_hex(b"not-a-real-zip"),
                    platform_match: murmur_artifact::PlatformMatch::NotApplicable,
                })
            }

            fn publish(
                &self,
                _meta: ArtifactMeta,
                _bytes: &[u8],
            ) -> Result<murmur_artifact::PublishResult, RegistryError> {
                unreachable!()
            }

            fn list_index(&self) -> Result<Vec<ArtifactMeta>, RegistryError> {
                unreachable!()
            }
        }

        let tempdir = tempfile::tempdir().unwrap();
        let request = StageRequest {
            credentials_file: None,
            manifest_dir: tempdir.path().to_path_buf(),
            capsule_name: "test".to_string(),
            capsule_version: String::new(),
            capsule_component_bytes: Vec::new(),
            artifacts: vec![crate::types::ArtifactRequest {
                name: "echo-tool".to_string(),
                version: "0.0.1".to_string(),
                runtime: ArtifactRuntime::Tool,
                source: None,
                on_overflow: Default::default(),
                capabilities: None,
                config: None,
            }],
            allowlisted_tools: HashSet::from(["echo-tool".to_string()]),
            lock_expectations: Some(vec![crate::types::LockExpectation {
                name: "echo-tool".to_string(),
                resolved_version: "0.0.1".to_string(),
                sha256: "different".to_string(),
            }]),
            capability_policy: CapabilityPolicy::default(),
            inference: None,
            system_prompt_overridden: false,
            context: None,
            context_id: None,
            resume: None,
            otel_endpoint: None,
            eval_config_json: None,
            case_id: None,
            dataset_id: None,
            lifecycle: None,
            lifecycle_override: None,
            trace: None,
            workdir: None,
            bind_addr: "127.0.0.1".to_string(),
            internal_port: None,
            declared_containment_floor: murmur_artifact::ContainmentClass::Advisory,
            exports: None,
            spawn_grant: None,
            machine_tokens_per_day: None,
        };

        let err = match stage_session(Arc::new(FakeRegistry), request) {
            Ok(_) => panic!("expected stage_session to fail"),
            Err(err) => err,
        };
        assert!(matches!(
            err,
            RuntimeError::ArtifactIntegrityFailed { name, version }
                if name == "echo-tool" && version == "0.0.1"
        ));
    }

    #[test]
    fn lock_expectations_require_entry_for_each_manifest_artifact() {
        struct FakeRegistry;

        impl Registry for FakeRegistry {
            fn resolve(
                &self,
                _name: &str,
                _version: &str,
            ) -> Result<ResolvedArtifact, RegistryError> {
                unreachable!("lock validation should fail before any registry resolve call")
            }

            fn publish(
                &self,
                _meta: ArtifactMeta,
                _bytes: &[u8],
            ) -> Result<murmur_artifact::PublishResult, RegistryError> {
                unreachable!()
            }

            fn list_index(&self) -> Result<Vec<ArtifactMeta>, RegistryError> {
                unreachable!()
            }
        }

        let tempdir = tempfile::tempdir().unwrap();
        let request = StageRequest {
            credentials_file: None,
            manifest_dir: tempdir.path().to_path_buf(),
            capsule_name: "test".to_string(),
            capsule_version: String::new(),
            capsule_component_bytes: Vec::new(),
            artifacts: vec![crate::types::ArtifactRequest {
                name: "echo-tool".to_string(),
                version: "0.0.1".to_string(),
                runtime: ArtifactRuntime::Tool,
                source: None,
                on_overflow: Default::default(),
                capabilities: None,
                config: None,
            }],
            allowlisted_tools: HashSet::from(["echo-tool".to_string()]),
            lock_expectations: Some(vec![crate::types::LockExpectation {
                name: "different-tool".to_string(),
                resolved_version: "0.0.1".to_string(),
                sha256: "abc".to_string(),
            }]),
            capability_policy: CapabilityPolicy::default(),
            inference: None,
            system_prompt_overridden: false,
            context: None,
            context_id: None,
            resume: None,
            otel_endpoint: None,
            eval_config_json: None,
            case_id: None,
            dataset_id: None,
            lifecycle: None,
            lifecycle_override: None,
            trace: None,
            workdir: None,
            bind_addr: "127.0.0.1".to_string(),
            internal_port: None,
            declared_containment_floor: murmur_artifact::ContainmentClass::Advisory,
            exports: None,
            spawn_grant: None,
            machine_tokens_per_day: None,
        };

        let err = match stage_session(Arc::new(FakeRegistry), request) {
            Ok(_) => panic!("expected stage_session to fail"),
            Err(err) => err,
        };
        assert!(matches!(
            err,
            RuntimeError::LockMissingEntry { name } if name == "echo-tool"
        ));
    }

    #[test]
    fn lock_expectation_version_mismatch_is_reported() {
        struct FakeRegistry;

        impl Registry for FakeRegistry {
            fn resolve(
                &self,
                _name: &str,
                _version: &str,
            ) -> Result<ResolvedArtifact, RegistryError> {
                unreachable!("version mismatch should fail before registry resolve")
            }

            fn publish(
                &self,
                _meta: ArtifactMeta,
                _bytes: &[u8],
            ) -> Result<murmur_artifact::PublishResult, RegistryError> {
                unreachable!()
            }

            fn list_index(&self) -> Result<Vec<ArtifactMeta>, RegistryError> {
                unreachable!()
            }
        }

        let tempdir = tempfile::tempdir().unwrap();
        let request = StageRequest {
            credentials_file: None,
            manifest_dir: tempdir.path().to_path_buf(),
            capsule_name: "test".to_string(),
            capsule_version: String::new(),
            capsule_component_bytes: Vec::new(),
            artifacts: vec![crate::types::ArtifactRequest {
                name: "echo-tool".to_string(),
                version: "0.0.9".to_string(),
                runtime: ArtifactRuntime::Tool,
                source: None,
                on_overflow: Default::default(),
                capabilities: None,
                config: None,
            }],
            allowlisted_tools: HashSet::from(["echo-tool".to_string()]),
            lock_expectations: Some(vec![crate::types::LockExpectation {
                name: "echo-tool".to_string(),
                resolved_version: "0.0.1".to_string(),
                sha256: "abc".to_string(),
            }]),
            capability_policy: CapabilityPolicy::default(),
            inference: None,
            system_prompt_overridden: false,
            context: None,
            context_id: None,
            resume: None,
            otel_endpoint: None,
            eval_config_json: None,
            case_id: None,
            dataset_id: None,
            lifecycle: None,
            lifecycle_override: None,
            trace: None,
            workdir: None,
            bind_addr: "127.0.0.1".to_string(),
            internal_port: None,
            declared_containment_floor: murmur_artifact::ContainmentClass::Advisory,
            exports: None,
            spawn_grant: None,
            machine_tokens_per_day: None,
        };

        let err = match stage_session(Arc::new(FakeRegistry), request) {
            Ok(_) => panic!("expected stage_session to fail"),
            Err(err) => err,
        };
        assert!(matches!(
            err,
            RuntimeError::LockVersionMismatch {
                name,
                requested,
                pinned,
            } if name == "echo-tool" && requested == "0.0.9" && pinned == "0.0.1"
        ));
    }

    // ── local-source skill resolution ──────────────────────────────────────

    #[test]
    fn load_local_skill_md_reads_file_path() {
        let dir = tempfile::tempdir().unwrap();
        let skill = dir.path().join("skill.md");
        fs::write(&skill, b"# hi from file").unwrap();
        let bytes = load_local_skill_md(dir.path(), "skill.md").unwrap();
        assert_eq!(bytes, b"# hi from file");
    }

    #[test]
    fn load_local_skill_md_finds_skill_md_in_directory_case_insensitive() {
        let manifest_dir = tempfile::tempdir().unwrap();
        let skill_dir = manifest_dir.path().join("skills").join("my-skill");
        fs::create_dir_all(&skill_dir).unwrap();
        // Uppercase filename — must still be found.
        fs::write(skill_dir.join("SKILL.MD"), b"# upper").unwrap();
        let bytes = load_local_skill_md(manifest_dir.path(), "skills/my-skill").unwrap();
        assert_eq!(bytes, b"# upper");
    }

    #[test]
    fn load_local_skill_md_missing_path_errors_with_name() {
        let dir = tempfile::tempdir().unwrap();
        let err = load_local_skill_md(dir.path(), "does/not/exist").unwrap_err();
        match err {
            RuntimeError::SkillSourceNotFound { path } => {
                assert!(path.contains("does/not/exist"), "path was: {path}");
            }
            other => panic!("expected SkillSourceNotFound, got {other:?}"),
        }
    }

    #[test]
    fn load_local_skill_md_directory_without_skill_md_errors() {
        let dir = tempfile::tempdir().unwrap();
        let empty = dir.path().join("empty");
        fs::create_dir_all(&empty).unwrap();
        let err = load_local_skill_md(dir.path(), "empty").unwrap_err();
        match err {
            RuntimeError::SkillSourceMissingSkillMd { path } => {
                assert!(path.contains("empty"), "path was: {path}");
            }
            other => panic!("expected SkillSourceMissingSkillMd, got {other:?}"),
        }
    }

    #[test]
    fn load_local_skill_md_absolute_path_ignores_manifest_dir() {
        let manifest_dir = tempfile::tempdir().unwrap();
        let elsewhere = tempfile::tempdir().unwrap();
        let skill = elsewhere.path().join("skill.md");
        fs::write(&skill, b"# absolute").unwrap();
        let bytes = load_local_skill_md(manifest_dir.path(), &skill.to_string_lossy()).unwrap();
        assert_eq!(bytes, b"# absolute");
    }

    /// A backstop-stripped `env.allow` entry refuses staging before the registry is consulted for
    /// the one declared artifact.
    #[test]
    fn stage_session_refuses_an_env_allow_entry_the_backstop_strips() {
        struct PanicRegistry;
        impl Registry for PanicRegistry {
            fn resolve(&self, _: &str, _: &str) -> Result<ResolvedArtifact, RegistryError> {
                panic!("the refusal must precede registry resolution");
            }
            fn publish(
                &self,
                _: ArtifactMeta,
                _: &[u8],
            ) -> Result<murmur_artifact::PublishResult, RegistryError> {
                panic!("the refusal must precede any registry call");
            }
            fn list_index(&self) -> Result<Vec<ArtifactMeta>, RegistryError> {
                panic!("the refusal must precede any registry call");
            }
        }

        let project = tempfile::tempdir().unwrap();
        let request = StageRequest {
            credentials_file: None,
            manifest_dir: project.path().to_path_buf(),
            capsule_name: "test".to_string(),
            capsule_version: "0.0.1".to_string(),
            capsule_component_bytes: Vec::new(),
            artifacts: vec![crate::types::ArtifactRequest {
                name: "some-tool".to_string(),
                version: "0.1.0".to_string(),
                runtime: ArtifactRuntime::Tool,
                source: None,
                on_overflow: Default::default(),
                capabilities: None,
                config: None,
            }],
            allowlisted_tools: HashSet::new(),
            lock_expectations: None,
            capability_policy: env_allow_policy(&["GITHUB_TOKEN"], &[]),
            inference: None,
            system_prompt_overridden: false,
            context: None,
            context_id: None,
            resume: None,
            otel_endpoint: None,
            eval_config_json: None,
            case_id: None,
            dataset_id: None,
            lifecycle: None,
            lifecycle_override: None,
            trace: None,
            workdir: None,
            bind_addr: "127.0.0.1".to_string(),
            internal_port: None,
            declared_containment_floor: murmur_artifact::ContainmentClass::Advisory,
            exports: None,
            spawn_grant: None,
            machine_tokens_per_day: None,
        };

        match stage_session(Arc::new(PanicRegistry), request) {
            Err(RuntimeError::EnvAllowStrippedByBackstop { entries }) => assert_eq!(
                entries,
                vec![super::StrippedEnvAllowEntry {
                    name: "GITHUB_TOKEN".to_string(),
                    pattern: "GITHUB_TOKEN".to_string(),
                    source: crate::shell::BackstopPatternSource::Builtin,
                }]
            ),
            Err(other) => panic!("expected EnvAllowStrippedByBackstop, got {other}"),
            Ok(_) => panic!("staging must refuse a backstop-stripped env.allow entry"),
        }
    }

    #[test]
    fn stage_session_installs_local_source_skill_without_registry() {
        use murmur_artifact::{InferenceConfig, InferenceDriver};

        // Registry must never be consulted for a local-source skill.
        struct PanicRegistry;
        impl Registry for PanicRegistry {
            fn resolve(&self, _: &str, _: &str) -> Result<ResolvedArtifact, RegistryError> {
                panic!("registry must not be called for a local-source skill");
            }
            fn publish(
                &self,
                _: ArtifactMeta,
                _: &[u8],
            ) -> Result<murmur_artifact::PublishResult, RegistryError> {
                unreachable!()
            }
            fn list_index(&self) -> Result<Vec<ArtifactMeta>, RegistryError> {
                unreachable!()
            }
        }

        let project = tempfile::tempdir().unwrap();
        let skill_dir = project.path().join("skills").join("my-skill");
        fs::create_dir_all(&skill_dir).unwrap();
        fs::write(skill_dir.join("skill.md"), b"# my local skill").unwrap();

        let inference = InferenceConfig {
            transport: "http".into(),
            endpoint: Some("http://localhost".into()),
            model: "claude-3-haiku".into(),
            api_key: None,
            driver: Some(InferenceDriver {
                artifact: "test-driver".into(),
                config: None,
            }),
            command: None,
            compaction: None,
            system_prompt: None,
            system_prompt_file: None,
            system_prompt_artifact: None,
            max_turns: 10,
            max_tokens: None,
            max_session_tokens: None,
        };

        let request = StageRequest {
            credentials_file: None,
            manifest_dir: project.path().to_path_buf(),
            capsule_name: "test".to_string(),
            capsule_version: "0.0.1".to_string(),
            capsule_component_bytes: Vec::new(),
            artifacts: vec![crate::types::ArtifactRequest {
                name: "my-skill".to_string(),
                version: "local".to_string(),
                runtime: ArtifactRuntime::Skill,
                source: Some("skills/my-skill".to_string()),
                on_overflow: Default::default(),
                capabilities: None,
                config: None,
            }],
            allowlisted_tools: HashSet::new(),
            lock_expectations: None,
            capability_policy: CapabilityPolicy::default(),
            inference: Some(inference),
            system_prompt_overridden: false,
            context: None,
            context_id: None,
            resume: None,
            otel_endpoint: None,
            eval_config_json: None,
            case_id: None,
            dataset_id: None,
            lifecycle: None,
            lifecycle_override: None,
            trace: None,
            workdir: None,
            bind_addr: "127.0.0.1".to_string(),
            internal_port: None,
            declared_containment_floor: murmur_artifact::ContainmentClass::Advisory,
            exports: None,
            spawn_grant: None,
            machine_tokens_per_day: None,
        };

        let staged = stage_session(Arc::new(PanicRegistry), request).unwrap();
        let installed = staged
            .workdir
            .join("tools")
            .join("my-skill")
            .join("skill.md");
        assert!(
            installed.exists(),
            "skill.md not installed at {}",
            installed.display()
        );
        assert_eq!(fs::read(&installed).unwrap(), b"# my local skill");
        // No lock artifact recorded for a local-source skill.
        assert!(staged.resolved_lock_artifacts.is_empty());
        assert_eq!(staged.installed_artifacts.len(), 1);
        assert_eq!(staged.installed_artifacts[0].version, "local");
        // MURMUR.md (written during staging) lists the skill as callable.
        let murmur_md = fs::read_to_string(staged.workdir.join("MURMUR.md")).unwrap();
        assert!(
            murmur_md.contains("**my-skill**"),
            "MURMUR.md missing skill listing:\n{murmur_md}"
        );
        assert!(
            murmur_md.contains("call by name to load guidance"),
            "MURMUR.md missing callable skill hint:\n{murmur_md}"
        );
    }

    // ── manage.pull() ──────────────────────────────────────────────────────────

    fn zip_with_files(files: &[(&str, &[u8])]) -> Vec<u8> {
        use std::io::Write as _;
        let mut cursor = std::io::Cursor::new(Vec::<u8>::new());
        {
            let mut zip = zip::ZipWriter::new(&mut cursor);
            let options = zip::write::SimpleFileOptions::default();
            for (name, bytes) in files {
                zip.start_file(*name, options).unwrap();
                zip.write_all(bytes).unwrap();
            }
            zip.finish().unwrap();
        }
        cursor.into_inner()
    }

    fn build_test_state(
        registry: Arc<dyn Registry>,
        workdir: PathBuf,
        lock_path: PathBuf,
    ) -> CapsuleStoreState {
        let engine = build_engine().unwrap();
        let wasi = build_wasi_ctx(
            &workdir,
            None,
            None,
            None,
            &[],
            &CapabilityPolicy::default(),
        )
        .unwrap();
        CapsuleStoreState {
            limits: crate::limits::ExecutionLimits::default().limiter(),
            table: ResourceTable::new(),
            wasi,
            http: WasiHttpCtx::new(),
            http_hooks: NetworkPolicyHooks {
                network_allow_rules: Vec::new(),
                inference_gateway: None,
            },
            network_allow_rules: Vec::new(),
            peer_fetch_rules: Vec::new(),
            peer_plane: None,
            peer_own_audience: String::new(),
            peer_trace: None,
            plan_trace: None,
            plan_counter: AtomicU64::new(0),
            delegation: None,
            inference_env: Vec::new(),
            inference_gateway: None,
            spend: Arc::new(SpendMeter::unlimited()),
            engine,
            workdir: workdir.clone(),
            accessible_workdir: workdir,
            tool_components: HashMap::new(),
            artifact_grants: HashMap::new(),
            allowlisted_tools: HashSet::new(),
            installed_artifacts: Vec::new(),
            session_id: "ses_test".to_string(),
            pending_a2a_events: Vec::new(),
            capability_policy: CapabilityPolicy::default(),
            protected_paths: ProtectedPaths::default(),
            tool_annotations: ToolAnnotationMap::default(),
            shell_enforcement: sandbox::ShellEnforcement::environment_only(),
            current_traceparent: None,
            current_task_provenance: None,
            current_context_id: None,
            live_delegations: Arc::new(crate::cancel::LiveDelegations::new()),
            detached: None,
            shell_grace_secs: 0,
            a2a_task_registry: None,
            a2a_sse: None,
            a2a_task_id: None,
            input_timeout_secs: None,
            a2a_chunk_event_id: Arc::new(AtomicU64::new(0)),
            a2a_chunks_emitted: Arc::new(AtomicBool::new(false)),
            registry,
            lock_path,
            driver_continuation_id: None,
            driver_continuation_context_id: None,
            driver_continuation_acked_len: 0,
        }
    }

    // ── Driver continuation bookkeeping on CapsuleStoreState ─────────────

    fn continuation_test_state() -> CapsuleStoreState {
        let dir = tempfile::tempdir().unwrap();
        let workdir = dir.path().to_path_buf();
        let lock_path = workdir.join("murmur.lock");
        // Registry/workdir are irrelevant to continuation bookkeeping; reuse the helper.
        build_test_state(
            Arc::new(FakeSkillRegistry::new(Vec::new())),
            workdir,
            lock_path,
        )
    }

    #[test]
    fn continuation_default_is_none_and_active_query_returns_none() {
        let state = continuation_test_state();
        assert!(state.driver_continuation_id.is_none());
        assert!(state.active_continuation(Some("ctx-a")).is_none());
        assert!(state.active_continuation(None).is_none());
    }

    #[test]
    fn continuation_record_then_active_requires_matching_context() {
        // Scenario 6: a held continuation is only reused under the same context_id.
        let mut state = continuation_test_state();
        state.record_continuation("cont-1".into(), Some("ctx-a".into()), 2);

        assert_eq!(
            state.active_continuation(Some("ctx-a")),
            Some(("cont-1", 2)),
            "same context → continuation is active"
        );
        assert!(
            state.active_continuation(Some("ctx-b")).is_none(),
            "different context → continuation must not be reused"
        );
        assert!(
            state.active_continuation(None).is_none(),
            "absent context → continuation must not be reused"
        );
    }

    #[test]
    fn continuation_clear_drops_all_bookkeeping() {
        // Scenarios 3 & 5: driver silence / replace-context commit drops the held id.
        let mut state = continuation_test_state();
        state.record_continuation("cont-1".into(), Some("ctx-a".into()), 5);
        state.clear_continuation();
        assert!(state.driver_continuation_id.is_none());
        assert_eq!(state.driver_continuation_acked_len, 0);
        assert!(state.active_continuation(Some("ctx-a")).is_none());
    }

    #[test]
    fn advance_acked_len_only_affects_same_context_held_continuation() {
        // Scenario 7: end_turn persists an assistant message the driver already knows; the
        // acked length advances so the next same-context Task wires only its new user message.
        let mut state = continuation_test_state();
        state.record_continuation("cont-1".into(), Some("ctx-a".into()), 1);

        state.advance_continuation_acked_len(Some("ctx-b"), 9);
        assert_eq!(
            state.driver_continuation_acked_len, 1,
            "advancing under a different context must be a no-op"
        );

        state.advance_continuation_acked_len(Some("ctx-a"), 2);
        assert_eq!(
            state.active_continuation(Some("ctx-a")),
            Some(("cont-1", 2))
        );

        state.clear_continuation();
        state.advance_continuation_acked_len(Some("ctx-a"), 7);
        assert_eq!(
            state.driver_continuation_acked_len, 0,
            "advancing with no held continuation must be a no-op"
        );
    }

    struct FakeSkillRegistry {
        bytes: Vec<u8>,
        sha256: String,
    }

    impl FakeSkillRegistry {
        fn new(bytes: Vec<u8>) -> Self {
            let sha256 = murmur_artifact::sha256_hex(&bytes);
            Self { bytes, sha256 }
        }
    }

    impl Registry for FakeSkillRegistry {
        fn resolve(&self, name: &str, version: &str) -> Result<ResolvedArtifact, RegistryError> {
            Ok(ResolvedArtifact {
                meta: ArtifactMeta {
                    name: name.to_string(),
                    version: version.to_string(),
                    runtime: RuntimeType::Static,
                    artifact_runtime: "skill".to_string(),
                    platforms: Vec::new(),
                    description: None,
                    tags: Vec::new(),
                    wit_contracts: None,
                },
                bytes: self.bytes.clone().into(),
                sha256: self.sha256.clone(),
                platform_match: murmur_artifact::PlatformMatch::NotApplicable,
            })
        }

        fn publish(
            &self,
            _meta: ArtifactMeta,
            _bytes: &[u8],
        ) -> Result<murmur_artifact::PublishResult, RegistryError> {
            unreachable!()
        }

        fn list_index(&self) -> Result<Vec<ArtifactMeta>, RegistryError> {
            unreachable!()
        }
    }

    #[test]
    fn pull_happy_path_installs_artifact_and_updates_lock() {
        let artifact_bytes = zip_with_files(&[
            (
                PACKED_MANIFEST_ENTRY,
                b"name: my-skill\nversion: 1.0.0\nruntime: skill\n",
            ),
            ("skill.md", b"# guidance"),
        ]);
        let registry = Arc::new(FakeSkillRegistry::new(artifact_bytes));
        let expected_sha256 = registry.sha256.clone();

        let project = tempfile::tempdir().unwrap();
        let workdir = project.path().join("workdir");
        fs::create_dir_all(&workdir).unwrap();
        let lock_path = project.path().join("murmur.lock");

        let mut state = build_test_state(registry, workdir.clone(), lock_path.clone());

        let summary = manage::Host::pull(&mut state, "my-skill".to_string(), "1.0.0".to_string())
            .expect("pull should succeed");
        assert_eq!(summary.name, "my-skill");
        assert_eq!(summary.version, "1.0.0");

        let installed_skill_md = workdir.join("tools").join("my-skill").join("skill.md");
        assert!(installed_skill_md.exists());
        assert_eq!(fs::read(&installed_skill_md).unwrap(), b"# guidance");

        assert!(state
            .installed_artifacts
            .iter()
            .any(|a| a.name == "my-skill" && a.version == "1.0.0"));

        let lock = read_lockfile(&lock_path).expect("murmur.lock should have been written");
        let entry = lock
            .artifact_for("my-skill")
            .expect("lock entry for my-skill");
        assert_eq!(entry.resolved_version, "1.0.0");
        assert_eq!(entry.sha256.any.as_deref().unwrap(), expected_sha256);
    }

    /// A mid-session `manage.pull()` lands on disk but does not reach the wire: the agent loop
    /// holds one tool inventory for the whole session precisely so a pull cannot reorder or grow
    /// the tool array that is part of the provider's cached prompt prefix.
    #[test]
    fn pull_does_not_refresh_the_held_tool_inventory() {
        let artifact_bytes = zip_with_files(&[
            (
                PACKED_MANIFEST_ENTRY,
                b"name: aaa-late-skill\nversion: 1.0.0\nruntime: skill\n",
            ),
            ("skill.md", b"# guidance"),
        ]);
        let registry = Arc::new(FakeSkillRegistry::new(artifact_bytes));

        let project = tempfile::tempdir().unwrap();
        let workdir = project.path().join("workdir");
        // One tool already installed at launch. The pulled artifact sorts before it, so a
        // refreshed inventory would not merely append — it would shift the whole array.
        let existing = workdir.join("tools").join("zzz-existing-tool");
        fs::create_dir_all(&existing).unwrap();
        fs::write(
            existing.join(PACKED_MANIFEST_ENTRY),
            "name: zzz-existing-tool\nversion: 1.0.0\nruntime: tool\n",
        )
        .unwrap();
        let lock_path = project.path().join("murmur.lock");

        let mut state = build_test_state(registry, workdir.clone(), lock_path);

        // What run_agent_loop does once, before the turn loop.
        let snapshot = crate::agent::inventory::build_tool_inventory(&workdir, None);
        assert_eq!(snapshot.len(), 1);

        manage::Host::pull(
            &mut state,
            "aaa-late-skill".to_string(),
            "1.0.0".to_string(),
        )
        .expect("pull should succeed");

        // (a) The held snapshot is untouched by the pull.
        assert_eq!(snapshot.len(), 1);
        assert_eq!(snapshot[0]["name"], "zzz-existing-tool");

        // (b) Every payload built from it still carries exactly that array.
        let payload = crate::agent::build_driver_payload(
            "m",
            8192,
            &[serde_json::json!({"role": "user", "content": []})],
            &snapshot,
            "sys",
            None,
            Some("cap:1.0.0"),
        );
        assert_eq!(payload["tools"], serde_json::json!(snapshot));

        // (c) The pull really did land: a fresh build sees it, and sorts it first.
        let fresh = crate::agent::inventory::build_tool_inventory(&workdir, None);
        assert_eq!(fresh.len(), 2);
        assert_eq!(fresh[0]["name"], "aaa-late-skill");
        assert_eq!(fresh[1]["name"], "zzz-existing-tool");
    }

    #[test]
    fn pull_rejects_tampered_bytes_and_writes_nothing() {
        struct TamperedRegistry;
        impl Registry for TamperedRegistry {
            fn resolve(
                &self,
                name: &str,
                version: &str,
            ) -> Result<ResolvedArtifact, RegistryError> {
                Ok(ResolvedArtifact {
                    meta: ArtifactMeta {
                        name: name.to_string(),
                        version: version.to_string(),
                        runtime: RuntimeType::Static,
                        artifact_runtime: "skill".to_string(),
                        platforms: Vec::new(),
                        description: None,
                        tags: Vec::new(),
                        wit_contracts: None,
                    },
                    bytes: b"tampered-bytes".to_vec().into(),
                    sha256: "not-the-real-hash".to_string(),
                    platform_match: murmur_artifact::PlatformMatch::NotApplicable,
                })
            }

            fn publish(
                &self,
                _meta: ArtifactMeta,
                _bytes: &[u8],
            ) -> Result<murmur_artifact::PublishResult, RegistryError> {
                unreachable!()
            }

            fn list_index(&self) -> Result<Vec<ArtifactMeta>, RegistryError> {
                unreachable!()
            }
        }

        let project = tempfile::tempdir().unwrap();
        let workdir = project.path().join("workdir");
        fs::create_dir_all(&workdir).unwrap();
        let lock_path = project.path().join("murmur.lock");

        let mut state = build_test_state(
            Arc::new(TamperedRegistry),
            workdir.clone(),
            lock_path.clone(),
        );

        let err = manage::Host::pull(&mut state, "evil-tool".to_string(), "1.0.0".to_string())
            .expect_err("tampered bytes must be rejected");
        assert!(err.contains("integrity"), "unexpected error message: {err}");

        assert!(!workdir.join("tools").join("evil-tool").exists());
        assert!(!lock_path.exists());
        assert!(state.installed_artifacts.is_empty());
    }

    #[test]
    fn pull_rejects_lock_conflict_and_writes_nothing() {
        let artifact_bytes = zip_with_files(&[
            (
                PACKED_MANIFEST_ENTRY,
                b"name: my-skill\nversion: 2.0.0\nruntime: skill\n",
            ),
            ("skill.md", b"# guidance v2"),
        ]);
        let registry = Arc::new(FakeSkillRegistry::new(artifact_bytes));

        let project = tempfile::tempdir().unwrap();
        let workdir = project.path().join("workdir");
        fs::create_dir_all(&workdir).unwrap();
        let lock_path = project.path().join("murmur.lock");

        // Pin a different version/hash for this artifact ahead of time.
        write_lockfile_atomic(
            &lock_path,
            &MurmurLock {
                lock_version: LOCK_VERSION,
                artifacts: vec![LockedArtifact {
                    name: "my-skill".to_string(),
                    resolved_version: "1.0.0".to_string(),
                    sha256: LockedSha256::any("pinned-hash-from-earlier-pull".to_string()),
                }],
            },
        )
        .unwrap();

        let mut state = build_test_state(registry, workdir.clone(), lock_path.clone());

        let err = manage::Host::pull(&mut state, "my-skill".to_string(), "2.0.0".to_string())
            .expect_err("lock conflict must be rejected");
        assert!(
            err.contains("murmur.lock conflict"),
            "unexpected error message: {err}"
        );

        assert!(!workdir
            .join("tools")
            .join("my-skill")
            .join("skill.md")
            .exists());
        assert!(state.installed_artifacts.is_empty());

        // Lock must be left exactly as it was.
        let lock = read_lockfile(&lock_path).unwrap();
        let entry = lock.artifact_for("my-skill").unwrap();
        assert_eq!(entry.resolved_version, "1.0.0");
        assert_eq!(
            entry.sha256.any.as_deref().unwrap(),
            "pinned-hash-from-earlier-pull"
        );
    }

    /// Writes an executable shell script native-tool fixture that echoes the given env
    /// var names (space-separated `NAME=value`, empty string for an unset var) into the
    /// `data` field of a passing ToolResult JSON payload on stdout.
    fn write_env_echo_native_tool(dir: &Path, name: &str, env_vars: &[&str]) -> std::path::PathBuf {
        use std::os::unix::fs::PermissionsExt;

        let script_path = dir.join(name);
        let echoes: String = env_vars
            .iter()
            .map(|var| format!(r#"echo -n "{var}=${var} ""#))
            .collect::<Vec<_>>()
            .join("\n");
        let script = format!(
            "#!/bin/sh\ncat >/dev/null\nprintf '{{\"status\":\"passed\",\"data\":\"'\n{echoes}\nprintf '\"}}'\n"
        );
        fs::write(&script_path, script).unwrap();
        fs::set_permissions(&script_path, fs::Permissions::from_mode(0o755)).unwrap();
        script_path
    }

    /// A plan `shell` step and the equivalent direct shell tool call are shown the decision
    /// point the same way, so a command refused as one is refused as the other.
    ///
    /// The two resolvers are separate because the two forms are: a tool call carries a `command`
    /// string the runtime always hands to the interpreter as `-c`, a plan step carries a whole
    /// argv the scheduler execs directly. What must agree is the value the checks read — the
    /// binary, the argv, and the `-c` body whose redirections are live.
    #[test]
    fn a_plan_shell_step_resolves_as_the_equivalent_shell_tool_call_does() {
        let tmp = TempDir::new().unwrap();
        let policy = CapabilityPolicy {
            shell_allow: vec!["bash".to_string()],
            ..CapabilityPolicy::default()
        };

        let direct = resolve_shell_call(
            "bash",
            &murmur::tool::run::ToolInput {
                data: Some(r#"{"command":"printf x > out.txt"}"#.to_string()),
                log_path: None,
            },
            tmp.path(),
            &policy,
        )
        .expect("a declared binary with a usable command resolves");

        let step = GatedStepCall::Shell {
            binary: "bash".to_string(),
            command: "bash -c 'printf x > out.txt'".to_string(),
            argv: vec!["-c".to_string(), "printf x > out.txt".to_string()],
        }
        .resolve(tmp.path());

        let ResolvedCall::Shell {
            binary,
            argv,
            script,
            ..
        } = step
        else {
            panic!("a shell step resolves to a shell call");
        };
        assert_eq!(binary, direct.binary);
        assert_eq!(argv, direct.argv);
        assert_eq!(script, direct.script);
    }

    /// The wiring the shell-event fix depends on: `dispatch_shell_tool` carries the resolved
    /// binary out of `execute_shell` and into `ShellDispatchInfo`, which is the only channel
    /// by which `agent.rs` can put it on the hook event and the trace record. `command` keeps
    /// its pre-existing meaning — the argument list alone, never the binary name.
    #[test]
    fn dispatch_shell_tool_reports_the_invoked_binary_separately_from_the_command() {
        let tmp = TempDir::new().unwrap();
        let policy = CapabilityPolicy {
            shell_allow: vec!["bash".to_string()],
            ..CapabilityPolicy::default()
        };

        let outcome = dispatch_shell_tool(
            "bash",
            murmur::tool::run::ToolInput {
                data: Some(r#"{"command":"echo hi"}"#.to_string()),
                log_path: None,
            },
            tmp.path(),
            tmp.path(),
            &[],
            &policy,
            &sandbox::ShellEnforcement::environment_only(),
            None,
        );

        let shell = outcome
            .shell
            .expect("a successful shell call reports itself");
        assert!(
            Path::new(&shell.binary).is_absolute() && shell.binary.ends_with("bash"),
            "binary must be the resolved path of what ran, got {:?}",
            shell.binary
        );
        assert_eq!(
            shell.command, "echo hi",
            "command must still carry only the argument list"
        );
        assert_eq!(shell.exit_code, 0);
    }

    /// The `$ ` line is a command line, so for a non-interpreter it carries the binary the
    /// model was told to omit from `command`. The name printed is the declared short name and
    /// not `ShellResult::binary`, which is the resolved path.
    #[test]
    fn shell_tool_result_names_the_binary_a_non_interpreter_call_ran() {
        let tmp = TempDir::new().unwrap();
        let policy = CapabilityPolicy {
            shell_allow: vec!["ls".to_string()],
            ..CapabilityPolicy::default()
        };

        let outcome = dispatch_shell_tool(
            "ls",
            murmur::tool::run::ToolInput {
                data: Some(r#"{"command":"-d ."}"#.to_string()),
                log_path: None,
            },
            tmp.path(),
            tmp.path(),
            &[],
            &policy,
            &sandbox::ShellEnforcement::environment_only(),
            None,
        );

        let data = outcome.result.data.expect("a finished call renders text");
        let first = data.lines().next().expect("the text opens with the $ line");
        assert_eq!(first, "$ ls -d .");
        assert!(
            !first.starts_with("$ /"),
            "the resolved path must not reach the $ line, got {first:?}"
        );
        let printed_binary = first
            .strip_prefix("$ ")
            .and_then(|rest| rest.split_whitespace().next())
            .expect("the $ line names a binary");
        assert!(
            !printed_binary.contains('/'),
            "the $ line names the declared short name, got {printed_binary:?}"
        );
    }

    /// An interpreter's `command` is a whole shell line already, so it stands alone: `$ bash
    /// echo hi` would read as bash invoked with `echo` as its script argument, which is not
    /// what ran.
    #[test]
    fn shell_tool_result_leaves_an_interpreter_command_line_alone() {
        let tmp = TempDir::new().unwrap();
        let policy = CapabilityPolicy {
            shell_allow: vec!["bash".to_string()],
            ..CapabilityPolicy::default()
        };

        let outcome = dispatch_shell_tool(
            "bash",
            murmur::tool::run::ToolInput {
                data: Some(r#"{"command":"echo hi"}"#.to_string()),
                log_path: None,
            },
            tmp.path(),
            tmp.path(),
            &[],
            &policy,
            &sandbox::ShellEnforcement::environment_only(),
            None,
        );

        let data = outcome.result.data.expect("a finished call renders text");
        let first = data.lines().next().expect("the text opens with the $ line");
        assert_eq!(first, "$ echo hi");
    }

    /// The argv a policy hook decides on and the argv the spawn receives come from one
    /// resolution, not two: `resolve_shell_call` is what `dispatch_shell_tool` uses, so a
    /// drift between the approved call and the executed one is not expressible.
    #[test]
    fn resolve_shell_call_and_dispatch_shell_tool_agree_on_argv() {
        let tmp = TempDir::new().unwrap();
        let policy = CapabilityPolicy {
            shell_allow: vec!["bash".to_string()],
            ..CapabilityPolicy::default()
        };
        let input = murmur::tool::run::ToolInput {
            data: Some(r#"{"command":"echo one 'two three'"}"#.to_string()),
            log_path: None,
        };

        let resolved =
            resolve_shell_call("bash", &input, tmp.path(), &policy).expect("bash resolves");
        let outcome = dispatch_shell_tool(
            "bash",
            input,
            tmp.path(),
            tmp.path(),
            &[],
            &policy,
            &sandbox::ShellEnforcement::environment_only(),
            None,
        );

        let shell = outcome
            .shell
            .expect("a successful shell call reports itself");
        assert_eq!(resolved.argv, shell.argv);
        assert_eq!(resolved.script, shell.script);
        assert_eq!(
            resolved.argv,
            vec!["-c".to_string(), "echo one 'two three'".to_string()],
            "an interpreter takes the whole command as one -c body"
        );
    }

    /// A non-interpreter binary is word-split and carries no script.
    #[test]
    fn resolve_shell_call_splits_a_non_interpreter_and_reports_no_script() {
        let tmp = TempDir::new().unwrap();
        let policy = CapabilityPolicy {
            shell_allow: vec!["curl".to_string()],
            ..CapabilityPolicy::default()
        };
        let resolved = resolve_shell_call(
            "curl",
            &murmur::tool::run::ToolInput {
                data: Some(r#"{"command":"-s http://example.com"}"#.to_string()),
                log_path: None,
            },
            tmp.path(),
            &policy,
        )
        .expect("curl resolves");

        assert_eq!(resolved.argv, vec!["-s", "http://example.com"]);
        assert_eq!(resolved.script, None);
    }

    /// Nothing resolves for a name the manifest never declared, and nothing resolves for input
    /// carrying no command — the two cases that make the decision point see a tool call rather
    /// than a shell call.
    #[test]
    fn resolve_shell_call_declines_an_undeclared_binary_and_unusable_input() {
        let tmp = TempDir::new().unwrap();
        let policy = CapabilityPolicy {
            shell_allow: vec!["bash".to_string()],
            ..CapabilityPolicy::default()
        };
        assert!(resolve_shell_call(
            "curl",
            &murmur::tool::run::ToolInput {
                data: Some(r#"{"command":"--version"}"#.to_string()),
                log_path: None,
            },
            tmp.path(),
            &policy,
        )
        .is_none());
        assert!(resolve_shell_call(
            "bash",
            &murmur::tool::run::ToolInput {
                data: Some(r#"{"nope":1}"#.to_string()),
                log_path: None,
            },
            tmp.path(),
            &policy,
        )
        .is_none());
    }

    /// One resolution feeds the policy decision and the spawn for a recipe invocation too: the
    /// body the hook is shown arrives without moving the argv the executable receives.
    #[test]
    fn resolve_shell_call_and_dispatch_shell_tool_agree_on_a_recipe_invocation() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("justfile"),
            "build:\n  echo RECIPE-BODY-MARKER\n",
        )
        .unwrap();
        let policy = CapabilityPolicy {
            shell_allow: vec!["just".to_string()],
            ..CapabilityPolicy::default()
        };
        let input = murmur::tool::run::ToolInput {
            data: Some(r#"{"command":"build"}"#.to_string()),
            log_path: None,
        };

        let resolved =
            resolve_shell_call("just", &input, tmp.path(), &policy).expect("just resolves");
        let outcome = dispatch_shell_tool(
            "just",
            input,
            tmp.path(),
            tmp.path(),
            &[],
            &policy,
            &sandbox::ShellEnforcement::environment_only(),
            None,
        );

        assert_eq!(
            resolved.recipe.as_deref(),
            Some("echo RECIPE-BODY-MARKER"),
            "the recipe body is read out of the workdir"
        );
        assert_eq!(
            resolved.argv,
            vec!["build".to_string()],
            "resolving a recipe does not move the argv"
        );
        // `just` need not exist on the host: what the resolution produced is the assertion, and
        // a spawn that fails still carries the argv it was given.
        if let Some(shell) = outcome.shell {
            assert_eq!(resolved.argv, shell.argv);
            assert_eq!(resolved.script, shell.script);
            assert_eq!(resolved.recipe, shell.recipe);
        }
    }

    /// The dispatch-layer half of the composed-root failure path: a sealed session whose root
    /// could not be built does not come back as an ordinary failed tool call the capsule gets
    /// another turn to react to. The tool result is still filled in (so the trace records the
    /// attempt), but `fatal` carries the typed `RuntimeError` the agent turn loop returns and
    /// the CLI renders as `E-RUN-014`.
    ///
    /// Linux-only because the forced-failure seam lives in the Linux `pre_exec` path; the
    /// mechanism it stands in for is Linux-only too.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_sealed_composed_root_failure_ends_the_session_not_just_the_tool_call() {
        if crate::network_namespace::skip_without_egress_namespace(
            "a_sealed_composed_root_failure_ends_the_session_not_just_the_tool_call",
        ) {
            return;
        }
        let tmp = TempDir::new().unwrap();
        let policy = CapabilityPolicy {
            shell_allow: vec!["bash".to_string()],
            ..CapabilityPolicy::default()
        };

        let _guard = sandbox::ForceSealedRootFailureGuard::new();
        let outcome = dispatch_shell_tool(
            "bash",
            murmur::tool::run::ToolInput {
                data: Some(r#"{"command":"echo hi"}"#.to_string()),
                log_path: None,
            },
            tmp.path(),
            tmp.path(),
            &[],
            &policy,
            &sandbox::sealed_test_enforcement(),
            None,
        );

        assert!(
            matches!(outcome.result.status, murmur::tool::run::Status::Error),
            "the failed call must still read as a failed call"
        );
        let data = outcome.result.data.as_deref().unwrap_or_default();
        assert!(
            data.contains("composed root"),
            "the tool result must still say what happened: {data}"
        );
        let fatal = outcome
            .fatal
            .expect("a composed-root failure must be carried out as session-fatal");
        assert!(
            matches!(fatal, RuntimeError::SealedRootConstructionFailed { .. }),
            "must be the variant murmur-cli maps to E-RUN-014: {fatal}"
        );
    }

    /// The contrast: an ordinary shell failure leaves `fatal` unset, so the capsule keeps its
    /// turn. Without this, "always fatal" would pass the test above.
    #[test]
    fn an_ordinary_shell_failure_leaves_the_session_running() {
        let tmp = TempDir::new().unwrap();
        let outcome = dispatch_shell_tool(
            "bash",
            murmur::tool::run::ToolInput {
                data: Some(r#"{"command":"echo hi"}"#.to_string()),
                log_path: None,
            },
            tmp.path(),
            tmp.path(),
            &[],
            // Empty allowlist: `execute_shell` refuses before spawning anything.
            &CapabilityPolicy::default(),
            &sandbox::ShellEnforcement::environment_only(),
            None,
        );

        assert!(matches!(
            outcome.result.status,
            murmur::tool::run::Status::Error
        ));
        assert!(
            outcome.fatal.is_none(),
            "a disallowed binary is the capsule's problem, not the session's"
        );
    }

    // ── the tool-result fence ───────────────────────────────────────────────

    fn tool_result_with(
        data: Option<&str>,
        summary: Option<&str>,
    ) -> murmur::tool::run::ToolResult {
        murmur::tool::run::ToolResult {
            status: murmur::tool::run::Status::Passed,
            summary: summary.map(str::to_string),
            data: data.map(str::to_string),
            data_path: None,
            truncated: false,
            metadata: Vec::new(),
        }
    }

    /// Every shape a dispatch branch can hand back — data, summary only, neither — is fenced
    /// once. A second application anywhere would show up here as a second marker pair.
    #[test]
    fn fence_wraps_each_dispatch_result_shape_exactly_once() {
        let shapes = [
            tool_result_with(Some("stdout line"), Some("ran ok")),
            tool_result_with(Some("stdout line"), None),
            tool_result_with(None, Some("ran ok")),
            tool_result_with(None, None),
        ];
        for mut result in shapes {
            fence_tool_result("web-fetch", &mut result);
            let text = result.data.expect("the fenced text lands in data");
            assert_eq!(
                text.matches("<untrusted-content source=tool:web-fetch>")
                    .count(),
                1,
                "exactly one opening marker: {text}"
            );
            assert_eq!(
                text.matches(crate::fence::FENCE_CLOSE).count(),
                1,
                "exactly one closing marker: {text}"
            );
        }
    }

    /// The reduction happens inside the dispatcher, so the `data.or(summary)` both model-facing
    /// callers write has nothing unfenced left to fall back to.
    #[test]
    fn fence_moves_a_summary_only_result_into_fenced_data() {
        let mut result = tool_result_with(None, Some("ran ok"));
        fence_tool_result("probe", &mut result);
        assert_eq!(
            result.data.as_deref(),
            Some("<untrusted-content source=tool:probe>\nran ok\n</untrusted-content>")
        );
        assert!(
            result.summary.is_none(),
            "no unfenced text may survive on the outcome"
        );
    }

    /// A dispatch that produced nothing still reaches the model as a fenced block, so "the tool
    /// said nothing" is not the one result that reads as the runtime's own voice.
    #[test]
    fn fence_wraps_the_empty_dispatch_result_too() {
        let mut result = tool_result_with(None, None);
        fence_tool_result("probe", &mut result);
        assert_eq!(
            result.data.as_deref(),
            Some(
                "<untrusted-content source=tool:probe>\ntool returned no data\n</untrusted-content>"
            )
        );
    }

    /// The fields the fence does not touch: everything the tool declared *about* the call, as
    /// opposed to the content shown to the model.
    #[test]
    fn fence_leaves_the_declarative_tool_result_fields_alone() {
        let mut result = murmur::tool::run::ToolResult {
            status: murmur::tool::run::Status::Error,
            summary: Some("failed".to_string()),
            data: Some("boom".to_string()),
            data_path: Some("out/log.txt".to_string()),
            truncated: true,
            metadata: vec![("state_effect".to_string(), "read".to_string())],
        };
        fence_tool_result("probe", &mut result);
        assert!(matches!(result.status, murmur::tool::run::Status::Error));
        assert_eq!(result.data_path.as_deref(), Some("out/log.txt"));
        assert!(result.truncated);
        assert_eq!(result.metadata.len(), 1);
    }

    /// The composed path, on real inputs and a real file: dispatch a real shell tool, then
    /// hand its `ShellDispatchInfo` to a real `TraceWriter` exactly as `agent.rs` does, and
    /// read the resulting `workdir/trace.jsonl` back. This is the automated stand-in for
    /// eyeballing a session's trace after `mur run` — the two lines it mirrors in `agent.rs`
    /// are a straight field pass-through, but the JSONL key and its value are pinned here.
    #[test]
    fn shell_dispatch_writes_the_resolved_binary_into_trace_jsonl() {
        let tmp = TempDir::new().unwrap();
        let workdir = tmp.path().to_path_buf();
        let policy = CapabilityPolicy {
            shell_allow: vec!["bash".to_string()],
            ..CapabilityPolicy::default()
        };

        let rt = tokio::runtime::Runtime::new().unwrap();
        let events: Vec<serde_json::Value> = rt.block_on(async {
            let outcome = dispatch_shell_tool(
                "bash",
                murmur::tool::run::ToolInput {
                    data: Some(r#"{"command":"echo hi"}"#.to_string()),
                    log_path: None,
                },
                &workdir,
                &workdir,
                &[],
                &policy,
                &sandbox::ShellEnforcement::environment_only(),
                None,
            );
            let shell = outcome.shell.expect("the shell call reports itself");

            let mut trace = TraceWriter::open(
                &workdir,
                "ses_test".to_string(),
                "cap".to_string(),
                "0.1.0".to_string(),
                "test-model".to_string(),
                Vec::new(),
                crate::containment::scope_report_for_tier(
                    &policy,
                    murmur_artifact::ContainmentClass::Advisory,
                    sandbox::EnforcementTier::EnvironmentOnly,
                    None,
                    None,
                    None,
                    Vec::new(),
                    Vec::new(),
                    Vec::new(),
                    crate::cgroup::IoMaxReport::default(),
                ),
                murmur_artifact::TraceCapture::Meta,
                None,
                false,
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();
            trace
                .write_shell(
                    1,
                    shell.binary.clone(),
                    shell.command.clone(),
                    shell.exit_code,
                    shell.stdout_bytes,
                    shell.stderr_bytes,
                    shell.duration_ms,
                    shell.resource_limit.clone(),
                )
                .await
                .unwrap();
            trace.flush().await.unwrap();

            fs::read_to_string(workdir.join("trace.jsonl"))
                .unwrap()
                .lines()
                .filter(|l| !l.is_empty())
                .map(|l| serde_json::from_str(l).unwrap())
                .collect()
        });

        let shell_event = events
            .iter()
            .find(|e| e["event_type"] == "shell")
            .expect("trace.jsonl must carry a shell event");
        let binary = shell_event["binary"]
            .as_str()
            .expect("the shell event must carry a `binary` string");
        assert!(
            Path::new(binary).is_absolute() && binary.ends_with("bash"),
            "trace.jsonl's binary must be the resolved absolute path of what ran, got {binary:?}"
        );
        assert_eq!(shell_event["command"], "echo hi");
    }

    #[test]
    fn dispatch_native_tool_gets_synthetic_home_matching_execute_shell() {
        let tmp = TempDir::new().unwrap();
        let binary = write_env_echo_native_tool(tmp.path(), "echo-home", &["HOME"]);
        let policy = CapabilityPolicy::default();

        let result = dispatch_native_tool(
            "echo-home",
            murmur::tool::run::ToolInput {
                data: None,
                log_path: None,
            },
            &binary,
            tmp.path(),
            tmp.path(),
            &policy,
            &sandbox::ShellEnforcement::environment_only(),
        )
        .unwrap();

        let expected_home = tmp.path().join(".capsule-home");
        let data = result.data.unwrap_or_default();
        assert!(
            data.contains(&format!("HOME={}", expected_home.display())),
            "expected synthetic HOME in native tool output, got: {data}"
        );
        assert!(expected_home.is_dir());
    }

    #[test]
    fn dispatch_native_tool_strips_credential_shaped_var() {
        let tmp = TempDir::new().unwrap();
        let binary = write_env_echo_native_tool(tmp.path(), "echo-token", &["GITHUB_TOKEN"]);
        let policy = CapabilityPolicy::default();

        std::env::set_var("GITHUB_TOKEN", "leaked-token");
        let result = dispatch_native_tool(
            "echo-token",
            murmur::tool::run::ToolInput {
                data: None,
                log_path: None,
            },
            &binary,
            tmp.path(),
            tmp.path(),
            &policy,
            &sandbox::ShellEnforcement::environment_only(),
        )
        .unwrap();
        std::env::remove_var("GITHUB_TOKEN");

        let data = result.data.unwrap_or_default();
        assert!(
            !data.contains("leaked-token"),
            "GITHUB_TOKEN must not reach a native tool subprocess, got: {data}"
        );
    }

    #[test]
    fn dispatch_native_tool_strips_wildcard_credential_pattern() {
        let tmp = TempDir::new().unwrap();
        let binary = write_env_echo_native_tool(tmp.path(), "echo-stripe", &["STRIPE_API_KEY"]);
        let policy = CapabilityPolicy::default();

        std::env::set_var("STRIPE_API_KEY", "leaked-key");
        let result = dispatch_native_tool(
            "echo-stripe",
            murmur::tool::run::ToolInput {
                data: None,
                log_path: None,
            },
            &binary,
            tmp.path(),
            tmp.path(),
            &policy,
            &sandbox::ShellEnforcement::environment_only(),
        )
        .unwrap();
        std::env::remove_var("STRIPE_API_KEY");

        let data = result.data.unwrap_or_default();
        assert!(
            !data.contains("leaked-key"),
            "*_API_KEY wildcard pattern must strip STRIPE_API_KEY from native tool subprocess, got: {data}"
        );
    }

    #[test]
    fn dispatch_native_tool_keeps_safe_baseline_var() {
        let tmp = TempDir::new().unwrap();
        let binary = write_env_echo_native_tool(tmp.path(), "echo-cargo-home", &["CARGO_HOME"]);
        let policy = CapabilityPolicy::default();

        std::env::set_var("CARGO_HOME", "/fake/cargo/home");
        let result = dispatch_native_tool(
            "echo-cargo-home",
            murmur::tool::run::ToolInput {
                data: None,
                log_path: None,
            },
            &binary,
            tmp.path(),
            tmp.path(),
            &policy,
            &sandbox::ShellEnforcement::environment_only(),
        )
        .unwrap();
        std::env::remove_var("CARGO_HOME");

        let data = result.data.unwrap_or_default();
        assert!(
            data.contains("CARGO_HOME=/fake/cargo/home"),
            "safe baseline var CARGO_HOME must pass through to native tool subprocess, got: {data}"
        );
    }

    #[test]
    fn dispatch_native_tool_composes_policy_strip_env() {
        let tmp = TempDir::new().unwrap();
        let binary =
            write_env_echo_native_tool(tmp.path(), "echo-mycompany", &["MYCOMPANY_SECRET"]);
        let policy = CapabilityPolicy {
            shell_strip_env: vec!["MYCOMPANY_*".to_string()],
            ..CapabilityPolicy::default()
        };

        std::env::set_var("MYCOMPANY_SECRET", "leaked-secret");
        let result = dispatch_native_tool(
            "echo-mycompany",
            murmur::tool::run::ToolInput {
                data: None,
                log_path: None,
            },
            &binary,
            tmp.path(),
            tmp.path(),
            &policy,
            &sandbox::ShellEnforcement::environment_only(),
        )
        .unwrap();
        std::env::remove_var("MYCOMPANY_SECRET");

        let data = result.data.unwrap_or_default();
        assert!(
            !data.contains("leaked-secret"),
            "policy.shell_strip_env pattern must compose for native tool subprocess, got: {data}"
        );
    }

    // ── Per-artifact grant narrowing for tools and drivers ───────────────────────────

    /// The capsule ceiling the narrowing tests clamp against. Loopback ports nothing listens
    /// on, so a policy decision is observable without any connection ever completing.
    fn narrowing_ceiling() -> Vec<NetworkAllowRule> {
        parse_network_allow_rules(&[
            "http://127.0.0.1:1".to_string(),
            "http://127.0.0.1:2".to_string(),
        ])
        .unwrap()
    }

    fn grant_of(network: Option<Vec<&str>>, scope: Option<&str>) -> ToolCapabilityGrant {
        let caps = murmur_artifact::Capabilities {
            peer_fetch: None,
            network: network.map(|allow| murmur_artifact::NetworkCapabilities {
                allow: allow.into_iter().map(str::to_string).collect(),
                unix_sockets: false,
            }),
            filesystem: scope.map(|scope| murmur_artifact::FilesystemCapabilities {
                scope: Some(scope.to_string()),
                workdir_exec: false,
                read_only: Vec::new(),
            }),
            shell: None,
            spawn: None,
            env: None,
            limits: None,
            resources: None,
            state: None,
            task_io: None,
            conversation: None,
            plan: None,
            containment: None,
        };
        ToolCapabilityGrant::derive(Some(&caps), &narrowing_ceiling(), "test-capsule")
            .expect("grant is valid")
    }

    /// Push a request through the very `NetworkPolicyHooks` a tool store is built with, so
    /// the assertion is on the real wasi-http gate rather than on the rule list.
    fn send_through_tool_hooks(rules: &[NetworkAllowRule], uri: &str, use_tls: bool) -> bool {
        use http_body_util::{BodyExt, Empty};

        let mut hooks = NetworkPolicyHooks {
            network_allow_rules: rules.to_vec(),
            inference_gateway: None,
        };
        let body = Empty::<bytes::Bytes>::new()
            .map_err(|err| match err {})
            .boxed_unsync();
        let request = hyper::Request::builder()
            .uri(uri)
            .body(body)
            .expect("request builds");
        let config = wasmtime_wasi_http::p2::types::OutgoingRequestConfig {
            use_tls,
            connect_timeout: std::time::Duration::from_millis(1),
            first_byte_timeout: std::time::Duration::from_millis(1),
            between_bytes_timeout: std::time::Duration::from_millis(1),
        };

        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async { hooks.send_request(request, config).is_ok() })
    }

    fn gateway_test_config() -> wasmtime_wasi_http::p2::types::OutgoingRequestConfig {
        wasmtime_wasi_http::p2::types::OutgoingRequestConfig {
            use_tls: false,
            connect_timeout: std::time::Duration::from_millis(1),
            first_byte_timeout: std::time::Duration::from_millis(1),
            between_bytes_timeout: std::time::Duration::from_millis(1),
        }
    }

    /// A tool store that is not the configured driver's gets no gateway, so its request to the
    /// gateway authority is an ordinary allow-list-checked request — denied here — and is never
    /// rewritten or given the key.
    #[test]
    fn gateway_is_driver_only() {
        use http_body_util::{BodyExt, Empty};

        const KEY: &str = "sk-driver-only-marker";
        let gateway = Arc::new(
            InferenceGateway::new(
                "the-driver",
                "http://127.0.0.1:1",
                murmur_artifact::InferenceAuth {
                    header: "x-api-key".to_string(),
                    value: "{key}".to_string(),
                },
                Some(Arc::new(
                    InferenceCredential::resolve(&ApiKeyReference::Literal(KEY.to_string()), None)
                        .unwrap(),
                )),
                Arc::new(SpendMeter::unlimited()),
            )
            .unwrap(),
        );
        assert!(gateway_for_store(Some(&gateway), "the-driver").is_some());
        assert!(gateway_for_store(Some(&gateway), "other-tool").is_none());

        let mut hooks = NetworkPolicyHooks {
            network_allow_rules: Vec::new(),
            inference_gateway: gateway_for_store(Some(&gateway), "other-tool"),
        };
        let request = hyper::Request::builder()
            .uri("http://127.0.0.1:9/")
            .body(
                Empty::<bytes::Bytes>::new()
                    .map_err(|err| match err {})
                    .boxed_unsync(),
            )
            .unwrap();
        let rt = tokio::runtime::Runtime::new().unwrap();
        let Err(denied) = rt.block_on(async { hooks.send_request(request, gateway_test_config()) })
        else {
            panic!("a non-driver store's request to the gateway authority is denied");
        };
        assert!(matches!(
            denied.downcast_ref(),
            Some(WasiHttpErrorCode::HttpRequestDenied)
        ));
        assert!(!format!("{denied:?}").contains(KEY));
    }

    fn http_inference(endpoint: &str, api_key: Option<&str>) -> InferenceConfig {
        InferenceConfig {
            transport: "http".to_string(),
            endpoint: Some(endpoint.to_string()),
            model: "test-model".to_string(),
            api_key: api_key.map(|key| ApiKeyReference::Literal(key.to_string())),
            driver: Some(murmur_artifact::InferenceDriver {
                artifact: "the-driver".to_string(),
                config: None,
            }),
            command: None,
            compaction: None,
            system_prompt: None,
            system_prompt_file: None,
            system_prompt_artifact: None,
            max_turns: 10,
            max_tokens: None,
            max_session_tokens: None,
        }
    }

    #[test]
    fn inference_env_pairs_never_carries_the_api_key() {
        const KEY: &str = "sk-env-pairs-marker";
        let inference = http_inference("https://api.moonshot.ai/v1", Some(KEY));
        let gateway = InferenceGateway::new(
            "the-driver",
            "https://api.moonshot.ai/v1",
            murmur_artifact::InferenceAuth {
                header: "Authorization".to_string(),
                value: "Bearer {key}".to_string(),
            },
            inference
                .api_key
                .as_ref()
                .map(|reference| Arc::new(InferenceCredential::resolve(reference, None).unwrap())),
            Arc::new(SpendMeter::unlimited()),
        )
        .unwrap();
        for pairs in [
            inference_env_pairs(&inference, Some(&gateway)),
            inference_env_pairs(&inference, None),
        ] {
            assert!(pairs
                .iter()
                .all(|(name, value)| name != "MURMUR_INFERENCE_API_KEY" && !value.contains(KEY)));
        }
        let pairs = inference_env_pairs(&inference, Some(&gateway));
        assert!(pairs.contains(&(
            "MURMUR_INFERENCE_ENDPOINT".to_string(),
            "http://127.0.0.1:9/v1".to_string()
        )));
    }

    #[test]
    fn inference_endpoint_allow_entries_names_only_entries_matching_the_endpoint() {
        let allow = vec![
            "api.anthropic.com".to_string(),
            "https://api.anthropic.com".to_string(),
            "http://api.anthropic.com".to_string(),
            "example.com".to_string(),
        ];
        let inference = http_inference("https://api.anthropic.com", None);
        assert_eq!(
            inference_endpoint_allow_entries(&allow, Some(&inference)),
            vec!["api.anthropic.com", "https://api.anthropic.com"]
        );
        let process = InferenceConfig {
            transport: "process".to_string(),
            endpoint: None,
            ..inference
        };
        assert!(inference_endpoint_allow_entries(&allow, Some(&process)).is_empty());
    }

    /// The no-op invariant, network half: a tool with no per-artifact entry dispatches on the
    /// full ceiling, reaching everything the capsule may reach.
    #[test]
    fn ungranted_tool_keeps_the_whole_ceiling() {
        let ceiling = narrowing_ceiling();
        let rules = effective_tool_network_rules(None, &ceiling);

        assert!(send_through_tool_hooks(
            rules,
            "http://127.0.0.1:1/x",
            false
        ));
        assert!(send_through_tool_hooks(
            rules,
            "http://127.0.0.1:2/x",
            false
        ));
    }

    /// A narrowed tool reaches only its declared host; the ceiling's other host is gone for
    /// that artifact even though a sibling tool still reaches it.
    #[test]
    fn narrowed_tool_reaches_only_its_declared_host() {
        let ceiling = narrowing_ceiling();
        let grant = grant_of(Some(vec!["http://127.0.0.1:1"]), None);
        let narrowed = effective_tool_network_rules(Some(&grant), &ceiling);

        assert!(
            send_through_tool_hooks(narrowed, "http://127.0.0.1:1/x", false),
            "the declared host stays reachable"
        );
        assert!(
            !send_through_tool_hooks(narrowed, "http://127.0.0.1:2/x", false),
            "the rest of the ceiling is dropped for this artifact"
        );
        // The sibling with no entry is unaffected by its neighbour's narrowing.
        let sibling = effective_tool_network_rules(None, &ceiling);
        assert!(send_through_tool_hooks(
            sibling,
            "http://127.0.0.1:2/x",
            false
        ));
    }

    /// An entry outside the ceiling is dropped rather than granted, and reported so staging
    /// can raise `W-SEC-007`.
    #[test]
    fn out_of_ceiling_entry_is_dropped_and_reported() {
        let ceiling = narrowing_ceiling();
        let grant = grant_of(
            Some(vec!["http://127.0.0.1:1", "https://evil.example.com"]),
            None,
        );
        let narrowed = effective_tool_network_rules(Some(&grant), &ceiling);

        assert!(!send_through_tool_hooks(
            narrowed,
            "https://evil.example.com/x",
            true
        ));
        assert_eq!(
            grant.dropped_network_entries,
            vec!["https://evil.example.com".to_string()]
        );
    }

    /// Without a scope the preopened root is the workdir itself — observable because
    /// `preopened_dir` requires the directory to exist, so a missing workdir is an error.
    #[test]
    fn tool_without_filesystem_scope_preopens_the_workdir_itself() {
        let root = TempDir::new().unwrap();
        let missing = root.path().join("does-not-exist");

        assert!(
            build_wasi_ctx(
                &missing,
                None,
                None,
                None,
                &[],
                &CapabilityPolicy::default()
            )
            .is_err(),
            "an unscoped tool preopens the workdir, which must exist"
        );
        build_wasi_ctx(
            root.path(),
            None,
            None,
            None,
            &[],
            &CapabilityPolicy::default(),
        )
        .expect("an existing workdir preopens as before");
        assert!(
            !missing.exists(),
            "the unscoped path must not create anything"
        );
    }

    /// With a scope the preopened root is `<workdir>/<scope>`, created if absent. Sibling
    /// paths under the workdir are never mounted, so a guest has no descriptor for them.
    #[test]
    fn tool_with_filesystem_scope_preopens_only_the_scoped_subtree() {
        let root = TempDir::new().unwrap();
        std::fs::write(root.path().join("secret.txt"), b"capsule state").unwrap();

        build_wasi_ctx(
            root.path(),
            Some("cache"),
            None,
            None,
            &[],
            &CapabilityPolicy::default(),
        )
        .expect("a granted scope is created and preopened");

        let scoped = root.path().join("cache");
        assert!(scoped.is_dir(), "the granted scope is created if missing");
        std::fs::write(scoped.join("entry.json"), b"{}").unwrap();
        assert!(scoped.join("entry.json").exists());
        assert!(
            root.path().join("secret.txt").exists(),
            "nothing outside the scope was touched"
        );
    }

    /// A scope that cannot be created is a hard error naming the scope, never a silent
    /// widening back to the whole workdir.
    #[test]
    fn unusable_filesystem_scope_is_a_hard_error() {
        let root = TempDir::new().unwrap();
        // A regular file where the scope directory would go: `create_dir_all` cannot proceed.
        std::fs::write(root.path().join("cache"), b"not a directory").unwrap();

        let policy = CapabilityPolicy::default();
        let err = match build_wasi_ctx(root.path(), Some("cache"), None, None, &[], &policy) {
            Ok(_) => panic!("an uncreatable scope must fail loudly"),
            Err(err) => err,
        };
        assert!(
            err.to_string().contains("cache"),
            "the error must name the scope, got: {err}"
        );
    }

    /// End-to-end through the one dispatch body every WASM tool and the inference driver
    /// share: a real component is instantiated and called under a grant, and the scoped
    /// directory it was granted appears on the host filesystem.
    #[test]
    fn real_dispatch_applies_the_filesystem_scope() {
        let engine = build_engine().unwrap();
        let workdir = TempDir::new().unwrap();
        let component = crate::inference_import::test_support::driver_double(
            &engine,
            0,
            r#"{"stop_reason":"end_turn","content":[{"type":"text","text":"ok"}]}"#,
        );
        let ceiling = narrowing_ceiling();
        let grant = grant_of(None, Some("tool-cache"));

        let rt = tokio::runtime::Runtime::new().unwrap();
        let result = rt.block_on(async {
            invoke_tool_component(
                ToolInvokeEnv {
                    engine: &engine,
                    accessible_workdir: workdir.path(),
                    inference_env: &[],
                    capability_policy: &CapabilityPolicy::default(),
                    network_allow_rules: &ceiling,
                    artifact_grant: Some(&grant),
                    inference_gateway: None,
                },
                ToolA2aWiring::silent(),
                "scoped-tool",
                &component,
                murmur::tool::run::ToolInput {
                    data: Some("{}".to_string()),
                    log_path: None,
                },
            )
            .await
        });

        assert!(result.is_ok(), "the scoped tool still runs: {result:?}");
        assert!(
            workdir.path().join("tool-cache").is_dir(),
            "the real dispatch path preopened the granted scope"
        );
    }

    /// The same dispatch with no grant is byte-for-byte the pre-narrowing behavior: the whole
    /// accessible workdir is the preopen root and no subtree is created.
    #[test]
    fn real_dispatch_without_a_grant_is_unchanged() {
        let engine = build_engine().unwrap();
        let workdir = TempDir::new().unwrap();
        let component = crate::inference_import::test_support::driver_double(
            &engine,
            0,
            r#"{"stop_reason":"end_turn","content":[{"type":"text","text":"ok"}]}"#,
        );
        let ceiling = narrowing_ceiling();

        let rt = tokio::runtime::Runtime::new().unwrap();
        let result = rt.block_on(async {
            invoke_tool_component(
                ToolInvokeEnv {
                    engine: &engine,
                    accessible_workdir: workdir.path(),
                    inference_env: &[],
                    capability_policy: &CapabilityPolicy::default(),
                    network_allow_rules: &ceiling,
                    artifact_grant: None,
                    inference_gateway: None,
                },
                ToolA2aWiring::silent(),
                "plain-tool",
                &component,
                murmur::tool::run::ToolInput {
                    data: Some("{}".to_string()),
                    log_path: None,
                },
            )
            .await
        });

        assert!(
            result.is_ok(),
            "an ungranted tool runs as before: {result:?}"
        );
        assert_eq!(
            std::fs::read_dir(workdir.path()).unwrap().count(),
            0,
            "no per-artifact subtree is created when nothing was granted"
        );
    }

    /// Staging lowers a grant only for artifacts that declared one, and only from the
    /// operator's own entry — the map is the single source dispatch consults.
    #[test]
    fn staging_records_grants_only_for_declaring_artifacts() {
        let ceiling = narrowing_ceiling();
        let mut grants = HashMap::new();

        let declared = ArtifactRequest {
            name: "scoped-tool".to_string(),
            version: "1.0.0".to_string(),
            runtime: ArtifactRuntime::Tool,
            source: None,
            on_overflow: Default::default(),
            config: None,
            capabilities: Some(murmur_artifact::Capabilities {
                peer_fetch: None,
                network: Some(murmur_artifact::NetworkCapabilities {
                    allow: vec!["http://127.0.0.1:1".to_string()],
                    unix_sockets: false,
                }),
                filesystem: None,
                shell: None,
                spawn: None,
                env: None,
                limits: None,
                resources: None,
                state: None,
                task_io: None,
                conversation: None,
                plan: None,
                containment: None,
            }),
        };
        let silent = ArtifactRequest {
            name: "plain-tool".to_string(),
            version: "1.0.0".to_string(),
            runtime: ArtifactRuntime::Tool,
            source: None,
            on_overflow: Default::default(),
            capabilities: None,
            config: None,
        };

        stage_artifact_grant(&declared, &ceiling, "test-capsule", &mut grants).unwrap();
        stage_artifact_grant(&silent, &ceiling, "test-capsule", &mut grants).unwrap();

        assert!(grants.contains_key("scoped-tool"));
        assert!(
            !grants.contains_key("plain-tool"),
            "an artifact with no capabilities block must stay absent so dispatch falls back \
             to the ceiling"
        );
    }

    /// `config:` alone stages a grant, and that grant narrows nothing and widens nothing: every
    /// field but `config_json` equals [`ToolCapabilityGrant::default`], so the artifact keeps
    /// inheriting the capsule ceiling wholesale and simply gains one environment variable.
    ///
    /// `capabilities:` and `config:` are independent keys on one entry, so either alone has to
    /// produce an entry dispatch can find by name.
    #[test]
    fn config_alone_stages_a_grant_that_changes_nothing_else() {
        let ceiling = narrowing_ceiling();
        let mut grants = HashMap::new();

        let configured = ArtifactRequest {
            name: "config-echo".to_string(),
            version: "1.0.0".to_string(),
            runtime: ArtifactRuntime::Driver,
            source: None,
            on_overflow: Default::default(),
            capabilities: None,
            config: Some(serde_yaml::from_str("who: a\n").unwrap()),
        };

        stage_artifact_grant(&configured, &ceiling, "test-capsule", &mut grants).unwrap();

        let grant = grants
            .get("config-echo")
            .expect("config alone stages a grant");
        assert_eq!(grant.config_json.as_deref(), Some(r#"{"who":"a"}"#));
        assert_eq!(
            grant,
            &ToolCapabilityGrant {
                config_json: grant.config_json.clone(),
                ..ToolCapabilityGrant::default()
            },
            "declaring config must leave every other field at the inherit-everything default"
        );
    }

    // ── Protected paths on the store state ───────────────────────────────

    /// The single boolean the dispatch path branches on. A capsule that declared nothing answers
    /// `false`, which is what keeps it from resolving a call at all.
    #[test]
    fn has_protected_paths_is_false_without_a_declaration_and_true_with_one() {
        let dir = tempfile::tempdir().unwrap();
        let workdir = dir.path().to_path_buf();
        let lock_path = workdir.join("murmur.lock");
        let mut state = build_test_state(
            Arc::new(FakeSkillRegistry::new(Vec::new())),
            workdir,
            lock_path,
        );
        assert!(!state.has_protected_paths());
        assert!(state
            .check_protected_paths(&ResolvedCall::Tool {
                tool_name: "writer".to_string(),
                input: r#"{"path":"tests/a","content":"x"}"#.to_string(),
                input_bytes: 34,
            })
            .is_none());

        state.protected_paths = ProtectedPaths::from_declared(&["tests".to_string()]).unwrap();
        assert!(state.has_protected_paths());
        let refusal = state
            .check_protected_paths(&ResolvedCall::Tool {
                tool_name: "writer".to_string(),
                input: r#"{"path":"tests/a","content":"x"}"#.to_string(),
                input_bytes: 34,
            })
            .expect("a declared subtree is checked");
        assert_eq!(refusal.rule, "tests");
        assert_eq!(refusal.path, "tests/a");
    }

    /// A `read_only` entry that cannot be a workdir subtree refuses the launch at lowering, so no
    /// session ever runs against a rule the runtime could not build.
    #[test]
    fn a_malformed_read_only_entry_refuses_before_a_session_exists() {
        for entry in ["/etc", "../outside", "tests/../../outside"] {
            let err = ProtectedPaths::from_declared(&[entry.to_string()])
                .expect_err("staging must refuse");
            assert!(
                matches!(&err, RuntimeError::InvalidReadOnlyPath { path, .. } if path == entry),
                "{entry}: {err}"
            );
        }
    }

    /// A malformed `config:` block fails staging by artifact name, before any component is
    /// instantiated — the same treatment a malformed capability grant beside it gets.
    #[test]
    fn staging_rejects_a_malformed_config_block() {
        let mut grants = HashMap::new();
        let artifact = ArtifactRequest {
            name: "config-echo".to_string(),
            version: "1.0.0".to_string(),
            runtime: ArtifactRuntime::Tool,
            source: None,
            on_overflow: Default::default(),
            capabilities: None,
            config: Some(serde_yaml::from_str("[a, b]").unwrap()),
        };

        let err =
            stage_artifact_grant(&artifact, &narrowing_ceiling(), "test-capsule", &mut grants)
                .expect_err("a sequence must fail staging");
        assert!(matches!(err, RuntimeError::InvalidArtifactConfig { .. }));
        assert!(err.to_string().contains("config-echo"), "{err}");
        assert!(grants.is_empty());
    }

    /// A malformed grant fails staging rather than surfacing as a confusing denial once the
    /// tool is already running.
    #[test]
    fn staging_rejects_an_escaping_filesystem_scope() {
        let mut grants = HashMap::new();
        let artifact = ArtifactRequest {
            name: "escaping-tool".to_string(),
            version: "1.0.0".to_string(),
            runtime: ArtifactRuntime::Tool,
            source: None,
            on_overflow: Default::default(),
            config: None,
            capabilities: Some(murmur_artifact::Capabilities {
                peer_fetch: None,
                network: None,
                filesystem: Some(murmur_artifact::FilesystemCapabilities {
                    scope: Some("../escape".to_string()),
                    workdir_exec: false,
                    read_only: Vec::new(),
                }),
                shell: None,
                spawn: None,
                env: None,
                limits: None,
                resources: None,
                state: None,
                task_io: None,
                conversation: None,
                plan: None,
                containment: None,
            }),
        };

        let err =
            stage_artifact_grant(&artifact, &narrowing_ceiling(), "test-capsule", &mut grants)
                .expect_err("an escaping scope must fail staging");
        assert!(matches!(err, RuntimeError::InvalidFilesystemScope { .. }));
        assert!(grants.is_empty());
    }

    /// The inert-sub-block set is shared with the hook warning: `network`/`filesystem` are
    /// consumed, everything else is reported.
    #[test]
    fn inert_sub_blocks_are_exactly_the_unconsumed_ones() {
        let caps = murmur_artifact::Capabilities {
            peer_fetch: None,
            network: Some(murmur_artifact::NetworkCapabilities {
                allow: Vec::new(),
                unix_sockets: false,
            }),
            filesystem: Some(murmur_artifact::FilesystemCapabilities {
                scope: None,
                workdir_exec: false,
                read_only: Vec::new(),
            }),
            shell: Some(murmur_artifact::ShellCapabilities {
                allow: vec!["bash".to_string()],
                strip_env: None,
                baseline_env: None,
                interpreter_runtime: Vec::new(),
                staged_runtime: Vec::new(),
            }),
            spawn: None,
            env: Some(murmur_artifact::EnvCapabilities { allow: Vec::new() }),
            limits: None,
            resources: None,
            // Declared here precisely to assert its absence from the list below: `state` is a
            // sub-block per-artifact narrowing *does* read, so reporting it as inert would tell
            // an operator their durable store was ignored when it was granted.
            state: Some(murmur_artifact::StateCapabilities { store: None }),
            task_io: None,
            conversation: None,
            plan: None,
            containment: Some(murmur_artifact::ContainmentClass::Sealed),
        };

        assert_eq!(
            inert_capability_sub_blocks(Some(&caps)),
            vec!["shell", "env", "containment"]
        );
        assert!(inert_capability_sub_blocks(None).is_empty());
    }

    // ── End-to-end reopen loop (real Wasmtime hook + real process transport) ──────

    /// Write an executable fake `claude`-dialect CLI that, on each spawn, consumes its
    /// stdin then emits exactly one assistant text turn and a success result — so every
    /// agent-loop attempt burns exactly one turn and returns `Ok`.
    fn write_fake_claude_cli(dir: &Path) -> PathBuf {
        let script = dir.join("claude");
        fs::write(
            &script,
            "#!/bin/sh\ncat > /dev/null\nprintf '%s\\n' '{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"done\"}]}}'\nprintf '%s\\n' '{\"type\":\"result\",\"subtype\":\"success\",\"result\":\"done\"}'\n",
        )
        .unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = fs::metadata(&script).unwrap().permissions();
            perms.set_mode(0o755);
            fs::set_permissions(&script, perms).unwrap();
        }
        script
    }

    /// A current-version (`@0.8.0`, 7-case `hook-output`) `on-task-end` hook double that
    /// returns `reopen-task(reason)` on its first `reopen_limit` invocations (tracked by a
    /// mutable core global that persists across a blocking hook's reused store) and `none`
    /// thereafter. `reopen_limit` large ⇒ "always reopen".
    fn on_task_end_reopen_double(
        engine: &wasmtime::Engine,
        reopen_limit: u32,
        reason: &str,
    ) -> wasmtime::component::Component {
        let reason_len = reason.len();
        let stubs = [
            "on-session-start",
            "on-inference",
            "on-tool-call",
            "on-shell",
            "on-compaction",
            "on-session-end",
        ]
        .iter()
        .map(|n| format!("    (export \"{n}\" (func $noop))"))
        .collect::<Vec<_>>()
        .join("\n");
        let wat = format!(
            r#"(component
  (core module $m
    (memory (export "memory") 1)
    (global $count (mut i32) (i32.const 0))
    (data (i32.const 300) "{reason}")
    (func (export "realloc") (param i32 i32 i32 i32) (result i32) i32.const 512)
    (func (export "ontaskend") (param i32 i32 i32 i32) (result i32)
      (i32.store (i32.const 128) (i32.const 0))
      (if (result i32) (i32.lt_u (global.get $count) (i32.const {reopen_limit}))
        (then
          (global.set $count (i32.add (global.get $count) (i32.const 1)))
          (i32.store (i32.const 132) (i32.const 4))
          (i32.store (i32.const 136) (i32.const 300))
          (i32.store (i32.const 140) (i32.const {reason_len}))
          (i32.const 128))
        (else
          (i32.store (i32.const 132) (i32.const 0))
          (i32.const 128))))
    (func (export "noop"))
  )
  (core instance $i (instantiate $m))
  (alias core export $i "memory" (core memory $mem))
  (alias core export $i "realloc" (core func $realloc))

  (type $message (record
    (field "role" string)
    (field "content" string)
    (field "id" (option string))
    (field "source-id" (option string))))
  (type $tool-manifest (record (field "binary-name" string) (field "content" string)))
  (type $hook-output (variant
    (case "none")
    (case "replace-context" (list $message))
    (case "write-manifests" (list $tool-manifest))
    (case "artifact" string)
    (case "reopen-task" string)
    (case "seed-context" (list $message))
    (case "deny" string)))
  (type $task-end-event (record
    (field "task-id" string)
    (field "exit-status" string)))
  (type $ft (func (param "event" $task-end-event) (result (result $hook-output (error string)))))

  (func $te (type $ft)
    (canon lift (core func $i "ontaskend") (memory $mem) (realloc $realloc) string-encoding=utf8))
  (func $noop (canon lift (core func $i "noop")))

  (instance $lc
    (export "message" (type $message))
    (export "tool-manifest" (type $tool-manifest))
    (export "hook-output" (type $hook-output))
    (export "task-end-event" (type $task-end-event))
    (export "on-task-end" (func $te))
{stubs}
  )
  (export "murmur:hook/lifecycle@0.8.0" (instance $lc))
)"#
        );
        let bytes = wat::parse_str(&wat).expect("on-task-end reopen double WAT parses");
        wasmtime::component::Component::new(engine, &bytes)
            .expect("on-task-end reopen double compiles")
    }

    /// Drive `run_task_with_reopens` once, with a real process-transport agent loop (fake
    /// `claude` CLI, one turn per attempt) and a real Wasmtime `on-task-end` hook that
    /// reopens `reopen_limit` times. Returns the task result and the parsed `trace.jsonl`.
    async fn run_reopen_scenario(
        reopen_limit: u32,
        max_task_reopens: u32,
        max_turns: u32,
    ) -> (Result<(), RuntimeError>, Vec<serde_json::Value>) {
        let dir = tempfile::tempdir().unwrap();
        let workdir = dir.path().to_path_buf();
        fs::create_dir_all(workdir.join("tools")).unwrap();
        fs::write(workdir.join("task.md"), "Original task: build the thing.").unwrap();
        let cli = write_fake_claude_cli(dir.path());

        let inference = InferenceConfig {
            transport: "process".into(),
            endpoint: None,
            model: "test-model".into(),
            api_key: None,
            driver: None,
            command: Some(cli.to_string_lossy().to_string()),
            compaction: None,
            system_prompt: None,
            system_prompt_file: None,
            system_prompt_artifact: None,
            max_turns,
            max_tokens: None,
            max_session_tokens: None,
        };

        let mut state = build_test_state(
            Arc::new(FakeSkillRegistry::new(Vec::new())),
            workdir.clone(),
            workdir.join("murmur.lock"),
        );

        let mut trace = TraceWriter::open(
            &workdir,
            "ses_test".to_string(),
            "cap".to_string(),
            "0.1.0".to_string(),
            "test-model".to_string(),
            Vec::new(),
            crate::containment::scope_report_for_tier(
                &CapabilityPolicy::default(),
                murmur_artifact::ContainmentClass::Advisory,
                sandbox::EnforcementTier::EnvironmentOnly,
                None,
                None,
                None,
                Vec::new(),
                Vec::new(),
                Vec::new(),
                crate::cgroup::IoMaxReport::default(),
            ),
            murmur_artifact::TraceCapture::Meta,
            None,
            false,
            None,
            None,
            None,
            None,
        )
        .await
        .unwrap();

        let mut otel = OtelEmitter::new(None, &workdir, "cap".to_string(), "0.1.0".to_string());

        let staged_hook = StagedHookArtifact {
            name: "gatekeeper".to_string(),
            version: "0.0.1".to_string(),
            component: on_task_end_reopen_double(&state.engine, reopen_limit, "tests still fail"),
            config: murmur_artifact::HookConfig {
                binding: HookBinding::OnTaskEnd,
                execution_mode: murmur_artifact::HookExecutionMode::Blocking,
                commit_policy: murmur_artifact::HookCommitPolicy::ReopenTask,
            },
            grant: HookCapabilityGrant::default(),
            on_overflow: Default::default(),
        };

        let mut hooks = HookRuntime::new(
            &state.engine,
            &workdir,
            &workdir,
            vec![staged_hook],
            SessionContextData {
                capsule_name: "cap".to_string(),
                capsule_version: "0.1.0".to_string(),
                session_id: "ses_test".to_string(),
                model: "test-model".to_string(),
                capabilities: Vec::new(),
            },
            HookEnvVars::default(),
            crate::limits::ExecutionLimits::default(),
            None,
            None,
        )
        .await
        .unwrap();

        let run_config = agent::AgentRunConfig {
            context_window: 0,
            compaction_threshold: 0.98,
            compaction_model: None,
            compaction_system_prompt: None,
            compaction_dump_summaries: false,
            max_output_tokens: 1024,
            seed_budget: murmur_artifact::DEFAULT_SEED_BUDGET,
            seed_overflow_margin: murmur_artifact::DEFAULT_SEED_OVERFLOW_MARGIN,
            conversation_root: None,
            record_owner: None,
            resume: None,
        };

        // Caller resets per-task counters via write_task_start before the reopen loop.
        trace
            .write_task_start(
                "tsk_1",
                "ctx_1",
                "task_md",
                TaskProvenance::derive(TaskOrigin::User, None),
                None,
                8,
            )
            .await
            .unwrap();

        let result = run_task_with_reopens(
            &mut state,
            &workdir,
            &inference,
            max_task_reopens,
            None,
            run_config,
            &mut hooks,
            &mut trace,
            &mut otel,
            None,
            None,
            &workdir,
            "cap",
            "0.1.0",
            ConversationMode::Stateless,
            Some("ctx_1".to_string()),
            "tsk_1",
            None,
            None,
        )
        .await;

        trace.flush().await.unwrap();
        let content = fs::read_to_string(workdir.join("trace.jsonl")).unwrap();
        let events: Vec<serde_json::Value> = content
            .lines()
            .filter(|l| !l.is_empty())
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();
        (result.map(|_| ()), events)
    }

    // ── murmur:task-io/read end to end ────────────────────────────────────────

    use crate::task_io_import::test_support::{reader_double, REPORT_SEP};

    /// A `claude` CLI double that emits a different result sentinel on each invocation,
    /// counted through a file next to the script. A reopened task runs the agent loop more
    /// than once, and telling attempt 2's output from attempt 1's is the whole point of
    /// clearing the slot at attempt start.
    fn write_counting_fake_claude_cli(dir: &Path) -> PathBuf {
        let script = dir.join("claude-counting");
        let counter = dir.join("attempt-counter");
        fs::write(
            &script,
            format!(
                "#!/bin/sh\ncat > /dev/null\nn=$(cat '{c}' 2>/dev/null || echo 0)\n\
                 n=$((n+1))\necho \"$n\" > '{c}'\n\
                 printf '%s\\n' \"{{\\\"type\\\":\\\"assistant\\\",\\\"message\\\":\
                 {{\\\"content\\\":[{{\\\"type\\\":\\\"text\\\",\\\"text\\\":\
                 \\\"RESULT-$n\\\"}}]}}}}\"\n\
                 printf '%s\\n' \"{{\\\"type\\\":\\\"result\\\",\\\"subtype\\\":\
                 \\\"success\\\",\\\"result\\\":\\\"RESULT-$n\\\"}}\"\n",
                c = counter.display()
            ),
        )
        .unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = fs::metadata(&script).unwrap().permissions();
            perms.set_mode(0o755);
            fs::set_permissions(&script, perms).unwrap();
        }
        script
    }

    /// The task text every task-io scenario starts from — a sentinel a hook can only have
    /// obtained through the import, since the hook holds no filesystem scope.
    const TASK_SENTINEL: &str = "TASK-SENTINEL: build the thing.";

    /// Drive `run_task_with_reopens` end to end with the `murmur:task-io/read` reader double
    /// as the `on-task-end` hook, on either transport.
    ///
    /// The hook's grant is task-io only: no network rules, no filesystem scope. Everything it
    /// reports in its `reopen-task` reason therefore came through the import. Returns the
    /// task result and the parsed `trace.jsonl`.
    async fn run_task_io_scenario(
        transport: &str,
        task_io_read: bool,
        max_task_reopens: u32,
    ) -> (Result<(), RuntimeError>, Vec<serde_json::Value>) {
        let dir = tempfile::tempdir().unwrap();
        let workdir = dir.path().to_path_buf();
        fs::create_dir_all(workdir.join("tools")).unwrap();
        fs::write(workdir.join("task.md"), TASK_SENTINEL).unwrap();

        let mut state = build_test_state(
            Arc::new(FakeSkillRegistry::new(Vec::new())),
            workdir.clone(),
            workdir.join("murmur.lock"),
        );

        let inference = if transport == "process" {
            let cli = write_counting_fake_claude_cli(dir.path());
            InferenceConfig {
                transport: "process".into(),
                command: Some(cli.to_string_lossy().to_string()),
                driver: None,
                ..task_io_inference_config()
            }
        } else {
            // The http transport dispatches a WASM driver component out of `tools/<name>`;
            // the directory's existence is what `run_agent_loop` checks before instantiating.
            fs::create_dir_all(workdir.join("tools").join("mock-driver")).unwrap();
            state.tool_components.insert(
                "mock-driver".to_string(),
                crate::inference_import::test_support::driver_double(
                    &state.engine,
                    0,
                    r#"{"stop_reason":"end_turn","content":[{"type":"text","text":"RESULT-1"}]}"#,
                ),
            );
            InferenceConfig {
                transport: "http".into(),
                command: None,
                driver: Some(murmur_artifact::InferenceDriver {
                    artifact: "mock-driver".to_string(),
                    config: None,
                }),
                ..task_io_inference_config()
            }
        };

        let mut trace = TraceWriter::open(
            &workdir,
            "ses_test".to_string(),
            "cap".to_string(),
            "0.1.0".to_string(),
            "test-model".to_string(),
            Vec::new(),
            crate::containment::scope_report_for_tier(
                &CapabilityPolicy::default(),
                murmur_artifact::ContainmentClass::Advisory,
                sandbox::EnforcementTier::EnvironmentOnly,
                None,
                None,
                None,
                Vec::new(),
                Vec::new(),
                Vec::new(),
                crate::cgroup::IoMaxReport::default(),
            ),
            murmur_artifact::TraceCapture::Meta,
            None,
            false,
            None,
            None,
            None,
            None,
        )
        .await
        .unwrap();
        let mut otel = OtelEmitter::new(None, &workdir, "cap".to_string(), "0.1.0".to_string());

        let staged_hook = StagedHookArtifact {
            name: "gatekeeper".to_string(),
            version: "0.0.1".to_string(),
            component: reader_double(&state.engine),
            config: murmur_artifact::HookConfig {
                binding: HookBinding::OnTaskEnd,
                execution_mode: murmur_artifact::HookExecutionMode::Blocking,
                commit_policy: murmur_artifact::HookCommitPolicy::ReopenTask,
            },
            grant: crate::network_policy::HookCapabilityGrant {
                network_allow_rules: Vec::new(),
                filesystem_scope: None,
                task_io_read,
                conversation_read: false,
                state_store: None,
                state_dir: None,
                config_json: None,
            },
            on_overflow: Default::default(),
        };

        let mut hooks = HookRuntime::new(
            &state.engine,
            &workdir,
            &workdir,
            vec![staged_hook],
            SessionContextData {
                capsule_name: "cap".to_string(),
                capsule_version: "0.1.0".to_string(),
                session_id: "ses_test".to_string(),
                model: "test-model".to_string(),
                capabilities: Vec::new(),
            },
            HookEnvVars::default(),
            crate::limits::ExecutionLimits::default(),
            None,
            None,
        )
        .await
        .unwrap();

        let run_config = agent::AgentRunConfig {
            context_window: 0,
            compaction_threshold: 0.98,
            compaction_model: None,
            compaction_system_prompt: None,
            compaction_dump_summaries: false,
            max_output_tokens: 1024,
            seed_budget: murmur_artifact::DEFAULT_SEED_BUDGET,
            seed_overflow_margin: murmur_artifact::DEFAULT_SEED_OVERFLOW_MARGIN,
            conversation_root: None,
            record_owner: None,
            resume: None,
        };

        trace
            .write_task_start(
                "tsk_1",
                "ctx_1",
                "task_md",
                TaskProvenance::derive(TaskOrigin::User, None),
                None,
                8,
            )
            .await
            .unwrap();

        let result = run_task_with_reopens(
            &mut state,
            &workdir,
            &inference,
            max_task_reopens,
            None,
            run_config,
            &mut hooks,
            &mut trace,
            &mut otel,
            None,
            None,
            &workdir,
            "cap",
            "0.1.0",
            ConversationMode::Stateless,
            Some("ctx_1".to_string()),
            "tsk_1",
            None,
            None,
        )
        .await;

        trace.flush().await.unwrap();
        let content = fs::read_to_string(workdir.join("trace.jsonl")).unwrap();
        let events: Vec<serde_json::Value> = content
            .lines()
            .filter(|l| !l.is_empty())
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();
        (result.map(|_| ()), events)
    }

    /// The fields both transports share in [`run_task_io_scenario`].
    fn task_io_inference_config() -> InferenceConfig {
        InferenceConfig {
            transport: String::new(),
            endpoint: None,
            model: "test-model".into(),
            api_key: None,
            driver: None,
            command: None,
            compaction: None,
            system_prompt: None,
            system_prompt_file: None,
            system_prompt_artifact: None,
            max_turns: 10,
            max_tokens: None,
            max_session_tokens: None,
        }
    }

    /// Every `task_reopened` reason in `events`, in order, split into the reader double's
    /// five fields `[A, O, R, LI, LO]`.
    ///
    /// Split from the right: a reopened attempt's `as-given` is the task text plus the
    /// previous attempt's report injected as feedback, separators and all, so only the four
    /// trailing fields are positionally fixed. Everything before them is field `A`.
    fn reopen_reports(events: &[serde_json::Value]) -> Vec<Vec<String>> {
        events
            .iter()
            .filter(|e| e["event_type"] == "task_reopened")
            .map(|e| {
                let mut fields: Vec<String> = e["reason"]
                    .as_str()
                    .unwrap()
                    .rsplitn(5, REPORT_SEP)
                    .map(str::to_string)
                    .collect();
                fields.reverse();
                fields
            })
            .collect()
    }

    /// The shippable outcome: a hook with no filesystem grant and no network grant, granted
    /// only `task_io.read`, reads the task it was given and the result the agent produced at
    /// `on-task-end` and returns both in its `reopen-task` reason.
    #[tokio::test(flavor = "multi_thread")]
    async fn granted_hook_reads_task_and_result_over_the_process_transport() {
        let (_, events) = run_task_io_scenario("process", true, 1).await;
        assert_eq!(
            reopen_reports(&events),
            vec![vec![
                format!("A={TASK_SENTINEL}"),
                format!("O={TASK_SENTINEL}"),
                "R=RESULT-1".to_string(),
                format!("LI={}", TASK_SENTINEL.len()),
                "LO=8".to_string(),
            ]],
            "the hook holds no filesystem scope, so neither sentinel could have come from disk"
        );
    }

    /// Transport parity: the same hook and the same scenario through the WASM-driver loop in
    /// `agent.rs` rather than the subprocess loop in `agent/process.rs`. Each transport funnels
    /// its result-text write through its own recorder, so each transport's own result is what
    /// the hook reads.
    #[tokio::test(flavor = "multi_thread")]
    async fn granted_hook_reads_task_and_result_over_the_http_transport() {
        let (_, events) = run_task_io_scenario("http", true, 1).await;
        assert_eq!(
            reopen_reports(&events),
            vec![vec![
                format!("A={TASK_SENTINEL}"),
                format!("O={TASK_SENTINEL}"),
                "R=RESULT-1".to_string(),
                format!("LI={}", TASK_SENTINEL.len()),
                "LO=8".to_string(),
            ]]
        );
    }

    /// Default-deny end to end: the same double under a grant with `task_io_read: false` still
    /// instantiates, is still dispatched, and still drives a reopen — its reason just carries
    /// the `not-granted` marker instead of either sentinel. The session is not aborted.
    #[tokio::test(flavor = "multi_thread")]
    async fn an_ungranted_hook_reads_nothing_end_to_end() {
        let (_, events) = run_task_io_scenario("process", false, 1).await;
        let reports = reopen_reports(&events);
        assert_eq!(
            reports,
            vec![vec!["A=!0", "O=!0", "R=!0", "LI=!0", "LO=!0"]],
            "every read is not-granted, and no length leaks either"
        );
    }

    /// Reopen semantics across three attempts. `original` is byte-identical on every attempt;
    /// `as-given` picks up the `# Reopen feedback` section `build_reopen_task_md` writes; and
    /// the output read on attempt N is attempt N's own result, never attempt N-1's.
    #[tokio::test(flavor = "multi_thread")]
    async fn reopened_attempts_see_their_own_input_and_their_own_output() {
        let (result, events) = run_task_io_scenario("process", true, 2).await;
        assert!(
            result.is_err(),
            "the reader double always reopens, so the budget runs out"
        );
        let reports = reopen_reports(&events);
        assert_eq!(reports.len(), 2, "max_task_reopens: 2 ⇒ two reopens");

        for (index, report) in reports.iter().enumerate() {
            assert_eq!(
                report[1],
                format!("O={TASK_SENTINEL}"),
                "`original` never changes across attempts"
            );
            assert_eq!(
                report[2],
                format!("R=RESULT-{}", index + 1),
                "attempt {} must read its own result, never the previous attempt's",
                index + 1
            );
        }

        assert_eq!(
            reports[0][0],
            format!("A={TASK_SENTINEL}"),
            "attempt 1 was handed the pristine task"
        );
        let attempt_two_input = &reports[1][0];
        assert!(
            attempt_two_input.starts_with(&format!("A={TASK_SENTINEL}"))
                && attempt_two_input.contains("# Reopen feedback"),
            "attempt 2's `as-given` is the pristine task plus the injected feedback, got: \
             {attempt_two_input}"
        );
        assert_eq!(
            reports[1][3],
            format!("LI={}", attempt_two_input.len() - "A=".len()),
            "input-len reports the byte length of the very text read back"
        );
    }

    fn count_type(events: &[serde_json::Value], ty: &str) -> usize {
        events.iter().filter(|e| e["event_type"] == ty).count()
    }

    /// Happy path: one reopen, then the hook is satisfied. The agent loop runs twice, one
    /// `task_reopened` sits between the attempts naming the hook and its feedback, and the
    /// terminal `task_end` shows `reopen_count: 1` with the second attempt's real outcome.
    #[tokio::test(flavor = "multi_thread")]
    async fn reopen_once_then_satisfied_end_to_end() {
        let (result, events) = run_reopen_scenario(1, 5, 10).await;
        assert!(
            result.is_ok(),
            "a satisfied hook ends the task Ok: {result:?}"
        );
        assert_eq!(
            count_type(&events, "inference"),
            2,
            "agent loop ran exactly twice"
        );
        assert_eq!(count_type(&events, "task_reopened"), 1);
        let re = events
            .iter()
            .find(|e| e["event_type"] == "task_reopened")
            .unwrap();
        assert_eq!(re["hook_name"], "gatekeeper");
        assert_eq!(re["reason"], "tests still fail");
        assert_eq!(re["reopen_number"], 1);
        let end = events
            .iter()
            .find(|e| e["event_type"] == "task_end")
            .unwrap();
        assert_eq!(end["reopen_count"], 1);
        assert_eq!(end["exit_status"], "ok");
    }

    /// Budget exhausted: a hook that always reopens with `lifecycle.max_task_reopens: 1` runs
    /// the loop exactly twice, then ends `reopen_budget_exhausted` (an `Err`, so downstream
    /// task-failure branches fire) with `reopen_count: 1`.
    #[tokio::test(flavor = "multi_thread")]
    async fn reopen_budget_exhausted_end_to_end() {
        let (result, events) = run_reopen_scenario(99, 1, 10).await;
        assert!(
            result.is_err(),
            "an exhausted reopen budget is a task failure"
        );
        assert_eq!(count_type(&events, "inference"), 2, "1 original + 1 reopen");
        assert_eq!(count_type(&events, "task_reopened"), 1);
        let end = events
            .iter()
            .find(|e| e["event_type"] == "task_end")
            .unwrap();
        assert_eq!(end["reopen_count"], 1);
        assert_eq!(end["exit_status"], "reopen_budget_exhausted");
    }

    /// Turn ceiling respected: `inference.max_turns: 3`, `lifecycle.max_task_reopens: 5`, a
    /// hook that always reopens, one turn per attempt. Cumulative `inference` records never
    /// exceed 3, and the task ends `reopen_budget_exhausted` once turns run out even though
    /// reopens remain in the budget.
    #[tokio::test(flavor = "multi_thread")]
    async fn reopen_never_exceeds_max_turns_end_to_end() {
        let (result, events) = run_reopen_scenario(99, 5, 3).await;
        assert!(result.is_err());
        assert_eq!(
            count_type(&events, "inference"),
            3,
            "cumulative turns must never exceed max_turns"
        );
        assert_eq!(
            count_type(&events, "task_reopened"),
            2,
            "3 attempts ⇒ 2 reopens"
        );
        let end = events
            .iter()
            .find(|e| e["event_type"] == "task_end")
            .unwrap();
        assert_eq!(end["reopen_count"], 2);
        assert_eq!(end["exit_status"], "reopen_budget_exhausted");
    }
}